react-semaphor 0.0.633 → 0.0.634

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.
@@ -345,11 +345,11 @@
345
345
  ${d?`Python:
346
346
  ${d}`:""}
347
347
  `;N(z)}function M(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(tr,{jsonString:JSON.stringify(u,null,2)})})}),u&&u.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(er,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(sr,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function W(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:T||y,onClick:()=>{L()},className:"h-8 shrink-0",size:"sm",children:[T||y?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(St,{errorSql:w,sql:v==null?void 0:v.sql,error:F,onDebugWithAssistant:R}),e.jsx(os,{}),e.jsx(s.Toggle,{pressed:n,onPressedChange:z=>a(z),className:"h-8",size:"sm",variant:"outline",children:e.jsx(Zn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{k(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{}),e.jsx(ks,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),M()]}),W()]})}const rr=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:rs}];function lr({className:t}){const n=s.useEditorStore(d=>d.card),{setCardType:a,setCard:r,updateCardInFrame:o}=s.useEditorActions(),l=["table","aggregateTable","pivotTable"].includes(n.type),c=s.hasValidCardConfig(n.config);if(!l||!c)return null;const i=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=n.config)!=null&&m.pivotByColumns)&&n.config.pivotByColumns.length>0){const h={...n,type:u,config:{...n.config,pivotByColumns:[]}};r(h),o(h)}else{a(u);const h={...n,type:u};o(h)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:n.type,onValueChange:i,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:rr.map(d=>{const u=d.icon,m=n.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function or({card:t}){var N,k,I,S,C,v,T,y,O,E,B;const[n,a]=A.useState(!1),[r,o]=A.useState([]),{authToken:l}=s.useSemaphorContext(),c=s.getTokenParams(l==null?void 0:l.accessToken),i=s.useDashboardStore(w=>w.themeStyle),d={colors:((k=(N=i==null?void 0:i.chart)==null?void 0:N.dataset)==null?void 0:k.backgroundColor)||[]};(I=t.customCardPreferences)!=null&&I.inputData;const{getCard:u}=s.useCustomVisual(((S=t.customCardPreferences)==null?void 0:S.url)||""),m=((C=t.customCardPreferences)==null?void 0:C.visualType)||"single",h=s.useEditorStore(w=>w.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:g}=s.useDashboardCardQuery(t),j=A.useCallback((w,D)=>{o(L=>({...L,[w]:D}))},[]);if(!((v=t.customCardPreferences)!=null&&v.componentName))return null;const x=u((T=t.customCardPreferences)==null?void 0:T.componentName);function b(w){a(w)}const f=Object.keys(((y=t.customCardPreferences)==null?void 0:y.dataInputCardIds)||{}).map(w=>{var F,R,M;const D=(R=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:R[w].cardId,L=(M=h==null?void 0:h.cards)==null?void 0:M.find(P=>P.id===D);return L||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(A.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[x&&m==="single"&&e.jsx(x,{editing:!0,params:c,theme:d,settings:(O=t.customCardPreferences)==null?void 0:O.settings,onDataChange:j,data:(g==null?void 0:g.records)||[]}),x&&m==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((E=t.customCardPreferences)==null?void 0:E.dataInputCardIds)||{}).map(w=>{var F,R,M;const D=(R=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:R[w].cardId,L=(M=h==null?void 0:h.cards)==null?void 0:M.find(P=>P.id===D);if(L)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:b,onDataChange:j,dataInputIndex:w,card:L},L.id+w)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(x,{theme:d,onDataChange:j,settings:f.map(w=>{var D;return(D=w==null?void 0:w.customCardPreferences)==null?void 0:D.settings}),data:f.map(w=>w!=null&&w.id?r==null?void 0:r[w.id]:[])})})]})]},(B=t.customCardPreferences)==null?void 0:B.componentName)})}function Dt({className:t,...n}){var T;const a=s.useEditorStore(y=>y.card),r=s.isExplorerCard(a),o=((T=a.customCardPreferences)==null?void 0:T.showCardHeader)??!0,l=s.useEditorStore(y=>y.frame),c=s.useDashboardStore(y=>y.dashboard.filters),i=s.useEditorStore(y=>y.actions.setRunSql),{updateFilter:d}=s.useDashboardActions(),u=c==null?void 0:c.find(y=>y.id===l.filterId),{data:m,isLoading:h,isFetching:p,errorMessage:g,pagination:j}=s.useDashboardCardQuery(a),{setCard:x,updateCardInFrame:b}=s.useEditorActions(),{data:f}=s.useTopoJson(a),N=A.useMemo(()=>{var y;return a.type!=="pivotTable"||!((y=m==null?void 0:m.records)!=null&&y.length)?null:{records:m.records,columnSubtotalMeta:m.columnSubtotalMeta,subtotalColumns:m.subtotalColumns||[],pivotSchema:m.pivotSchema||[],groupByColumns:m.groupByColumns}},[a.type,m==null?void 0:m.records,m==null?void 0:m.columnSubtotalMeta,m==null?void 0:m.subtotalColumns,m==null?void 0:m.pivotSchema,m==null?void 0:m.groupByColumns]),k=s.usePivotTableConfig(a,N),I=(y,O)=>{var B,w;const E={...a,paginationConfig:{page:y+1,pageSize:O}};x(E),b(E),a.sql&&((w=(B=a.preferences)==null?void 0:B.tablePrefs)!=null&&w.enableDevModePagination)&&i(!0)},S=A.useMemo(()=>!a.id||!(m!=null&&m.records)?null:s.createChartConfig({card:a,data:m==null?void 0:m.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:f}),[a.id,m==null?void 0:m.records,a.type,a.queryConfig,a.customCfg,a.preferences,f]);function C(y){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(or,{card:y})})}function v(){if(m!=null&&m.records&&(m==null?void 0:m.records.length)===0&&!h&&!p)return g?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?"Error fetching data. Please check your chart configuration":"Error fetching data. Please check your SQL or Python code."})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((h||p)&&a.type!=="table")return e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!a.id)return null;if(a.type==="custom")return C(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&S)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:h||p?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:S})});if(a.type==="table")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:a,data:(m==null?void 0:m.records)||[],paginationMetadata:j,onPaginationChange:I,isLoading:h||p})});if(a.type==="pivotTable"&&k)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:a,data:k.data,options:k.options,onAggregationChange:y=>{const O=s.handleAggregationChange(y,a.config),E={...a,config:O};x(E),b(E)},onAggregationLabelChange:y=>{const O=s.handleAggregationLabelChange(y,a.config),E={...a,config:O};x(E),b(E)}})});if(a.type==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:a,data:(m==null?void 0:m.records)||[],groupByColumns:m==null?void 0:m.groupByColumns,pivotSchema:m==null?void 0:m.pivotSchema,paginationMetadata:j,onPaginationChange:I,onAggregationChange:y=>{const O=s.handleAggregationChange(y,a.config),E={...a,config:O};x(E),b(E)},isLoading:h||p})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[o&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-5",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:y=>x({...a,title:y}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(lr,{})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:y=>x({...a,description:y}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),u&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:u.title||u.column,onSave:y=>d({...u,title:y}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:u})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:v()})]})}const ps=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),ir=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),cr=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:o})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(ps,{language:"javascript",value:t,onChange:o})})]}),dr=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:o})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:o,variant:"outline",children:"Close"})]});function ur(){const[t,n]=A.useState(!1),[a,r]=A.useState(""),[o,l]=A.useState(""),[c,i]=A.useState(""),[d,u]=A.useState(""),m=s.useEditorStore(S=>S.card),h=s.useEditorStore(S=>S.card.customCfg),p=h?JSON.stringify(h,null,2):"",{data:g}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:x,setCustomVisualCode:b}=s.useEditorActions(),f=S=>{var C,v;return JSON.stringify({...S,data:{...S.data,datasets:(v=(C=S.data)==null?void 0:C.datasets)==null?void 0:v.map(T=>({...T,data:[]}))}},null,2)},N=()=>{var C,v;if(!((C=g==null?void 0:g.records)!=null&&C.length))return;const S=s.createChartConfig({card:m,data:g.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(S){r(f(S)),i(((v=m.preferences)==null?void 0:v.customVisualCode)||"");const T=s.merge(S,h);l(f(T))}},k=()=>{try{if(c&&b(c),o){const S=JSON.parse(o),C=s.getObjectDiff(JSON.parse(a),S);x(C),u("")}}catch{u("Invalid JSON configuration")}},I=Object.keys(h||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:N,className:I?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(ir,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Dt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(cr,{customCode:c,cardCustomCfgString:p,mergedConfig:o,onConfigChange:S=>l(S??""),onCodeChange:S=>i(S??"")})]}),e.jsx(dr,{error:d,hasCardCustomConfig:!!h,onReset:()=>{l(a),x(null)},onApply:k,onClose:()=>n(!1)})]})]})}function is(t){const[n,a]=A.useState(null);return n}function Tt(){const{authToken:t}=s.useSemaphorContext(),{data:n,isLoading:a,isFetching:r,isError:o}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(t==null?void 0:t.accessToken)});return{data:n,isLoading:a,isFetching:r,isError:o}}function kt(){const{data:t,isLoading:n,isError:a}=Tt(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),o=[];let l=n,c=a;return r.forEach((i,d)=>{var u;if(i.isLoading&&(l=!0),i.isError&&(c=!0),i.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],h=i.data.visuals.map(p=>({name:p.name,pluginName:m.label,componentType:p.componentType,pluginType:m.type,icon:p.icon,chartType:p.chartType,url:m.value}));o.push(...h)}}),{data:o,isLoading:l,isError:c}}function mr({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:o}=s.useEditorActions(),{data:l,isLoading:c,isError:i}=kt(),d=A.useCallback((u,m)=>{n(null),a({}),r(u),m&&o({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[n,a,r,o,t]);return c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading custom visuals..."})})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:e.jsx("div",{className:"text-sm text-destructive",children:"Failed to load custom visuals"})})]}):!l||l.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:l.map((u,m)=>e.jsx(hr,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const hr=({text:t,icon:n,onClick:a})=>{const r=is(),o=t.charAt(0).toUpperCase();return e.jsx(s.IconButton,{onClick:a,tooltip:t,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function Et({onChartTypeChange:t,iconClassName:n}){const{setCardType:a,setCardPreferences:r,setIsDevMode:o}=s.useEditorStore(m=>m.actions),{setCardCustomCfg:l,setCustomCardPreferences:c,setQueryConfig:i}=s.useEditorActions();function d(m,h){l(null),r({}),a(m),["custom","text","map"].includes(m)&&(o(!0),i(void 0)),t==null||t()}const u=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(s.IconButton,{openDelay:u,tooltip:"Table",onClick:()=>d("table"),className:"h-10 p-4",children:e.jsx(s.Table2,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bar Chart",onClick:()=>d("bar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnIncreasing,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Line Chart",onClick:()=>d("line"),className:"h-10 p-4",children:e.jsx(s.ChartLine,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Bar Chart",onClick:()=>d("stackedBar"),className:"h-10 p-4",children:e.jsx(s.ChartColumnStacked,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Stacked Line Chart",onClick:()=>d("stackedLine"),className:"h-10 p-4",children:e.jsx(s.MdStackedLineChart,{className:s.cn("size-5",n),strokeWidth:0})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Scatter Chart",onClick:()=>d("scatter"),className:"h-10 p-4",children:e.jsx(s.ChartScatter,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Bubble Chart",onClick:()=>d("bubble"),className:"h-10 p-4",children:e.jsx(s.TbChartBubble,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Pie Chart",onClick:()=>d("pie"),className:"h-10 p-4",children:e.jsx(s.ChartPie,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Doughnut Chart",onClick:()=>d("doughnut"),className:"h-10 p-4",children:e.jsx(s.Donut,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Funnel Chart",onClick:()=>d("funnel"),className:"h-10 p-4",children:e.jsx(s.TbChartFunnel,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Radar Chart",onClick:()=>d("radar"),className:"h-10 p-4",children:e.jsx(s.Radar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Polar Area Chart",onClick:()=>d("polarArea"),className:"h-10 p-4",children:e.jsx(s.PiChartPolar,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Tornado Chart",onClick:()=>d("tornado"),className:"h-10 p-4",children:e.jsx(s.Tornado,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Range Chart",onClick:()=>d("range"),className:"h-10 p-4",children:e.jsx(s.ChartNoAxesGantt,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"KPI",onClick:()=>d("kpi"),className:"h-10 p-4",children:e.jsx(s.TiSortNumerically,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Text",onClick:()=>d("text"),className:"h-10 p-4",children:e.jsx(s.BookType,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{tooltip:"Map",onClick:()=>d("map"),className:"h-10 p-4",children:e.jsx(s.Map,{className:s.cn("size-5",n)})}),e.jsx(s.IconButton,{openDelay:u,tooltip:"Custom",onClick:()=>d("custom"),className:"h-10 p-4",children:e.jsx(qe,{className:s.cn("size-5",n)})})]})}function xr({chartType:t,className:n,customIcon:a,componentName:r}){const o=is();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(ve,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&o?e.jsx(o,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(qe,{className:n});default:return e.jsx(s.Table2,{className:n})}}function It({variant:t="ghost"}){var l,c;const[n,a]=A.useState(!1),r=s.useEditorStore(i=>i.card),o=r.type;return s.useDashboardStore(i=>i.isVisualEditing),e.jsxs(s.Popover,{open:n,onOpenChange:a,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(xr,{className:"size-4",chartType:o,customIcon:(l=r.customCardPreferences)==null?void 0:l.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(s.PopoverContentCustom,{onOpenAutoFocus:i=>i.preventDefault(),className:"w-72 p-1",children:[e.jsx(Et,{onChartTypeChange:()=>a(!1)}),e.jsx(mr,{onChartTypeChange:()=>a(!1)})]})]})}function pr({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[o,l]=A.useState(!1),c=A.useRef(null),i=A.useRef(!1);function d(){t&&!i.current&&navigator.clipboard.writeText(t)}function u(p){(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())}function m(){const p=window.getSelection();if(p&&p.toString().trim()!==""){const g=p.toString();navigator.clipboard.writeText(g),l(!0),i.current=!0,setTimeout(()=>{l(!1),i.current=!1},1e3)}else i.current=!1}function h(){l(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:h,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),o&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function fr(){const t=s.useEditorStore(l=>{var c,i;return(i=(c=l.card.preferences)==null?void 0:c.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a}=s.useEditorStore(l=>l.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(Gs,{className:"size-4"}):e.jsx(Vs,{className:"size-4"})})}function o(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Gs,{className:"size-4"}):e.jsx(Vs,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():r()})}function At(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.isShowingVisual),a=s.useEditorStore(c=>{var i,d;return(d=(i=c.card)==null?void 0:i.preferences)==null?void 0:d.chartOptions}),r=s.getChartGridStyle(a),{setChartGrid:o}=s.useEditorActions();function l(){const c=["xy","none","x","y"],d=(c.indexOf(r)+1)%c.length;o(c[d])}return n?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(fr,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:l,children:[(r==="xy"||!r)&&e.jsx(rs,{className:"size-4"}),r==="x"&&e.jsx(ma,{className:"size-4"}),r==="y"&&e.jsx(Pa,{className:"size-4"}),r==="none"&&e.jsx(Ua,{className:"size-4"})]})]}):null}function gr(){const t=s.useEditorStore(j=>j.frame),n=s.useEditorStore(j=>j.card),{setFrame:a,setActiveTabCardId:r,setCard:o,updateCardInFrame:l}=s.useEditorActions(),c=(j,x)=>{j.dataTransfer.setData("tabIndex",x.toString())},i=j=>{j.preventDefault()},d=(j,x)=>{const b=j.dataTransfer.getData("tabIndex");if(b===x.toString())return;const f=Array.from(t.cards),[N]=f.splice(parseInt(b),1);f.splice(x,0,N),a({...t,cards:f})};function u(j){const x=t.cards.filter(N=>N.id!==j),b=x[0],f={...t,cards:x,activeCardId:b.id};a(f),r(b.id),o(b)}function m(j,x){const b={...t,cards:[...t.cards,x],activeCardId:j.id};a(b),r(x.id)}function h(){const j={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};m(n,j)}function p(j){const x={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,x)}function g(j,x){return j.cards.length===1&&(x.displayTab===!0||x.displayTab===void 0)||j.activeCardId!==x.id&&(x.displayTab===!0||x.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const b=x.displayTab===void 0?!1:!x.displayTab;o({...x,displayTab:b}),l({...x,displayTab:b})},children:x.displayTab===!0||x.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(fa,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((j,x)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:b=>c(b,x),onDragOver:i,onDrop:b=>d(b,x),className:"",value:j.id,children:[g(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:b=>{o({...n,tabTitle:b}),l({...n,tabTitle:b})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(j.id)})]},j.id)),e.jsx(s.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>p(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})}),e.jsx(s.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:h,children:e.jsx(xa,{className:"h-4 w-4"})})]})})}function Mt(){const t=s.useEditorStore(x=>x.frame),n=s.useEditorStore(x=>x.card),a=s.useEditorStore(x=>x.isSqlRunning),r=s.useEditorStore(x=>x.isDevMode),{setFrame:o,setActiveTabCardId:l,setCard:c,setIsDevMode:i,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:h}=s.useDashboardCardQuery(n);function p(x){const b=t.cards.find(f=>f.id===x);if(b!=null&&b.sql){r||i(!0),l(x);return}if(b!=null&&b.queryConfig){r&&i(!1),g(x),l(x);return}r||g(x),l(x)}function g(x){const b={...t,cards:t.cards.map(N=>N.id===n.id?n:N),activeCardId:x};o(b);const f=b.cards.find(N=>N.id===x);f.sql&&d(!0),c(f)}function j(){return n.type==="kpi"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:u==null?void 0:u.records,isPending:m||h})})}):n.type==="text"?m||h?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Dt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(x=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:x.id,children:j()},x.id)),e.jsx(gr,{})]})}function Qe({children:t}){var I,S;s.useEditorStore(C=>C.frame);const n=s.useEditorStore(C=>C.card),a=s.useEditorStore(C=>C.isDevMode),r=s.useEditorStore(C=>C.isShowingVisual),o=s.useDashboardStore(C=>C.isVisualEditing),l=s.useEditorStore(C=>C.pythonStdOut);s.useEditorStore(C=>C.actions.setRunSql);const{setFrame:c,setCard:i,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:h}=s.useEditorActions(),{data:p,isLoading:g,isFetching:j,errorMessage:x,refetch:b}=s.useDashboardCardQuery(n);function f(){const C=JSON.stringify(p==null?void 0:p.records,null,2),v=new Blob([C],{type:"application/json"}),T=URL.createObjectURL(v),y=document.createElement("a");y.href=T,y.download=`${n.title}.json`,y.click()}function N(){const v=[Object.keys(p==null?void 0:p.records.reduce((E,B)=>({...E,...B}),{})).join(","),...((p==null?void 0:p.records)||[]).map(E=>Object.values(E).join(","))].join(`
348
- `),T=new Blob([v],{type:"text/csv"}),y=URL.createObjectURL(T),O=document.createElement("a");O.href=y,O.download=`${n.title}.csv`,O.click()}function k(){const C=`Can you get the documentation for ${n.type} chart?`;u(C)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(It,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(oa,{className:"size-4"})}),!["table","custom"].includes(n.type)&&o&&e.jsx(ur,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:N,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(ja,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(At,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((S=(I=n.preferences)==null?void 0:I.tablePrefs)==null?void 0:S.enableDevModePagination)??!1,onCheckedChange:C=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:C}}),b()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(br,{})]}),r?e.jsx(Mt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:l&&e.jsx(jr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":l}),children:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[]}),x&&e.jsx(pr,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function jr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function br(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function vr(){var x,b;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=Tt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),o=s.useEditorStore(f=>f.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,N){if(!t)return;const I={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:I})}function h(f){var k,I;const N=(k=o==null?void 0:o.cards)==null?void 0:k.filter(S=>{var C;return((C=S==null?void 0:S.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(S=>({value:S.id,label:S.tabTitle||S.title}));return e.jsx("div",{className:"space-y-2",children:(I=f==null?void 0:f.dataInputs)==null?void 0:I.map((S,C)=>{var v,T;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:S}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((T=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[C])==null?void 0:T.cardId)||"",onValueChange:y=>m(C,y)})]},C+Math.random())})})}function p(f,N,k=[],I=""){var S,C;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((S=t==null?void 0:t.settings)==null?void 0:S[N])||I,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v.target.value}})}},N):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:k,value:((C=t==null?void 0:t.settings)==null?void 0:C[N])||I,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v}})}}):null:null}function g(f){const N=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([k,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:I.title}),p(I.ui,k,I.options,I.defaultValue)]},k))})}function j(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ce,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===l).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((b=r==null?void 0:r.customCardPreferences)==null?void 0:b.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Fe(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{l&&n(new Array(l.length).fill(!1))},[l]);function c(u,m){var h,p;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?o({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):o({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==u)}),n(g=>{const j=[...g];return j[u]=!1,j}))}function i(u,m){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);o({...a,onClickFilter:h})}function d(u){var m,h,p,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===u))==null?void 0:g.expression,onChange:j=>i(u,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:l==null?void 0:l.map((u,m)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[m]=!g[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function yr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,l=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...l};h.datalabels=m;const p=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(rt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function Nr(){const t=s.useEditorStore(l=>l.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({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("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Lt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",o=n==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=Nr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Rt(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ot,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Rt(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ot({col:t,idx:n,className:a,iconClassName:r,children:o}){const l=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,p;return(p=(h=m.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...l,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...l,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[o||e.jsx(cs,{className:"max-w-[100px]",title:t,children:Rt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(yr,{idx:n})]})]})}function Is(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedTableName),l=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function p(g,j="dashboard",x){var T;const b=s.fmt(g.column_name),f=s.fmt(a||""),N=s.fmt(r||""),k=s.fmt(m);let I=s.getQualifiedTableName({schemaName:N,tableName:k,connectionType:h,databaseName:f}),S=`${I}.${b}`;const C=(T=u==null?void 0:u.find(y=>y.id===n))==null?void 0:T.name;n&&n!=="none"&&(S=`${s.DATAMODEL_NAMESPCACE}.${C}.${b}`,I=`${s.DATAMODEL_NAMESPCACE}.${C}`),x!=null&&x.qualifiedFieldName&&(S=x.qualifiedFieldName),x!=null&&x.entityName&&(I=x.entityName);const v=l==null?void 0:l.find(y=>y.column===S&&y.table===k&&(y.database===f||y.database===a));if(v)d(v.id),i(v.id);else{const y=s.v4();return m==="api"&&t?(c({location:j,id:y,column:S,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),y):(c({id:y,location:j,column:S,title:g.column_name,dataType:g.data_type,table:o||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),y)}}return{assignFilter:p}}function Ue(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=Is();function l(i){const d=o(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Cr,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Cr({columns:t,onSelect:n}){var c;const[a,r]=Ie.useState(!1),[o,l]=Ie.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===o?"":d;l(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Sr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Lt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function wr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function Ft(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?l():c()})}const Dr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Tr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function kr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Er(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{}),e.jsx(Fe,{}),e.jsx(Ue,{})]})]})}function Er(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Dr,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Tr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Ir({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function o(c){const i=[...t];i.splice(c,1),n(i)}function l(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:l,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>o(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Ar(){var m,h,p,g,j;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),o=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.decimalPlaces});const l=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(x=>x.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:l||"none",onValueChange:x=>{var b,f,N;return o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",x,((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:x=>{var b,f,N;console.log("currency",x),o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,x==="none"?"":x,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var b,f,N;return o(Number(x),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var b,f,N;return o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Ir,{colorRanges:i,setColorRanges:d})]})]})}function Mr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Ar,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function fs({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Lr=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Rr=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],Or=Rr.map(t=>({label:t,value:t}));function Fr(){var d,u,m,h,p,g,j,x,b,f,N,k,I,S,C,v,T,y;const t=s.useEditorStore(O=>O.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(fs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),o({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),o({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Lr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Or,value:((f=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(S=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:C[0])||0,onChange:O=>{var E,B,w,D;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionOffset:[Number(O.target.value),((D=(w=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((y=(T=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:y[1])||0,onChange:O=>{var E,B,w,D;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionOffset:[((D=(w=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Fe,{})]})}function Br(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:n}=s.useEditorStore(o=>o.actions);function a(o){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Je({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Br,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function Pr(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Lt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function zr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),a=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{a({...n,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Bt({color:t,onColorChange:n,onClose:a}){const[r,o]=A.useState(0),[l,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const b=qs(t);if(b){const f=Hs(b.r,b.g,b.b);o(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=b=>{o(b),g(b,l,i)},p=b=>{const f=b.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(b.clientX-f.left)/f.width)),k=Math.max(0,Math.min(1,(b.clientY-f.top)/f.height)),I=N*100,S=(1-k)*100;c(I),d(S),g(r,I,S)},g=(b,f,N)=>{const k=Vr(b,f,N),I=_r(k.r,k.g,k.b);m(I)},j=b=>{if(m(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const f=qs(b);if(f){const N=Hs(f.r,f.g,f.b);o(N.h),c(N.s),d(N.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:b=>{b.buttons===1&&p(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${l}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>h(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:b=>j(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function qs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function _r(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Hs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),o=Math.min(t,n,a);let l=0,c=0;const i=(r+o)/2;if(r!==o){const d=r-o;switch(c=i>.5?d/(2-r-o):d/(r+o),r){case t:l=((n-a)/d+(n<a?6:0))/6;break;case n:l=((a-t)/d+2)/6;break;case a:l=((t-n)/d+4)/6;break}}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(i*100)}}function Vr(t,n,a){t/=360,n/=100,a/=100;let r,o,l;if(n===0)r=o=l=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),o=c(d,i,t),l=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(o*255),b:Math.round(l*255)}}const Gr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Pt(){var k,I,S,C,v,T,y,O,E,B;const t=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>{var D;return(D=w.card)==null?void 0:D.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:o}=s.useDashboardCardQuery(t),[l,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var F,R,M,P,W,z,X;if(!(o!=null&&o.records)||o.records.length===0)return[];const w=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",D=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",L=((F=t==null?void 0:t.config)==null?void 0:F.pivotByColumns)&&t.config.pivotByColumns.length>0;if((w||D)&&L){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const te=new Set;return o.pivotSchema.forEach(K=>{K.alias&&te.add(K.alias)}),Array.from(te)}if(o.records.length>0){const te=o.records[0],K=Object.keys(te),H=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(_=>{H.add(_.label||_.name),H.add(_.alias||_.name)});const U=new Set;return(M=t==null?void 0:t.config)!=null&&M.metricColumns&&t.config.metricColumns.forEach(_=>{const V=_.alias||_.name;U.add(V),U.add(`${V}_count`),U.add(`${V}_sum`),U.add(`${V}_avg`),U.add(`${V}_min`),U.add(`${V}_max`);const se=_.entityName||_.qualifiedEntityName;se&&(U.add(`${se}_${V}`),U.add(`${se}_${V}_count`))}),K.filter(_=>!H.has(_)&&!U.has(_))}}if((D||w)&&!L&&((W=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&W.length))return t.config.metricColumns.map(te=>te.alias||te.label||te.name);if((X=(z=t==null?void 0:t.config)==null?void 0:z.groupByColumns)!=null&&X.length){const te=t.config.groupByColumns[0],K=te.label||te.name,H=new Set;return o.records.forEach(U=>{const ee=U[K];ee!=null&&H.add(String(ee))}),Array.from(H)}return[]},[o,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns,(S=t==null?void 0:t.config)==null?void 0:S.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const w={};h.forEach((D,L)=>{w[D]=s.getColorForValue(D,L,n==null?void 0:n.colorConfig)}),c(w)},[h,n==null?void 0:n.colorConfig,p]);const g=(w,D)=>{const L={...l,[w]:D};c(L);const F={...n||{},colorConfig:{segments:L}};a(F);const R={...t,preferences:F};r(R)},j=(w,D)=>{var W;const L=p[D%p.length],{[w]:F,...R}=((W=n==null?void 0:n.colorConfig)==null?void 0:W.segments)||{},M={...n||{},colorConfig:{segments:R}};a(M);const P={...t,preferences:M};r(P),c(z=>({...z,[w]:L}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:v.length)||((y=(T=t==null?void 0:t.config)==null?void 0:T.pivotByColumns)==null?void 0:y.length):(E=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:E.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const w={...n||{},colorConfig:{segments:{}}};a(w);const D={...t,preferences:w};r(D);const L={};h.forEach((F,R)=>{L[F]=s.getColorForValue(F,R,void 0)}),c(L)},N=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",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(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((w,D)=>{const L=s.isDefaultColor(l[w],D),F=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===w,onOpenChange:R=>d(R?w:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:l[w]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((R,M)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",l[w]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{g(w,R),d(null)},children:[M===D%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${M}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Gr.map((R,M)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",l[w]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{g(w,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${M}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:w,color:l[w]}),d(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(w,D),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:w}),F&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},w)})}),u&&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:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Bt,{color:u.color,onColorChange:w=>{g(u.value,w),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:o=""}){const[l,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Ur=["auto","number","currency","percent","scientific","date"],Yr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],$r=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],qr=t=>t.charAt(0).toUpperCase()+t.slice(1);function As({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const o=t.type||"auto",l=(i,d)=>{n({...t,[i]:d})},c=()=>o==="currency"?2:o==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:o,onValueChange:i=>l("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ur.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":qr(i)},i))})]})]}),o!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(o)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>l("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),o==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>l("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>l("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>l("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>l("prefix",i.target.value),className:"h-8 text-xs"})})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>l("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>l("negativeInParentheses",i)})]}),o==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>l("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),o==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>l("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Ws({axis:t,label:n,type:a,config:r,onChange:o}){var h,p,g,j,x,b,f,N,k,I,S,C;const l=(v,T)=>{o({...r,[v]:T})},c=(v,T)=>{var y,O;o({...r,name:{enabled:v==="enabled"?T:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,text:v==="text"?T:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(v,T)=>{var y,O;o({...r,labels:{enabled:v==="enabled"?T:((y=r==null?void 0:r.labels)==null?void 0:y.enabled)??!0,rotation:v==="rotation"?T:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},d=(v,T)=>{o({...r,scale:{...r==null?void 0:r.scale,[v]:T===""?"auto":Number(T)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>l("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>l("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((b=r==null?void 0:r.labels)==null?void 0:b.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(As,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>o({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function zt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const o=s.AxisConfigurator.getAxisInfo(t.type,n);if(!o.hasXAxis&&!o.hasYAxis)return null;const l=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",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(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[o.hasXAxis&&e.jsx(Ws,{axis:"x",label:"X-Axis",type:o.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>l("x",c)}),o.hasYAxis&&e.jsx(Ws,{axis:"y",label:"Y-Axis",type:o.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>l("y",c)})]})})]})}function _t(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,p,g;return(g=(p=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",o="center",l=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",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(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??l,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||o,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Vt(){var T,y,O,E,B,w,D,L,F;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var M,P;return(P=(M=R.card)==null?void 0:M.preferences)==null?void 0:P.dataLabelsConfig}),a=s.useEditorStore(R=>{var M;return(M=R.card)==null?void 0:M.preferences}),{setCardPreferences:r,updateCardInFrame:o}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const l=((T=a==null?void 0:a.chartOptions)==null?void 0:T.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(O=(y=a==null?void 0:a.chartOptions)==null?void 0:y.plugins)==null?void 0:O.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,p=(R,M)=>{const P={...n,[R]:M},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},g=(R,M)=>{const P={...n,font:{...n==null?void 0:n.font,[R]:M}},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},j=(R,M)=>{const P={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:M}},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},b=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":l?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(l?["center","left","right"]:["center","top","bottom"]).filter(M=>M!==b),"custom"];const N=()=>s.titleCase(b),k=["center","start","end"],I=["center","start","end","top","bottom"],S=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],C=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",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($a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:R=>p("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>p("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?N():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>p("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>p("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>p("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>p("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((E=n==null?void 0:n.formatOptions)==null?void 0:E.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>j("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:R=>j("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((w=n==null?void 0:n.formatOptions)==null?void 0:w.useSuffix)??!1,onCheckedChange:R=>j("useSuffix",R)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((D=n==null?void 0:n.formatOptions)==null?void 0:D.locale)||"en-US",onValueChange:R=>j("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((L=n==null?void 0:n.font)==null?void 0:L.size)||12),onSave:R=>g("size",Number(R)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.font)==null?void 0:F.weight)||"normal",onValueChange:R=>g("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="auto"&&p("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>p("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Hr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Pt,{}),e.jsx(zt,{}),e.jsx(_t,{}),e.jsx(Vt,{})]})]})}const Wr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Kr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Jr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],o=l=>r.includes(a)?l:e.jsxs(e.Fragment,{children:[l,e.jsx(Hr,{})]});switch(a){case"stackedBar":case"stackedLine":return o(e.jsx(Pr,{}));case"tornado":case"pyramid":return o(e.jsx(Je,{docContent:Wr,cardType:a}));case"kpi":return e.jsx(Mr,{});case"line":case"bar":return o(e.jsx(Sr,{cardType:a}));case"range":return o(e.jsx(Je,{docContent:Kr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return o(e.jsx(Je,{cardType:a}));case"bubble":case"scatter":return o(e.jsx(wr,{cardType:a}));case"table":return e.jsx(zr,{cardType:a});case"text":return e.jsx(Je,{docContent:Qr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Fr,{});case"custom":return e.jsx(vr,{});default:return o(e.jsx(kr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:n,functions:a,onFunctionChange:r}){let o=a[0];"aggregate"in n?o=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(o=a.find(c=>c.value===n.granularity)||a[0]);function l(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:a,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Xr=[{label:"Sum",value:"SUM",logo:e.jsx(nt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ba,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Zr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=Xr;s.isTextDataType(t.type)&&(a=a.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(a=a.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};n(t.id,l)}return e.jsx(Gt,{column:t,functions:a,onFunctionChange:o=>r(o),label:"Aggregation"})}const el=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function sl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const o={...t,granularity:r,label:Ge(t.name,r)};n(t.id,o)}return e.jsx(Gt,{column:t,functions:el,onFunctionChange:r=>a(r),label:"Granularity"})}function tl({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),o=A.useMemo(()=>{let i=[];(a===Ae||a===Me||a===Le)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Ut({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(Ot,{idx:l,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ft,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function al({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[o,l]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),x=p?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,b=s.isTextDataType(t.type);function f(C){const v=s.isNumberDataType(C.data_type),T=s.isTextDataType(C.data_type),y=s.isDateDataType(C.data_type),O=v?"number":T?"string":y?"date":"string";if(r===Ae){if(T){const E={id:t.id,name:C.column_name,type:O,role:"groupby"};c(t.id,E)}if(y){const E={id:t.id,name:C.column_name,type:O,role:"groupby",label:Ge(C.column_name,"month"),granularity:"month"};c(t.id,E)}}if(r===Le){if(T){const E={id:t.id,name:C.column_name,type:O,role:"groupby"};d(t.id,E)}if(y){const E={id:t.id,name:C.column_name,type:O,label:Ge(C.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,E)}}if(r===Me){const E={id:t.id,name:C.column_name,type:O,role:"metric",label:He(C.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,E)}}function N(){if(r===Me)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Ut,{column:t})})}function k(){const C=s.isDateDataType(t.type);if(r===Me)return e.jsx(Zr,{column:t});if((r===Ae||r===Le)&&C)return e.jsx(sl,{column:t})}function I(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ae||r===Le)&&b}),children:e.jsx(tl,{col:t,onChange:f,droppableId:r})})}function S(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>l(!o),children:o?e.jsx(Va,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(st,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[S(),k(),I()]}),o&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function gs({id:t,label:n,columns:a,previewColumns:r,sortableType:o,onRemoveColumn:l}){var x,b;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var N;return(N=f.card)==null?void 0:N.type}),h=i||((b=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:b.type)===o,p=u?r:a,g=o===as?"Rows":o===ns?"Pivot Columns":"Columns";function j(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(f=>f.id===vt.id?e.jsx(nl,{},f.id):e.jsx(al,{droppableId:t,type:o,column:f,onRemoveColumn:l},f.id))})]})})}function nl(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Yt({children:t,id:n,type:a}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function rl(){const t=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(N=>N.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function p(f,N){const k=g(f);return k?k.role==="metric"?N==="asc"?u:m:N==="asc"?i:d:null}function g(f){return c.find(N=>N.id===f)}function j(f){const N=t.find(k=>k.columnId===f);if(N){const k={...N,direction:N.direction==="asc"?"desc":"asc"};l(k)}}const x=f=>{r({columnId:f.id,direction:"asc"})};function b(f){const N=t.find(k=>k.columnId===f);N&&o(N)}return e.jsx(s.SortableContext,{items:t.map(f=>Ye(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>x(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var N,k;return e.jsx(Yt,{id:Ye(f.columnId),type:Ts,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(st,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(cs,{className:"w-[175px] text-sm",children:((N=g(f.columnId))==null?void 0:N.label)||((k=g(f.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:p(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ye(f.columnId))})]})})}function ll(){const t=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(b=>b.card.type),a=s.useDndStore(b=>b.previewGroupByColumns),r=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=s.useDndStore(b=>b.previewMetricColumns),l=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(b=>b.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(b){i(b)}function h(b){d(b)}function p(b){u(b)}let g="Group By",j="Metrics",x="Stack By";return n==="table"&&(g="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Et,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(gs,{onRemoveColumn:m,sortableType:as,id:Ae,label:g,columns:t,previewColumns:a}),e.jsx(gs,{onRemoveColumn:p,sortableType:ns,id:Le,label:x,columns:l,previewColumns:c}),e.jsx(gs,{onRemoveColumn:h,sortableType:ys,id:Me,label:j,columns:r,previewColumns:o}),e.jsx(rl,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ms({children:t,column:n,id:a,sortableType:r,className:o}){const[l,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var p,g;return(g=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Yt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!l&&"rounded-b-md",l&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function ol({column:t,sortableType:n}){const a=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var I,S;return(S=(I=k.card)==null?void 0:I.queryConfig)==null?void 0:S.filters}),o=s.useEditorStore(k=>{var I,S;return(S=(I=k.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:S.find(C=>C.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var k;return(k=r==null?void 0:r.find(I=>I.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:p,isLoading:g,isFetching:j,isError:x}=s.useFilterQuery(h),b=A.useMemo(()=>{var I;return h.column?(I=p==null?void 0:p.records)==null?void 0:I.map(S=>{let C=h.column.split(".").slice(-1)[0].replace(/"/g,"");return S[C]===void 0&&(C=C.toLowerCase()),{id:S[C],value:S[C]}}):[]},[p,h.column]);function f(k){const I=k.map(S=>S.id);m(t.name,I)}function N(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(il,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:b,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Ms,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function il({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function cl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:o,inputClassName:l,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",o),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",l),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function dl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:b}=s.useEditorActions();function f(I){var C,v;const S={gte:(C=I==null?void 0:I.from)==null?void 0:C.toISOString(),lte:(v=I==null?void 0:I.to)==null?void 0:v.toISOString()};b(t.name,S)}function N(){b(t.name,null,!0),j(x)}function k(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(cl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:f,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Ms,{className:"w-72",id:t.id,sortableType:n,column:t,children:k()})}function ul({id:t,label:n,columns:a,previewColumns:r,sortableType:o}){var j,x;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(b=>b.activeId),u={},m=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===o;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(b){const f=s.isDateDataType(b.type);return b.id===vt.id?e.jsx(Ms,{id:b.id,sortableType:o,column:b,children:e.jsx(ml,{})},b.id):f?e.jsx(dl,{droppableId:t,sortableType:o,column:b},b.id):e.jsx(ol,{droppableId:t,sortableType:o,column:b},b.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(b=>b.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(b=>p(b))})]})})}function ml(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function hl(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),n=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(o){a(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ul,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:n})})}function xl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:o,errorSql:l}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(St,{sql:r==null?void 0:r.sql,error:o,errorSql:l})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Es,{}),e.jsx(ks,{variant:"default"})]})]})}function pl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(nr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Jr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Qe,{})})]}):e.jsx(Qe,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(ll,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(xl,{}),e.jsx(hl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Qe,{})})]})})]}):e.jsx(Qe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?l():c()})}function fl(t){s.useAIInteractionStore(G=>G.currentAIContext);const[n,a]=A.useState(""),[r,o]=A.useState(null),{authToken:l}=s.useSemaphorContext(),c=s.useEditorStore(G=>{var Y;return(Y=G==null?void 0:G.card)==null?void 0:Y.sql}),i=s.useEditorStore(G=>G.isDevMode),d=s.useEditorStore(G=>{var Y;return(Y=G==null?void 0:G.card)==null?void 0:Y.python}),{setCardPython:u,setCardSql:m,setRunSql:h,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),j=s.useEditorStore(G=>G.currentAssitantScope)||[],x=s.useEditorStore(G=>G.userInputForAI),b=s.useEditorStore(G=>G.triggerAIRun),f=s.useEditorStore(G=>G.card),N=s.useEditorStore(G=>G.selectedDatabaseName),k=s.useEditorStore(G=>G.selectedTableName),I=s.useEditorStore(G=>G.selectedConnectionId),S=s.useEditorStore(G=>G.selectedSchemaName),C=s.useDashboardStore(G=>G.dashboard.aiScopeTables),{errorMessage:v,refetch:T,data:y}=s.useDashboardCardQuery(f),{setTriggerAIRun:O,setCurrentAssitantScope:E,setCardConfig:B}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:D,selectedDatamodelId:L}=s.useEditorAside(),{messages:F,setMessages:R,regenerate:M,error:P,sendMessage:W,status:z,addToolResult:X,stop:te,clearError:K}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${l==null?void 0:l.accessToken}`}),body:()=>{const G=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:G.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:Y})=>({body:{...Y,messages:s.cleanupIncompleteMessages(G)}})}),onError:G=>{console.log("on error",G)},onToolCall:H,onFinish(){a("")}});A.useEffect(()=>{b&&x&&(W({role:"user",parts:[{type:"text",text:x}]}),O(!1))},[b,x,W,O]);async function H({toolCall:G}){var Y,re,oe,le,xe,pe,me,fe,$,J,Z,q,ae,ie,ce,Ee;if(["createChartFromSql","createForecast"].includes(G.toolName)){const Be=((Y=G.input)==null?void 0:Y.sql)??((re=G.args)==null?void 0:re.sql),Te=((oe=G.input)==null?void 0:oe.python)??((le=G.args)==null?void 0:le.python),he=((xe=G.input)==null?void 0:xe.chartType)??((pe=G.args)==null?void 0:pe.chartType);p(he),m(Be),u(Te),h(!0),X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(G.toolName==="getUserSql"){if(!c){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",sql:c,python:d||""}})}else if(G.toolName==="generateQueryConfig"){a("Generating query config...");const Be=((me=G.input)==null?void 0:me.chartType)??((fe=G.args)==null?void 0:fe.chartType),Te=(($=G.input)==null?void 0:$.queryConfig)??((J=G.args)==null?void 0:J.queryConfig);((Z=G.input)==null?void 0:Z.cardConfig)??((q=G.args)==null||q.cardConfig),p(Be),B(Te),m(void 0),u(void 0);const he=await T();if((ae=he==null?void 0:he.data)!=null&&ae.error){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",queryConfig:Te,message:(ie=he==null?void 0:he.data)==null?void 0:ie.error.message}});return}if((ce=he==null?void 0:he.data)!=null&&ce.records){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Ee=he==null?void 0:he.data)==null?void 0:Ee.records}})}else a("Analyzing...")}function U(G){const Y=s.removeFromScopeArray(j,G);ee(Y)}function ee(G){const Y=s.sanitizeAIScope(G);E(Y),R(re=>[...re,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Y)}`}]}])}function _(){const G={databaseName:N||"",schemaName:S||"",tableName:k||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||""},Y=s.dedup([...j,G]);ee(Y)}function V(){const G={databaseName:N||"",schemaName:S||"",tableName:k||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||"",datamodelId:L||""};if(!s.isInAiScopeArray([...C||[],...j],G)||j.length===0){const re=s.dedup([...C||[],...j,G]).filter(oe=>oe.connectionId===G.connectionId);ee(re)}}const se=!["ready","error"].includes(z),ne=s.getErrorMessage(P);return{messages:F,setMessages:R,sendMessage:W,regenerate:M,isLoading:se,handleSetAIScope:V,handleAddCurrentTableToScope:_,removeFromCurrentSelections:U,currentAssitantScope:j,setCurrentAssitantScope:E,stop:te,status:z,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ne,clearError:K}}const gl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ks(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,o]=A.useState(s.isDevEnv),[l,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:p}=s.useFileActions(),g=s.useFileAttachments("editor"),j=s.useDashboardStore(J=>J.dashboard.aiContext),x=s.useEditorStore(J=>J.card.dataSource),b=s.useEditorStore(J=>J.actions.setCardSql),f=s.useEditorStore(J=>J.actions.setRunSql),N=s.useEditorStore(J=>J.showAIDialog),k=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:S}=s.useEditorActions(),{setDataSource:C}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:T,setMessages:y,sendMessage:O,isLoading:E,stop:B,status:w,llmUsage:D,errorMessage:L,clearError:F}=fl(),[R,M]=A.useState(""),P=J=>{M(J.target.value)},W=J=>{J.preventDefault();const Z=R.trim();if(!Z&&g.length===0)return;const q=[];Z&&q.push({type:"text",text:Z}),g.forEach(ae=>{ae.data&&q.push({type:"file",mediaType:ae.type,filename:ae.name,url:`data:${ae.type};base64,${ae.data}`})}),O({role:"user",parts:q}),M(""),p("editor"),se({force:!0})},{visibleMessages:z,hasMoreMessages:X,totalMessageCount:te,loadMoreMessages:K,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:U,isAtBottom:ee,hasNewMessages:_,newMessageCount:V,scrollToBottom:se,handleScroll:ne,resetNewMessageCount:G}=s.useAutoScroll(z,{threshold:50,delay:0,dependencies:[w,T.length]});A.useEffect(()=>{var J;N&&((J=t.current)==null||J.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[N,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:w,isLoading:E,sendMessage:O});const{hasActiveTools:Y}=s.useActiveToolStatus(T);function re(J,Z){Z==="sql"?(b(J),f(!0)):Z==="python"&&(S(J),f(!0))}function oe(){var J;(J=j==null?void 0:j.selectedEntities)==null||J[0],d(!0)}function le(){u.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function xe(J){le();const Z={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};O(Z)}function pe(J){le(),O({role:"user",parts:[{type:"text",text:J}]})}function me(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:c,children:"System Message"})]})]})}function fe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(R==null?void 0:R.length)===0&&(T==null?void 0:T.filter(J=>J.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[fe(),k&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[me(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:oe,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),h("editor"),F(),H()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{I(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:U,className:"mt-2 flex w-full grow basis-0",onScroll:ne,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:K,className:"text-xs",children:["Load ",Math.min(5,te-z.length)," more messages (",te-z.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:z,showTools:r,handleRun:re,showSystemMessage:l}),!Y&&e.jsx(s.AssistantStatus,{status:w,errorMessage:L})]})}),!ee&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),G()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),_&&V>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:V>9?"9+":V})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[$&&!v&&e.jsx(s.Placeholders,{onClick:xe,placeholders:gl}),e.jsx("div",{children:$&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:pe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:M,stop:B,input:R,handleInputChange:P,handleSubmit:J=>{le(),W(J),se({force:!0})},isLoading:E,status:w,assistantType:"editor",onFocus:()=>{}})]}),D&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",D.inputTokens," prompt tokens, ",D.outputTokens," ","completion tokens, ",D.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:d,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ls=t=>{var E;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,p=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,dateFormat:w.dateFormat,customFormat:w.customFormat,granularity:w.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,direction:w.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((B,w)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:w});break}case"metrics":{n(h,{metricColumns:w});break}case"pivotBy":{n(h,{pivotByColumns:w});break}case"sortBy":{n(h,{sortByColumns:w});break}}},[h,n]),j=A.useCallback((B,w,D)=>{if(!h)return;const F=p(B)[w];if(F)switch(B){case"groupBy":a(h,F.id,{label:D});break;case"metrics":r(h,F.id,{label:D});break;case"pivotBy":o(h,F.id,{label:D});break;case"sortBy":l(h,F.id,{label:D});break}},[h,p,a,r,o,l]),x=A.useCallback((B,w)=>{if(!h)return;const L=p("metrics")[B];L&&r(h,L.id,{aggregate:w,label:s.getAggregationLabel(L.name,w)})},[h,p,r]),b=A.useCallback((B,w,D)=>{if(!h)return;const F=p("groupBy")[B];if(!F)return;const R={dateFormat:w};w==="custom"&&D?R.customFormat=D:R.customFormat=void 0,a(h,F.id,R)},[h,p,a]),f=A.useCallback((B,w)=>{if(!h)return;const L=p("groupBy")[B];L&&a(h,L.id,{granularity:w})},[h,p,a]),N=A.useCallback((B,w)=>{if(!h)return;const L=p("metrics")[B];L&&r(h,L.id,{aliasTemplate:w})},[h,p,r]),k=A.useCallback((B,w)=>{if(console.log("handleValueAliasesChange",B,w),!h)return;console.log("handleValueAliasesChange",B,w);const L=p("metrics")[B];L&&(console.log("handleValueAliasesChange",w),r(h,L.id,{valueAliases:w}))},[h,p,r]),I=A.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),S=A.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),C=A.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=A.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),T=A.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),y=A.useCallback(B=>{var P;if(!h)return;const w=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],D=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,L=s.validateEntityConsistency(B,w,D);if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const F=s.getSmartContainerForField(B,w),R=p(F);if(s.fieldAlreadyExists(B,R))return;const M=s.getNewField(B,F,R);M&&g(F,[...R,M])},[h,(E=t==null?void 0:t.config)==null?void 0:E.joinPlan,p,g]),O=A.useCallback((B,w)=>{if(!h)return;const L=p(B)[w];if(L){if(B!=="sortBy"){const F=p("sortBy"),R=F.filter(M=>!(M.name===L.name&&M.qualifiedEntityName===L.qualifiedEntityName));R.length!==F.length&&n(h,{sortByColumns:R})}switch(B){case"groupBy":c(h,L.id);break;case"metrics":i(h,L.id);break;case"pivotBy":d(h,L.id);break;case"sortBy":u(h,L.id);break}}},[h,p,c,i,d,u,n]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:O,handleFieldClick:y,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:C,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:T,cardType:m}};function jl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function bl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(j=>j.card),{handleFieldClick:m}=Ls(u),h={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return De;case"date":return s.Calendar;case"boolean":return Re;case"json":return _e;case"geo":return $e;default:return ve}},g=j=>{const x=(j||"").toLowerCase(),b=s.getDataType(x);return b==="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"})}):b==="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"})}):b==="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"})}):b==="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"})}):b==="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(_e,{className:"h-3 w-3"})}):b==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):b==="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(We,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(jl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function vl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),o=s.useEditorStore(k=>k.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const I=s.getDataType(k.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},p=(a==="all"?u:u.filter(k=>m(k)===a)).reduce((k,I)=>{const S=I.qualifiedEntityName||"Other Fields";return k[S]||(k[S]={label:s.toLabel(I.entityName),fields:[]}),k[S].fields.push(I),k},{}),j=Object.keys(p),x=u.filter(k=>m(k)==="dimensions").length,b=u.filter(k=>m(k)==="metrics").length,f=u.filter(k=>m(k)==="calculated").length,N=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[l.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>n(k.target.value)})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(We,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(p).map(([k,I])=>{const S=c.find(C=>C.entityName===k)||{entityName:k,label:I.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:S.label||S.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:S.label||S.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:I.fields.map(C=>e.jsx(bl,{field:C},C.id))})})]},k)})}),Object.keys(p).length===0&&l.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&l.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function yl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(vl,{})," "]})}function Nl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[o,l]=A.useState(new Set),c=()=>{const C=a.joins.length>0?Math.max(...a.joins.map(T=>T.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),l(new Set([...o,v.id]))},i=C=>{r({...a,joins:a.joins.filter(v=>v.id!==C)}),l(new Set([...o].filter(v=>v!==C)))},d=(C,v)=>{var E,B;const T=a.joins.find(w=>w.id===C);if(!T)return;const y={...T,...v},O=a.joins.map(w=>w.id===C?y:w);if((E=y.source)!=null&&E.name&&((B=y.target)!=null&&B.name)&&y.joinKeyGroups[0].keys.length===0){const w=n.find(R=>{var M;return R.name===((M=y.source)==null?void 0:M.name)}),D=n.find(R=>{var M;return R.name===((M=y.target)==null?void 0:M.name)}),L={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="},F=[...y.joinKeyGroups];F[0]={...F[0],keys:[L]},y.joinKeyGroups=F,O[O.findIndex(R=>R.id===C)]=y}r({...a,joins:O})};return{joinPlan:a,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:C=>{const v=a.joins.findIndex(T=>T.id===C);if(v>0){const T=[...a.joins],y={...T[v]},O={...T[v-1]};T[v]=O,T[v-1]=y,T.forEach((B,w)=>{B.sequence=w+1});const E={...a,joins:T};r(E)}},moveJoinDown:C=>{const v=a.joins.findIndex(T=>T.id===C);if(v<a.joins.length-1){const T=[...a.joins],y={...T[v]},O={...T[v+1]};T[v]=O,T[v+1]=y,T.forEach((B,w)=>{B.sequence=w+1});const E={...a,joins:T};r(E)}},toggleJoinExpansion:C=>{const v=new Set(o);v.has(C)?v.delete(C):v.add(C),l(v)},getAvailableSourceEntities:C=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(y=>y.id===C);if(v===0)return n;const T=new Set;return a.baseEntity.name&&T.add(a.baseEntity.name),a.joins.slice(0,v).forEach(y=>{T.add(y.source.name),T.add(y.target.name)}),n.filter(y=>T.has(y.name))},getAvailableTargetEntities:C=>n.filter(v=>v.name!==C),addJoinKeyGroup:C=>{const v=a.joins.find(y=>y.id===C);if(!v)return;const T=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(C,{joinKeyGroups:T})},updateGroupOperator:(C,v,T)=>{const y=a.joins.find(E=>E.id===C);if(!y)return;const O=[...y.joinKeyGroups];O[v]={...O[v],operator:T},d(C,{joinKeyGroups:O})},removeJoinKeyGroup:(C,v)=>{const T=a.joins.find(O=>O.id===C);if(!T)return;const y=[...T.joinKeyGroups];y.splice(v,1),d(C,{joinKeyGroups:y})},addJoinKey:(C,v)=>{const T=a.joins.find(w=>w.id===C);if(!T)return;const y=n.find(w=>w.name===T.source.name),O=n.find(w=>w.name===T.target.name),E=[...T.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(y==null?void 0:y.name)||"",entityName:(y==null?void 0:y.name)||"",entityType:(y==null?void 0:y.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};E[v]={...E[v],keys:[...E[v].keys,B]},d(C,{joinKeyGroups:E})},updateJoinKey:(C,v,T,y,O)=>{const E=a.joins.find(F=>F.id===C);if(!E)return;const B=n.find(F=>F.name===E.source.name),w=n.find(F=>F.name===E.target.name),D=[...E.joinKeyGroups],L=D[v].keys[T];y==="sourceColumnName"&&B?D[v].keys[T]={...L,source:{...L.source,name:O}}:y==="targetColumnName"&&w?D[v].keys[T]={...L,target:{...L.target,name:O}}:y==="operator"&&(D[v].keys[T]={...L,operator:O}),d(C,{joinKeyGroups:D})},removeJoinKey:(C,v,T)=>{const y=a.joins.find(E=>E.id===C);if(!y)return;const O=[...y.joinKeyGroups];O[v].keys.splice(T,1),d(C,{joinKeyGroups:O})},generateSQLPreview:()=>{const C=[...a.joins].sort((y,O)=>y.sequence-O.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let T=`SELECT *
348
+ `),T=new Blob([v],{type:"text/csv"}),y=URL.createObjectURL(T),O=document.createElement("a");O.href=y,O.download=`${n.title}.csv`,O.click()}function k(){const C=`Can you get the documentation for ${n.type} chart?`;u(C)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(It,{}),o&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:k,children:e.jsx(oa,{className:"size-4"})}),!["table","custom"].includes(n.type)&&o&&e.jsx(ur,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:N,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(ja,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(p==null?void 0:p.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(At,{})]}),n.type==="table"&&n.sql&&!s.hasValidCardConfig(n.config)&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((S=(I=n.preferences)==null?void 0:I.tablePrefs)==null?void 0:S.enableDevModePagination)??!1,onCheckedChange:C=>{var v;h({...n.preferences,tablePrefs:{...(v=n.preferences)==null?void 0:v.tablePrefs,enableDevModePagination:C}}),b()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(br,{})]}),r?e.jsx(Mt,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:l&&e.jsx(jr,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":l}),children:[(p==null?void 0:p.records)&&(p==null?void 0:p.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(p==null?void 0:p.records)||[]}),x&&e.jsx(pr,{error:x})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function jr(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function br(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Ce({defaultValue:t,label:n,options:a,value:r,onValueChange:o,className:l,icon:c,showPlaceholderLabel:i=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),i&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function vr(){var x,b;const t=s.useEditorStore(f=>f.card.customCardPreferences),{data:n}=Tt(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(f=>f.card),o=s.useEditorStore(f=>f.frame),l=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:i,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(x=d==null?void 0:d.visuals)==null?void 0:x.find(f=>f.name===(t==null?void 0:t.componentName));function m(f,N){if(!t)return;const I={...(t==null?void 0:t.dataInputCardIds)||{},[f]:{cardId:N,hookRef:null}};c({...t,dataInputCardIds:I})}function h(f){var k,I;const N=(k=o==null?void 0:o.cards)==null?void 0:k.filter(S=>{var C;return((C=S==null?void 0:S.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(S=>({value:S.id,label:S.tabTitle||S.title}));return e.jsx("div",{className:"space-y-2",children:(I=f==null?void 0:f.dataInputs)==null?void 0:I.map((S,C)=>{var v,T;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:S}),e.jsx(Ce,{className:"col-span-6 h-8 w-full justify-between",label:"",options:N||[],value:((T=(v=t==null?void 0:t.dataInputCardIds)==null?void 0:v[C])==null?void 0:T.cardId)||"",onValueChange:y=>m(C,y)})]},C+Math.random())})})}function p(f,N,k=[],I=""){var S,C;return t?f==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((S=t==null?void 0:t.settings)==null?void 0:S[N])||I,onChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v.target.value}})}},N):f==="select"?e.jsx(Ce,{className:"h-8 w-full",label:"",options:k,value:((C=t==null?void 0:t.settings)==null?void 0:C[N])||I,onValueChange:v=>{c({...t,settings:{...t==null?void 0:t.settings,[N]:v}})}}):null:null}function g(f){const N=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:N.map(([k,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:I.title}),p(I.ui,k,I.options,I.defaultValue)]},k))})}function j(f){t&&c({...t,visualType:f,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ce,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(t==null?void 0:t.url)||"",onValueChange:f=>c({...t||{url:"",componentName:""},url:f})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:l,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:i&&e.jsx(Ce,{icon:e.jsx(ha,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(i==null?void 0:i.filter(f=>f.type===l).map(f=>({value:f.name,label:f.name})))||[],value:t.componentName,onValueChange:f=>{console.log("changing value",f),c({...t,componentName:f})}})})]})})]}),((b=r==null?void 0:r.customCardPreferences)==null?void 0:b.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:h(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:g(u)})})]})]})]})}function Fe(){const[t,n]=A.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),l=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),A.useEffect(()=>{l&&n(new Array(l.length).fill(!1))},[l]);function c(u,m){var h,p;m?a!=null&&a.onClickFilter&&((h=a==null?void 0:a.onClickFilter)==null?void 0:h.length)>0?o({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):o({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(o({...a,onClickFilter:(p=a==null?void 0:a.onClickFilter)==null?void 0:p.filter(g=>g.columnIndex!==u)}),n(g=>{const j=[...g];return j[u]=!1,j}))}function i(u,m){var p;const h=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.map(g=>g.columnIndex===u?{...g,expression:m.target.value}:g);o({...a,onClickFilter:h})}function d(u){var m,h,p,g;if(t!=null&&t[u]||(h=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input,{value:(g=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(j=>j.columnIndex===u))==null?void 0:g.expression,onChange:j=>i(u,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:l==null?void 0:l.map((u,m)=>{var h,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(g=>g.columnIndex===m)),onCheckedChange:g=>c(m,g)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{n(g=>{const j=[...g];return j[m]=!g[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function yr({idx:t}){var i;const n=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),a=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),o=(i=n==null?void 0:n.chartOptions)==null?void 0:i.indexAxis,l=a==null?void 0:a.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!l)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:m}]});else{const h={...l};h.datalabels=m;const p=a==null?void 0:a.map(g=>g.idx===u?h:g);r({...n,datasetOptions:p})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(rt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Da,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wa,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function Nr(){const t=s.useEditorStore(l=>l.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(l=>!s.METADATA_KEYS.includes(l));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const l=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:c}=s.getKeys(l);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function cs({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("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Lt(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var u,m,h;return(h=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",o=n==="y"?"Dimension":"Metric",{dimensionKeys:l,transformedMetricKeys:c,keys:i}=Nr();return i.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:l.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Rt(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(Ot,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Rt(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Ot({col:t,idx:n,className:a,iconClassName:r,children:o}){const l=s.useEditorStore(m=>{var h;return(h=m.card)==null?void 0:h.preferences}),c=s.useEditorStore(m=>{var h,p;return(p=(h=m.card)==null?void 0:h.preferences)==null?void 0:p.datasetOptions}),i=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!i)d({...l,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const h={...i};h.type=m==="area"?"line":m,h.fill=m==="area"?"origin":"";const p=c==null?void 0:c.map(g=>g.idx===n?h:g);d({...l,datasetOptions:p})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[o||e.jsx(cs,{className:"max-w-[100px]",title:t,children:Rt(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(yr,{idx:n})]})]})}function Is(){const t=s.useEditorStore(g=>g.selectedConnectionId),n=s.useEditorStore(g=>g.selectedDatamodelId),a=s.useEditorStore(g=>g.selectedDatabaseName),r=s.useEditorStore(g=>g.selectedSchemaName),o=s.useEditorStore(g=>g.selectedTableName),l=s.useDashboardStore(g=>g.dashboard.filters)||[],c=s.useDashboardStore(g=>g.actions.addFilter),i=s.useDashboardStore(g=>g.actions.removeFilter),{removeFilterValues:d}=s.useDashboardActions(),{modelItems:u,tableName:m,connectionType:h}=s.useEditorAside();function p(g,j="dashboard",x){var T;const b=s.fmt(g.column_name),f=s.fmt(a||""),N=s.fmt(r||""),k=s.fmt(m);let I=s.getQualifiedTableName({schemaName:N,tableName:k,connectionType:h,databaseName:f}),S=`${I}.${b}`;const C=(T=u==null?void 0:u.find(y=>y.id===n))==null?void 0:T.name;n&&n!=="none"&&(S=`${s.DATAMODEL_NAMESPCACE}.${C}.${b}`,I=`${s.DATAMODEL_NAMESPCACE}.${C}`),x!=null&&x.qualifiedFieldName&&(S=x.qualifiedFieldName),x!=null&&x.entityName&&(I=x.entityName);const v=l==null?void 0:l.find(y=>y.column===S&&y.table===k&&(y.database===f||y.database===a));if(v)d(v.id),i(v.id);else{const y=s.v4();return m==="api"&&t?(c({location:j,id:y,column:S,title:g.column_name,dataType:g.data_type,table:"api",database:"",connectionId:t,operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),y):(c({id:y,location:j,column:S,title:g.column_name,dataType:g.data_type,table:o||"",database:a||"",connectionId:t||"",operation:"in",sql:s.getDefaultFilterSql(g.data_type,I,b)}),y)}}return{assignFilter:p}}function Ue(){const t=s.useDashboardStore(i=>i.dashboard.filters),n=s.useEditorStore(i=>i.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=Is();function l(i){const d=o(i,"frame");a({...n,filterId:d})}const c=t==null?void 0:t.find(i=>i.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Cr,{onSelect:l,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function Cr({columns:t,onSelect:n}){var c;const[a,r]=Ie.useState(!1),[o,l]=Ie.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[o?(c=t.find(i=>i.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(i=>e.jsxs(s.CommandItem,{value:i.column_name,onSelect:d=>{const u=d===o?"":d;l(u),r(!1),u&&n(i)},children:[i.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===i.column_name?"opacity-100":"opacity-0")})]},i.column_name))})]})]})})]})}function Sr({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:n=>n.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Lt,{})})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function wr({cardType:t}){function n(a){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:a==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),a==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:n(t)})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function Ft(){const t=s.useEditorStore(i=>i.card.type),n=s.useEditorStore(i=>i.isDevMode),a=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:r}=s.useEditorStore(i=>i.actions);function o(i){var m;const d={datalabels:{display:i!=="none",align:i,anchor:i,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(m=a==null?void 0:a.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function l(){var i,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var i,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(i=a==null?void 0:a.chartOptions)==null?void 0:i.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?l():c()})}const Dr={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Tr={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function kr(){const t=s.useEditorStore(n=>n.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Er(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{}),e.jsx(Fe,{}),e.jsx(Ue,{})]})]})}function Er(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(Dr,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Tr,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function Ir({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(c,i,d){const u=[...t];u[c]={...u[c],[i]:d},n(u)}function o(c){const i=[...t];i.splice(c,1),n(i)}function l(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:l,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,i)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(i,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(i,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(i,"color",d.target.value),value:c.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>o(i),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},i))]})}function Ar(){var m,h,p,g,j;const t=s.useEditorStore(x=>x.card.preferences),n=s.useEditorStore(x=>x.actions.setCardPreferences),a=s.useEditorStore(x=>x.card),r=s.isExplorerCard(a),o=s.useEditorStore(x=>x.actions.setNumberFormat);s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.decimalPlaces});const l=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.locale}),c=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.currency});s.useEditorStore(x=>x.actions.setFilterOnClickField);const i=s.useEditorStore(x=>{var b,f;return(f=(b=x.card.preferences)==null?void 0:b.formatNumber)==null?void 0:f.colorRanges})||[],d=s.useEditorStore(x=>x.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(x=>x.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:x=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:x}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((h=t==null?void 0:t.formatNumber)==null?void 0:h.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:l||"none",onValueChange:x=>{var b,f,N;return o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",x,((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(x=>e.jsx(s.SelectItem,{value:x.locale,children:x.locale},x.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:x=>{var b,f,N;console.log("currency",x),o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,x==="none"?"":x,((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),u.map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((g=(p=t==null?void 0:t.formatNumber)==null?void 0:p.decimalPlaces)==null?void 0:g.toString())||"0",onValueChange:x=>{var b,f,N;return o(Number(x),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((f=t==null?void 0:t.formatNumber)==null?void 0:f.locale)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(x=>e.jsx(s.SelectItem,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:x=>{var b,f,N;return o(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((f=t==null?void 0:t.formatNumber)==null?void 0:f.currency)||"",((N=t==null?void 0:t.formatNumber)==null?void 0:N.locale)||"",x.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Ir,{colorRanges:i,setColorRanges:d})]})]})}function Mr(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Ar,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function fs({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const Lr=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],Rr=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],Or=Rr.map(t=>({label:t,value:t}));function Fr(){var d,u,m,h,p,g,j,x,b,f,N,k,I,S,C,v,T,y;const t=s.useEditorStore(O=>O.card),n=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=A.useState(((h=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:l}=s.useTopoJson(t),c=Object.keys((l==null?void 0:l.objects)||{}).map(O=>({label:O,value:O}))||[],i=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(fs,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ce,{className:"h-9",options:i,onValueChange:O=>{console.log("value",O),o({...t.preferences,mapVisualOptions:{topoJsonUrl:O}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:O=>{r(O.target.value)},onBlur:()=>{var O;console.log("onBlur",a),o({...t.preferences,mapVisualOptions:{...(O=t.preferences)==null?void 0:O.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(Ce,{className:"h-9",options:c,value:((g=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:g.objectKey)||"",label:"Map Object",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,objectKey:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(Ce,{className:"h-9",options:Lr,value:((x=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:x.projection)||"",label:"Projection",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projection:O}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(Ce,{className:"h-9",options:Or,value:((f=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,colorScale:O}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(fs,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((k=(N=t.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:k.projectionScale)||1,onChange:O=>{var E;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionScale:Number(O.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(S=(I=t.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:C[0])||0,onChange:O=>{var E,B,w,D;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionOffset:[Number(O.target.value),((D=(w=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((y=(T=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:T.projectionOffset)==null?void 0:y[1])||0,onChange:O=>{var E,B,w,D;o({...t.preferences,mapVisualOptions:{...(E=t.preferences)==null?void 0:E.mapVisualOptions,projectionOffset:[((D=(w=(B=t.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:D[0])||0,Number(O.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Fe,{})]})}function Br(){var r;const t=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:n}=s.useEditorStore(o=>o.actions);function a(o){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Je({cardType:t,docContent:n,suffix:a="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${a}`}),e.jsx(s.AccordionContent,{children:n||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Br,{})})]}),!["range","text"].includes(t)&&e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function Pr(){const t=s.useEditorStore(r=>{var o,l;return(l=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:l.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(Ce,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{n(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[a(),e.jsx(Lt,{})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})]})})}function zr({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(o=>{var l;return(l=o.card)==null?void 0:l.preferences}),a=s.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{a({...n,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(Fe,{}),e.jsx(Ue,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function Bt({color:t,onColorChange:n,onClose:a}){const[r,o]=A.useState(0),[l,c]=A.useState(100),[i,d]=A.useState(50),[u,m]=A.useState(t);A.useEffect(()=>{const b=qs(t);if(b){const f=Hs(b.r,b.g,b.b);o(f.h),c(f.s),d(f.l),m(t)}},[t]);const h=b=>{o(b),g(b,l,i)},p=b=>{const f=b.currentTarget.getBoundingClientRect(),N=Math.max(0,Math.min(1,(b.clientX-f.left)/f.width)),k=Math.max(0,Math.min(1,(b.clientY-f.top)/f.height)),I=N*100,S=(1-k)*100;c(I),d(S),g(r,I,S)},g=(b,f,N)=>{const k=Vr(b,f,N),I=_r(k.r,k.g,k.b);m(I)},j=b=>{if(m(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const f=qs(b);if(f){const N=Hs(f.r,f.g,f.b);o(N.h),c(N.s),d(N.l)}}},x=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(n(u),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:p,onMouseMove:b=>{b.buttons===1&&p(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${l}%`,top:`${100-i}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>h(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:u,onChange:b=>j(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:x,children:"OK"})]})]})}function qs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function _r(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Hs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),o=Math.min(t,n,a);let l=0,c=0;const i=(r+o)/2;if(r!==o){const d=r-o;switch(c=i>.5?d/(2-r-o):d/(r+o),r){case t:l=((n-a)/d+(n<a?6:0))/6;break;case n:l=((a-t)/d+2)/6;break;case a:l=((t-n)/d+4)/6;break}}return{h:Math.round(l*360),s:Math.round(c*100),l:Math.round(i*100)}}function Vr(t,n,a){t/=360,n/=100,a/=100;let r,o,l;if(n===0)r=o=l=a;else{const c=(u,m,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(m-u)*6*h:h<.5?m:h<.6666666666666666?u+(m-u)*(.6666666666666666-h)*6:u),i=a<.5?a*(1+n):a+n-a*n,d=2*a-i;r=c(d,i,t+1/3),o=c(d,i,t),l=c(d,i,t-1/3)}return{r:Math.round(r*255),g:Math.round(o*255),b:Math.round(l*255)}}const Gr=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Pt(){var k,I,S,C,v,T,y,O,E,B;const t=s.useEditorStore(w=>w.card),n=s.useEditorStore(w=>{var D;return(D=w.card)==null?void 0:D.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:o}=s.useDashboardCardQuery(t),[l,c]=A.useState({}),[i,d]=A.useState(null),[u,m]=A.useState(null),h=A.useMemo(()=>{var F,R,M,P,W,z,X;if(!(o!=null&&o.records)||o.records.length===0)return[];const w=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",D=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line",L=((F=t==null?void 0:t.config)==null?void 0:F.pivotByColumns)&&t.config.pivotByColumns.length>0;if((w||D)&&L){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const te=new Set;return o.pivotSchema.forEach(K=>{K.alias&&te.add(K.alias)}),Array.from(te)}if(o.records.length>0){const te=o.records[0],K=Object.keys(te),H=new Set;(R=t==null?void 0:t.config)!=null&&R.groupByColumns&&t.config.groupByColumns.forEach(_=>{H.add(_.label||_.name),H.add(_.alias||_.name)});const U=new Set;return(M=t==null?void 0:t.config)!=null&&M.metricColumns&&t.config.metricColumns.forEach(_=>{const V=_.alias||_.name;U.add(V),U.add(`${V}_count`),U.add(`${V}_sum`),U.add(`${V}_avg`),U.add(`${V}_min`),U.add(`${V}_max`);const se=_.entityName||_.qualifiedEntityName;se&&(U.add(`${se}_${V}`),U.add(`${se}_${V}_count`))}),K.filter(_=>!H.has(_)&&!U.has(_))}}if((D||w)&&!L&&((W=(P=t==null?void 0:t.config)==null?void 0:P.metricColumns)!=null&&W.length))return t.config.metricColumns.map(te=>te.alias||te.label||te.name);if((X=(z=t==null?void 0:t.config)==null?void 0:z.groupByColumns)!=null&&X.length){const te=t.config.groupByColumns[0],K=te.label||te.name,H=new Set;return o.records.forEach(U=>{const ee=U[K];ee!=null&&H.add(String(ee))}),Array.from(H)}return[]},[o,(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns,(I=t==null?void 0:t.config)==null?void 0:I.pivotByColumns,(S=t==null?void 0:t.config)==null?void 0:S.metricColumns,t==null?void 0:t.type]),p=A.useMemo(()=>s.getDefaultChartColors(),[]);A.useEffect(()=>{const w={};h.forEach((D,L)=>{w[D]=s.getColorForValue(D,L,n==null?void 0:n.colorConfig)}),c(w)},[h,n==null?void 0:n.colorConfig,p]);const g=(w,D)=>{const L={...l,[w]:D};c(L);const F={...n||{},colorConfig:{segments:L}};a(F);const R={...t,preferences:F};r(R)},j=(w,D)=>{var W;const L=p[D%p.length],{[w]:F,...R}=((W=n==null?void 0:n.colorConfig)==null?void 0:W.segments)||{},M={...n||{},colorConfig:{segments:R}};a(M);const P={...t,preferences:M};r(P),c(z=>({...z,[w]:L}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((v=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:v.length)||((y=(T=t==null?void 0:t.config)==null?void 0:T.pivotByColumns)==null?void 0:y.length):(E=(O=t==null?void 0:t.config)==null?void 0:O.groupByColumns)==null?void 0:E.length)||["table","kpi","text","custom"].includes(t.type))return null;const f=()=>{const w={...n||{},colorConfig:{segments:{}}};a(w);const D={...t,preferences:w};r(D);const L={};h.forEach((F,R)=>{L[F]=s.getColorForValue(F,R,void 0)}),c(L)},N=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",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(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:N&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:f,children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((w,D)=>{const L=s.isDefaultColor(l[w],D),F=!L;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:i===w,onOpenChange:R=>d(R?w:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:l[w]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:p.slice(0,10).map((R,M)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",l[w]===R?"border-gray-900":"border-transparent"),style:{backgroundColor:R},onClick:()=>{g(w,R),d(null)},children:[M===D%p.length&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-white/90 px-0.5 text-[8px] font-bold text-gray-900 shadow-sm",children:"D"})}),e.jsx("span",{className:"sr-only",children:R})]},`default-${M}`))})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Popular Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Gr.map((R,M)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",l[w]===R?"border-2 border-gray-900":R==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:R},onClick:()=>{g(w,R),d(null)},children:e.jsx("span",{className:"sr-only",children:R})},`preset-${M}`))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx("button",{className:"text-sm font-medium text-blue-600 hover:text-blue-700",onClick:()=>{m({value:w,color:l[w]}),d(null)},children:"Custom color"}),!L&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(w,D),d(null)},children:[e.jsx(s.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:w}),F&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},w)})}),u&&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:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Bt,{color:u.color,onColorChange:w=>{g(u.value,w),m(null)},onClose:()=>m(null)})})]})]})})]})}function we({value:t,onSave:n,placeholder:a="",type:r="text",className:o=""}){const[l,c]=A.useState(t??""),[i,d]=A.useState(!1);A.useEffect(()=>{c(t??"")},[t]);const u=()=>{n(l),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:i?l:t??"",onChange:h=>{c(h.target.value),d(!0)},onFocus:()=>d(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&i&&l!==t?u():h.key==="Escape"&&m()},"aria-label":a||"Edit field"}),i&&l!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Ur=["auto","number","currency","percent","scientific","date"],Yr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],$r=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"en-IN",label:"English (India)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"},{value:"ja-JP",label:"Japanese"},{value:"ko-KR",label:"Korean"},{value:"ru-RU",label:"Russian"},{value:"ar-SA",label:"Arabic"},{value:"hi-IN",label:"Hindi"},{value:"nl-NL",label:"Dutch"},{value:"sv-SE",label:"Swedish"}],qr=t=>t.charAt(0).toUpperCase()+t.slice(1);function As({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const o=t.type||"auto",l=(i,d)=>{n({...t,[i]:d})},c=()=>o==="currency"?2:o==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:o,onValueChange:i=>l("type",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ur.map(i=>e.jsx(s.SelectItem,{value:i,className:"text-xs",children:i==="auto"?"Auto (Default)":qr(i)},i))})]})]}),o!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(o)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??c(),onChange:i=>l("decimalPlaces",parseInt(i.target.value)||0),className:"h-8 text-xs"})})]}),o==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:i=>l("currency",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Yr.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:i=>l("useSuffix",i)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:i=>l("locale",i),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:$r.map(i=>e.jsx(s.SelectItem,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:i=>l("prefix",i.target.value),className:"h-8 text-xs"})})]}),o==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:i=>l("suffix",i.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(o)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:i=>l("negativeInParentheses",i)})]}),o==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:i=>l("multiplyBy",i.target.value?parseFloat(i.target.value):void 0),className:"h-8 text-xs"})})]}),o==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:i=>l("dateFormat",i.target.value),className:"h-8 text-xs"})})]})]})]})}function Ws({axis:t,label:n,type:a,config:r,onChange:o}){var h,p,g,j,x,b,f,N,k,I,S,C;const l=(v,T)=>{o({...r,[v]:T})},c=(v,T)=>{var y,O;o({...r,name:{enabled:v==="enabled"?T:((y=r==null?void 0:r.name)==null?void 0:y.enabled)??!1,text:v==="text"?T:(O=r==null?void 0:r.name)==null?void 0:O.text}})},i=(v,T)=>{var y,O;o({...r,labels:{enabled:v==="enabled"?T:((y=r==null?void 0:r.labels)==null?void 0:y.enabled)??!0,rotation:v==="rotation"?T:(O=r==null?void 0:r.labels)==null?void 0:O.rotation}})},d=(v,T)=>{o({...r,scale:{...r==null?void 0:r.scale,[v]:T===""?"auto":Number(T)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:v=>l("enabled",v),onClick:v=>v.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((h=r==null?void 0:r.name)==null?void 0:h.enabled)??!1,onCheckedChange:v=>c("enabled",v)})]}),((p=r==null?void 0:r.name)==null?void 0:p.enabled)&&e.jsx(we,{placeholder:`${n} title`,value:((g=r==null?void 0:r.name)==null?void 0:g.text)||"",onSave:v=>c("text",v),className:""})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:v=>l("position",v),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":s.titleCase(v)},v))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:v=>i("enabled",v)})]}),((x=r==null?void 0:r.labels)==null?void 0:x.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((b=r==null?void 0:r.labels)==null?void 0:b.rotation)||"auto"),onValueChange:v=>i("rotation",v==="auto"?"auto":Number(v)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v,className:"text-xs",children:v==="auto"?"Auto (Default)":`${v}°`},v))})]})]})]}),a==="value"&&e.jsx(As,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:v=>o({...r,formatOptions:v}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.min)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.min)===void 0?"":String(r.scale.min),onSave:v=>d("min",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((k=r==null?void 0:r.scale)==null?void 0:k.max)==="auto"||((I=r==null?void 0:r.scale)==null?void 0:I.max)===void 0?"":String(r.scale.max),onSave:v=>d("max",v),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"auto",value:((S=r==null?void 0:r.scale)==null?void 0:S.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:v=>d("stepSize",v),className:""})})]})]})]})]})]})}function zt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var i;return(i=c.card)==null?void 0:i.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi"].includes(t.type))return null;const o=s.AxisConfigurator.getAxisInfo(t.type,n);if(!o.hasXAxis&&!o.hasYAxis)return null;const l=(c,i)=>{const u={...n||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:i};a(u);const m={...t,preferences:u};r(m)};return e.jsxs(s.AccordionItem,{value:"axes",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(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[o.hasXAxis&&e.jsx(Ws,{axis:"x",label:"X-Axis",type:o.xAxisType,config:n==null?void 0:n.xAxisConfig,onChange:c=>l("x",c)}),o.hasYAxis&&e.jsx(Ws,{axis:"y",label:"Y-Axis",type:o.yAxisType,config:n==null?void 0:n.yAxisConfig,onChange:c=>l("y",c)})]})})]})}function _t(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var m,h,p,g;return(g=(p=(h=(m=u.card)==null?void 0:m.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r="bottom",o="center",l=!(t.type==="stackedBar"||t.type==="stackedLine"),c=(u,m)=>{const h={...n,[u]:m};a(h)},i=["top","bottom","left","right"],d=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",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(Ca,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.display)??l,onCheckedChange:u=>c("display",u)})]}),((n==null?void 0:n.display)??l)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||r,onValueChange:u=>c("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:i.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(n==null?void 0:n.align)||o,onValueChange:u=>c("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function Vt(){var T,y,O,E,B,w,D,L,F;const t=s.useEditorStore(R=>R.card),n=s.useEditorStore(R=>{var M,P;return(P=(M=R.card)==null?void 0:M.preferences)==null?void 0:P.dataLabelsConfig}),a=s.useEditorStore(R=>{var M;return(M=R.card)==null?void 0:M.preferences}),{setCardPreferences:r,updateCardInFrame:o}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const l=((T=a==null?void 0:a.chartOptions)==null?void 0:T.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",i=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!i,u=(O=(y=a==null?void 0:a.chartOptions)==null?void 0:y.plugins)==null?void 0:O.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),h=(n==null?void 0:n.enabled)!==void 0?n.enabled:m,p=(R,M)=>{const P={...n,[R]:M},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},g=(R,M)=>{const P={...n,font:{...n==null?void 0:n.font,[R]:M}},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},j=(R,M)=>{const P={...n,formatOptions:{...n==null?void 0:n.formatOptions,[R]:M}},W={...t.preferences||{},dataLabelsConfig:P};r(W);const z={...t,preferences:W};o(z)},b=(()=>{const R=t.type;return R==="stackedBar"||R==="stackedLine"||R==="pie"||R==="doughnut"?"center":l?"right":"top"})();let f=[];c||i?f=["center"]:f=["auto",...(l?["center","left","right"]:["center","top","bottom"]).filter(M=>M!==b),"custom"];const N=()=>s.titleCase(b),k=["center","start","end"],I=["center","start","end","top","bottom"],S=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],C=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"GBP",label:"GBP - British Pound"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"INR",label:"INR - Indian Rupee"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"}],v=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",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($a,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:h,onCheckedChange:R=>p("enabled",R)})]}),h&&e.jsxs(e.Fragment,{children:[!c&&!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(n==null?void 0:n.position)||"auto",onValueChange:R=>p("position",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"?N():R==="custom"?"Custom (Advanced)":s.titleCase(R)},R))})]})]}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(n==null?void 0:n.showTotal)??!1,onCheckedChange:R=>p("showTotal",R)})]}),(n==null?void 0:n.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(n==null?void 0:n.anchor)||"center",onValueChange:R=>p("anchor",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((n==null?void 0:n.align)||"center"),onValueChange:R=>p("align",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:s.titleCase(R)},R))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(n==null?void 0:n.format)||(d?"auto":"none"),onValueChange:R=>p("format",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:S.map(R=>e.jsx(s.SelectItem,{value:R,className:"text-xs",children:R==="auto"&&d?"Auto (Use Axis)":R==="none"?"None (Raw Value)":s.titleCase(R)},R))})]})]}),(n==null?void 0:n.format)&&!["auto","none"].includes(n.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(n.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String(((E=n==null?void 0:n.formatOptions)==null?void 0:E.decimalPlaces)??(n.format==="currency"?2:n.format==="percent"?1:0)),onSave:R=>j("decimalPlaces",Number(R)),className:""})})]}),n.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((B=n==null?void 0:n.formatOptions)==null?void 0:B.currency)||"USD",onValueChange:R=>j("currency",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]}),["number","currency"].includes(n.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((w=n==null?void 0:n.formatOptions)==null?void 0:w.useSuffix)??!1,onCheckedChange:R=>j("useSuffix",R)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((D=n==null?void 0:n.formatOptions)==null?void 0:D.locale)||"en-US",onValueChange:R=>j("locale",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:v.map(R=>e.jsx(s.SelectItem,{value:R.value,className:"text-xs",children:R.label},R.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"12",value:String(((L=n==null?void 0:n.font)==null?void 0:L.size)||12),onSave:R=>g("size",Number(R)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((F=n==null?void 0:n.font)==null?void 0:F.weight)||"normal",onValueChange:R=>g("weight",R),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(n==null?void 0:n.color)==="auto"||!(n!=null&&n.color)?"auto":"custom",onValueChange:R=>{R==="auto"&&p("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(we,{type:"number",placeholder:"0",value:String((n==null?void 0:n.rotation)||0),onSave:R=>p("rotation",Number(R)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Hr(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[e.jsx(Pt,{}),e.jsx(zt,{}),e.jsx(_t,{}),e.jsx(Vt,{})]})]})}const Wr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),Kr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Qr=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Jr(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],o=l=>r.includes(a)?l:e.jsxs(e.Fragment,{children:[l,e.jsx(Hr,{})]});switch(a){case"stackedBar":case"stackedLine":return o(e.jsx(Pr,{}));case"tornado":case"pyramid":return o(e.jsx(Je,{docContent:Wr,cardType:a}));case"kpi":return e.jsx(Mr,{});case"line":case"bar":return o(e.jsx(Sr,{cardType:a}));case"range":return o(e.jsx(Je,{docContent:Kr,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return o(e.jsx(Je,{cardType:a}));case"bubble":case"scatter":return o(e.jsx(wr,{cardType:a}));case"table":return e.jsx(zr,{cardType:a});case"text":return e.jsx(Je,{docContent:Qr,cardType:a,suffix:"Visual"});case"map":return e.jsx(Fr,{});case"custom":return e.jsx(vr,{});default:return o(e.jsx(kr,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Gt({label:t,column:n,functions:a,onFunctionChange:r}){let o=a[0];"aggregate"in n?o=a.find(c=>c.value===n.aggregate)||a[0]:"granularity"in n&&(o=a.find(c=>c.value===n.granularity)||a[0]);function l(c){r(c)}return e.jsx(Ce,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:a,value:o.value,onValueChange:c=>l(c),label:t,showPlaceholderLabel:!1})}const Xr=[{label:"Sum",value:"SUM",logo:e.jsx(nt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(De,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(ba,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(aa,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(s.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(s.ArrowUp,{className:"size-3.5"})}];function Zr({column:t}){const{updateMetricColumnOld:n}=s.useEditorActions();let a=Xr;s.isTextDataType(t.type)&&(a=a.filter(o=>["COUNT","DISTINCT"].includes(o.value))),s.isNumberDataType(t.type)&&(a=a.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const l={...t,aggregate:o,label:He(t.name,o)};n(t.id,l)}return e.jsx(Gt,{column:t,functions:a,onFunctionChange:o=>r(o),label:"Aggregation"})}const el=[{label:"Day (D)",value:"day",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(s.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function sl({column:t}){const{updateGroupByColumnOld:n}=s.useEditorActions();function a(r){const o={...t,granularity:r,label:Ge(t.name,r)};n(t.id,o)}return e.jsx(Gt,{column:t,functions:el,onFunctionChange:r=>a(r),label:"Granularity"})}function tl({col:t,onChange:n,droppableId:a}){const{columns:r}=s.useDataColumns(),o=A.useMemo(()=>{let i=[];(a===Ae||a===Me||a===Le)&&(i=r);const d=i==null?void 0:i.filter(u=>u.column_name!==t.name);return d==null?void 0:d.map(u=>({id:u.column_name,value:u.column_name}))},[r,a,t.name]),l=[{id:t.name,value:t.name}];function c(i){const d=r==null?void 0:r.find(u=>{var m;return u.column_name===((m=i[0])==null?void 0:m.id)});d&&n(d)}return o!=null&&o.length?e.jsx(s.ComboBox2,{multiple:!1,options:o,selectedOptions:l,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:t.name})}function Ut({column:t}){const n=s.useEditorStore(d=>d.card.type),a=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(a==null?void 0:a.map(d=>d.label))||[],o=r==null?void 0:r.find(d=>d===t.label||d===t.name),l=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(Ot,{idx:l,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ft,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&i()]})}function al({column:t,type:n,onRemoveColumn:a,droppableId:r}){const[o,l]=A.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:i,updatePivotByColumnOld:d}=s.useEditorActions(),{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id,data:{type:n}}),x=p?{opacity:j?.5:void 0,transform:s.CSS.Translate.toString(p),transition:g}:void 0,b=s.isTextDataType(t.type);function f(C){const v=s.isNumberDataType(C.data_type),T=s.isTextDataType(C.data_type),y=s.isDateDataType(C.data_type),O=v?"number":T?"string":y?"date":"string";if(r===Ae){if(T){const E={id:t.id,name:C.column_name,type:O,role:"groupby"};c(t.id,E)}if(y){const E={id:t.id,name:C.column_name,type:O,role:"groupby",label:Ge(C.column_name,"month"),granularity:"month"};c(t.id,E)}}if(r===Le){if(T){const E={id:t.id,name:C.column_name,type:O,role:"groupby"};d(t.id,E)}if(y){const E={id:t.id,name:C.column_name,type:O,label:Ge(C.column_name,"month"),granularity:"month",role:"groupby"};d(t.id,E)}}if(r===Me){const E={id:t.id,name:C.column_name,type:O,role:"metric",label:He(C.column_name,"SUM"),aggregate:v?"SUM":"COUNT"};i(t.id,E)}}function N(){if(r===Me)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(Ut,{column:t})})}function k(){const C=s.isDateDataType(t.type);if(r===Me)return e.jsx(Zr,{column:t});if((r===Ae||r===Le)&&C)return e.jsx(sl,{column:t})}function I(){return e.jsx("div",{className:s.cn("grow",{"pl-3":(r===Ae||r===Le)&&b}),children:e.jsx(tl,{col:t,onChange:f,droppableId:r})})}function S(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>l(!o),children:o?e.jsx(Va,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(st,{className:s.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...m,...u,ref:h,style:x,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[S(),k(),I()]}),o&&N()]}),e.jsx("div",{className:s.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>a(t.id),children:e.jsx(s.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function gs({id:t,label:n,columns:a,previewColumns:r,sortableType:o,onRemoveColumn:l}){var x,b;const{setNodeRef:c,isOver:i,over:d}=s.useDroppable({id:t}),u=s.useDndStore(f=>f.activeId),m=s.useEditorStore(f=>{var N;return(N=f.card)==null?void 0:N.type}),h=i||((b=(x=d==null?void 0:d.data)==null?void 0:x.current)==null?void 0:b.type)===o,p=u?r:a,g=o===as?"Rows":o===ns?"Pivot Columns":"Columns";function j(){if(!p||p.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(f=>f.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md p-4",h&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(s.Label,{className:"text-sm",children:n}),m!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:g})]}),j(),e.jsx("div",{className:"space-y-2",children:p==null?void 0:p.map(f=>f.id===vt.id?e.jsx(nl,{},f.id):e.jsx(al,{droppableId:t,type:o,column:f,onRemoveColumn:l},f.id))})]})})}function nl(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function Yt({children:t,id:n,type:a}){const{attributes:r,listeners:o,setNodeRef:l,transform:c,transition:i,isDragging:d}=s.useSortable({id:n,data:{type:a}}),u=c?{opacity:d?.5:void 0,transform:s.CSS.Translate.toString(c),transition:i}:void 0;return e.jsx("div",{...o,...r,ref:l,style:u,children:t})}function rl(){const t=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.orderBy})||[],n=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.groupByColumns})||[],a=s.useEditorStore(f=>{var N;return(N=f.card.queryConfig)==null?void 0:N.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:l}=s.useEditorActions(),c=[...n,...a];if(c.length===0)return e.jsx(e.Fragment,{});const i=e.jsx(ra,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),d=e.jsx(ta,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=e.jsx(na,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),m=e.jsx(sa,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=c==null?void 0:c.filter(f=>!t.some(N=>N.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function p(f,N){const k=g(f);return k?k.role==="metric"?N==="asc"?u:m:N==="asc"?i:d:null}function g(f){return c.find(N=>N.id===f)}function j(f){const N=t.find(k=>k.columnId===f);if(N){const k={...N,direction:N.direction==="asc"?"desc":"asc"};l(k)}}const x=f=>{r({columnId:f.id,direction:"asc"})};function b(f){const N=t.find(k=>k.columnId===f);N&&o(N)}return e.jsx(s.SortableContext,{items:t.map(f=>Ye(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(s.Label,{className:"text-sm",children:"Sort By"}),h.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(s.ComboBox2,{multiple:!1,options:h,selectedOptions:[],onChange:f=>x(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),t.map(f=>{var N,k;return e.jsx(Yt,{id:Ye(f.columnId),type:Ts,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(st,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(cs,{className:"w-[175px] text-sm",children:((N=g(f.columnId))==null?void 0:N.label)||((k=g(f.columnId))==null?void 0:k.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>j(f.columnId),className:"rounded-sm p-0",children:p(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>b(f.columnId),className:"rounded-sm p-0",children:e.jsx(s.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Ye(f.columnId))})]})})}function ll(){const t=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),n=s.useEditorStore(b=>b.card.type),a=s.useDndStore(b=>b.previewGroupByColumns),r=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=s.useDndStore(b=>b.previewMetricColumns),l=s.useEditorStore(b=>{var f;return((f=b.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=s.useDndStore(b=>b.previewPivotColumns),{removeColumnFromGroupBy:i,removeColumnFromMetricColumns:d,removeColumnFromPivotBy:u}=s.useEditorActions();function m(b){i(b)}function h(b){d(b)}function p(b){u(b)}let g="Group By",j="Metrics",x="Stack By";return n==="table"&&(g="Rows",j="Metrics",x="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(Et,{iconClassName:"size-[19px]"}),e.jsxs(s.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(gs,{onRemoveColumn:m,sortableType:as,id:Ae,label:g,columns:t,previewColumns:a}),e.jsx(gs,{onRemoveColumn:p,sortableType:ns,id:Le,label:x,columns:l,previewColumns:c}),e.jsx(gs,{onRemoveColumn:h,sortableType:ys,id:Me,label:j,columns:r,previewColumns:o}),e.jsx(rl,{})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Ms({children:t,column:n,id:a,sortableType:r,className:o}){const[l,c]=A.useState(!1),{removeEditorFilter:i,clearEditorFilter:d}=s.useEditorActions(),u=s.useEditorStore(h=>{var p,g;return(g=(p=h.card.queryConfig)==null?void 0:p.filters)==null?void 0:g.some(j=>j.filterColumnName===n.name)});function m(h){i(h)}return e.jsx(Yt,{id:a,type:r,children:e.jsxs("div",{className:s.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":l}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-sm",children:n.name}),u&&e.jsx("button",{onClick:()=>d(n),children:e.jsx(s.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>m(n),children:e.jsx(s.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:s.cn("group flex items-center rounded-t-md text-sm",!l&&"rounded-b-md",l&&"border border-border"),children:[e.jsx("div",{children:e.jsx(s.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:s.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:t})]})]})})}function ol({column:t,sortableType:n}){const a=s.useDashboardStore(k=>k.themeStyle),r=s.useEditorStore(k=>{var I,S;return(S=(I=k.card)==null?void 0:I.queryConfig)==null?void 0:S.filters}),o=s.useEditorStore(k=>{var I,S;return(S=(I=k.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:S.find(C=>C.name===t.name)}),{selectedConnectionId:l,selectedDatabaseName:c,selectedTableName:i}=s.useEditorAside(),d=A.useMemo(()=>{var k;return(k=r==null?void 0:r.find(I=>I.filterColumnName===t.name))==null?void 0:k.filterValue},[r,t.name]),u=A.useMemo(()=>Array.isArray(d)?d.map(k=>({id:k,value:k})):[],[d]),{updateEditorFilterValue:m}=s.useEditorActions(),h={column:t.name,sql:t.sql,id:t.name,connectionId:l,dataType:t.type},{data:p,isLoading:g,isFetching:j,isError:x}=s.useFilterQuery(h),b=A.useMemo(()=>{var I;return h.column?(I=p==null?void 0:p.records)==null?void 0:I.map(S=>{let C=h.column.split(".").slice(-1)[0].replace(/"/g,"");return S[C]===void 0&&(C=C.toLowerCase()),{id:S[C],value:S[C]}}):[]},[p,h.column]);function f(k){const I=k.map(S=>S.id);m(t.name,I)}function N(){return g||j?e.jsx(s.Skeleton,{style:{borderRadius:a==null?void 0:a.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):x?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(s.ComboBox2,{renderFilterModeButton:()=>e.jsx(il,{columnName:t.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:b,onChange:f,selectedOptions:u,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(Ms,{className:"w-60",id:t.id,sortableType:n,column:t,children:N()})}function il({columnName:t}){const{setEditorFilterMode:n}=s.useEditorActions(),a=s.useEditorStore(o=>{var l,c;return(c=(l=o.card.queryConfig)==null?void 0:l.filterColumns)==null?void 0:c.find(i=>i.name===t)});function r(){(a==null?void 0:a.mode)==="exclude"?n(t,"include"):n(t,"exclude")}return e.jsx(s.Button,{onClick:r,variant:"secondary",size:"sm",className:s.cn("h-5 text-xs hover:underline",{}),children:s.titleCase((a==null?void 0:a.mode)==="exclude"?"exclude":"include")})}function cl({open:t,setOpen:n,dateRange:a,setDateRange:r,containerClassName:o,inputClassName:l,title:c,onApply:i,onClear:d}){const u=s.useDashboardStore(m=>m.themeStyle);return e.jsx("div",{className:s.cn("grid gap-2",o),children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{style:{borderRadius:u==null?void 0:u.controlInputRadius},asChild:!0,children:e.jsxs(s.Button,{size:"sm",id:"date",variant:"outline",className:s.cn("h-9 w-full justify-start rounded-sm text-left font-normal",!a&&"text-muted-foreground",l),children:[e.jsx(s.Calendar,{className:"mr-2 h-4 w-4"}),a!=null&&a.from?a.to?e.jsxs(e.Fragment,{children:[s.format(a.from,"LLL dd, y")," -"," ",s.format(a.to,"LLL dd, y")]}):s.format(a.from,"LLL dd, y"):e.jsx("span",{children:"Pick a date"})]})}),e.jsxs(s.PopoverContent,{style:{borderRadius:u==null?void 0:u.controlInputRadius},className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsx(s.Label,{children:c})}),e.jsx(s.Calendar$1,{initialFocus:!0,mode:"range",defaultMonth:a==null?void 0:a.from,selected:a,onSelect:r,numberOfMonths:2}),e.jsxs("div",{className:"flex justify-end gap-2 px-4 py-3",children:[e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:m=>{m.stopPropagation(),i(a),n(!1)},children:"Apply"}),e.jsx(s.Button,{style:{borderRadius:u==null?void 0:u.controlInputRadius},size:"sm",variant:"outline",onClick:d,children:"Clear"})]})]})]})})}function dl({column:t,sortableType:n}){const[a,r]=A.useState(!1),{selectedConnectionId:o,selectedDatabaseName:l,selectedTableName:c}=s.useEditorAside(),i={column:t.name,sql:t.sql,id:t.name,connectionId:o,title:"",dataType:t.type},{isLoading:d,isFetching:u,isError:m,data:h}=s.useFilterQuery(i),p=h==null?void 0:h.records,{dateRange:g,setDateRange:j,initialDateRange:x}=s.useDateRangeFromRecords(p),{updateEditorFilterValue:b}=s.useEditorActions();function f(I){var C,v;const S={gte:(C=I==null?void 0:I.from)==null?void 0:C.toISOString(),lte:(v=I==null?void 0:I.to)==null?void 0:v.toISOString()};b(t.name,S)}function N(){b(t.name,null,!0),j(x)}function k(){return d||u?e.jsx("div",{children:e.jsx(s.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):m?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):p?e.jsx(cl,{title:i.title,open:a,inputClassName:"h-8",setOpen:r,dateRange:g,setDateRange:j,onApply:f,onClear:N}):e.jsx(s.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(Ms,{className:"w-72",id:t.id,sortableType:n,column:t,children:k()})}function ul({id:t,label:n,columns:a,previewColumns:r,sortableType:o}){var j,x;const{setNodeRef:l,isOver:c,over:i}=s.useDroppable({id:t}),d=s.useDndStore(b=>b.activeId),u={},m=c||((x=(j=i==null?void 0:i.data)==null?void 0:j.current)==null?void 0:x.type)===o;function h(){if(!g||g.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function p(b){const f=s.isDateDataType(b.type);return b.id===vt.id?e.jsx(Ms,{id:b.id,sortableType:o,column:b,children:e.jsx(ml,{})},b.id):f?e.jsx(dl,{droppableId:t,sortableType:o,column:b},b.id):e.jsx(ol,{droppableId:t,sortableType:o,column:b},b.id)}const g=d?r:a;return e.jsx(s.SortableContext,{items:a==null?void 0:a.map(b=>b.id),children:e.jsxs("div",{className:s.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",m&&"border border-muted-foreground/20"),ref:l,style:u,children:[e.jsx(s.Label,{className:"text-sm",children:n}),h(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:g==null?void 0:g.map(b=>p(b))})]})})}function ml(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function hl(){const t=s.useEditorStore(o=>{var l;return((l=o.card.queryConfig)==null?void 0:l.filterColumns)||[]}),n=s.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:a}=s.useEditorActions();function r(o){a(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(ul,{onRemoveColumn:r,sortableType:Cs,id:Ns,label:"Filters",columns:t,previewColumns:n})})}function xl(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>c.showAIDialog),{setShowAIDialog:a}=s.useEditorActions(),{data:r,errorMessage:o,errorSql:l}=s.useDashboardCardQuery(t);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(os,{}),!n&&e.jsxs(s.Button,{onClick:()=>a(!0),variant:"secondary",size:"sm",children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(St,{sql:r==null?void 0:r.sql,error:o,errorSql:l})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(Es,{}),e.jsx(ks,{variant:"default"})]})]})}function pl(){const t=A.useRef(null),n=A.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog),o=s.useEditorStore(i=>i.isDevMode);A.useEffect(()=>{var i,d,u,m;r?((i=t.current)==null||i.resize(0),(d=n.current)==null||d.resize(0)):((u=t.current)==null||u.resize(25),(m=n.current)==null||m.resize(25))},[r]);function l(){return e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(nr,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Jr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Qe,{})})]}):e.jsx(Qe,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:a?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:n,defaultSize:25,maxSize:30,children:e.jsx(ll,{})})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(s.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(s.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx(xl,{}),e.jsx(hl,{})]}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(Qe,{})})]})})]}):e.jsx(Qe,{})})})}return e.jsx(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?l():c()})}function fl(t){s.useAIInteractionStore(G=>G.currentAIContext);const[n,a]=A.useState(""),[r,o]=A.useState(null),{authToken:l}=s.useSemaphorContext(),c=s.useEditorStore(G=>{var Y;return(Y=G==null?void 0:G.card)==null?void 0:Y.sql}),i=s.useEditorStore(G=>G.isDevMode),d=s.useEditorStore(G=>{var Y;return(Y=G==null?void 0:G.card)==null?void 0:Y.python}),{setCardPython:u,setCardSql:m,setRunSql:h,switchCardType:p,setQueryConfig:g}=s.useEditorActions(),j=s.useEditorStore(G=>G.currentAssitantScope)||[],x=s.useEditorStore(G=>G.userInputForAI),b=s.useEditorStore(G=>G.triggerAIRun),f=s.useEditorStore(G=>G.card),N=s.useEditorStore(G=>G.selectedDatabaseName),k=s.useEditorStore(G=>G.selectedTableName),I=s.useEditorStore(G=>G.selectedConnectionId),S=s.useEditorStore(G=>G.selectedSchemaName),C=s.useDashboardStore(G=>G.dashboard.aiScopeTables),{errorMessage:v,refetch:T,data:y}=s.useDashboardCardQuery(f),{setTriggerAIRun:O,setCurrentAssitantScope:E,setCardConfig:B}=s.useEditorActions(),{selectedDatamodelName:w,connectionType:D,selectedDatamodelId:L}=s.useEditorAside(),{messages:F,setMessages:R,regenerate:M,error:P,sendMessage:W,status:z,addToolResult:X,stop:te,clearError:K}=s.useChat({transport:new s.DefaultChatTransport({api:"https://semaphor.cloud/api/v1/assistant",headers:()=>({Authorization:`Bearer ${l==null?void 0:l.accessToken}`}),body:()=>{const G=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",isDevMode:i,aiContext:G.currentAIContext,reasoningEffort:G.reasoningEffort,showReasoning:G.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:G,body:Y})=>({body:{...Y,messages:s.cleanupIncompleteMessages(G)}})}),onError:G=>{console.log("on error",G)},onToolCall:H,onFinish(){a("")}});A.useEffect(()=>{b&&x&&(W({role:"user",parts:[{type:"text",text:x}]}),O(!1))},[b,x,W,O]);async function H({toolCall:G}){var Y,re,oe,le,xe,pe,me,fe,$,J,Z,q,ae,ie,ce,Ee;if(["createChartFromSql","createForecast"].includes(G.toolName)){const Be=((Y=G.input)==null?void 0:Y.sql)??((re=G.args)==null?void 0:re.sql),Te=((oe=G.input)==null?void 0:oe.python)??((le=G.args)==null?void 0:le.python),he=((xe=G.input)==null?void 0:xe.chartType)??((pe=G.args)==null?void 0:pe.chartType);p(he),m(Be),u(Te),h(!0),X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(G.toolName==="getUserSql"){if(!c){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",message:"No SQL found"}});return}X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",sql:c,python:d||""}})}else if(G.toolName==="generateQueryConfig"){a("Generating query config...");const Be=((me=G.input)==null?void 0:me.chartType)??((fe=G.args)==null?void 0:fe.chartType),Te=(($=G.input)==null?void 0:$.queryConfig)??((J=G.args)==null?void 0:J.queryConfig);((Z=G.input)==null?void 0:Z.cardConfig)??((q=G.args)==null||q.cardConfig),p(Be),B(Te),m(void 0),u(void 0);const he=await T();if((ae=he==null?void 0:he.data)!=null&&ae.error){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"error",queryConfig:Te,message:(ie=he==null?void 0:he.data)==null?void 0:ie.error.message}});return}if((ce=he==null?void 0:he.data)!=null&&ce.records){X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized"}});return}X({tool:G.toolName,toolCallId:G.toolCallId,output:{status:"success",queryConfig:Te,message:"The data has been visualized",records:(Ee=he==null?void 0:he.data)==null?void 0:Ee.records}})}else a("Analyzing...")}function U(G){const Y=s.removeFromScopeArray(j,G);ee(Y)}function ee(G){const Y=s.sanitizeAIScope(G);E(Y),R(re=>[...re,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Y)}`}]}])}function _(){const G={databaseName:N||"",schemaName:S||"",tableName:k||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||""},Y=s.dedup([...j,G]);ee(Y)}function V(){const G={databaseName:N||"",schemaName:S||"",tableName:k||"",datamodelName:s.resolveDatamodelName(w),connectionId:I||"",connectionType:D||"",datamodelId:L||""};if(!s.isInAiScopeArray([...C||[],...j],G)||j.length===0){const re=s.dedup([...C||[],...j,G]).filter(oe=>oe.connectionId===G.connectionId);ee(re)}}const se=!["ready","error"].includes(z),ne=s.getErrorMessage(P);return{messages:F,setMessages:R,sendMessage:W,regenerate:M,isLoading:se,handleSetAIScope:V,handleAddCurrentTableToScope:_,removeFromCurrentSelections:U,currentAssitantScope:j,setCurrentAssitantScope:E,stop:te,status:z,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:ne,clearError:K}}const gl=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ks(){const t=A.useRef(null),[n,a]=A.useState(!1),[r,o]=A.useState(s.isDevEnv),[l,c]=A.useState(!1),[i,d]=A.useState(!1),u=s.useCurrentAIContext(),{setCurrentAIContext:m}=s.useAIActions(),{clearQueue:h}=s.useQueueActions(),{clearFileAttachments:p}=s.useFileActions(),g=s.useFileAttachments("editor"),j=s.useDashboardStore(J=>J.dashboard.aiContext),x=s.useEditorStore(J=>J.card.dataSource),b=s.useEditorStore(J=>J.actions.setCardSql),f=s.useEditorStore(J=>J.actions.setRunSql),N=s.useEditorStore(J=>J.showAIDialog),k=s.useDashboardStore(J=>J.handleOpenAssistantProfile),{setShowAIDialog:I,setCardPython:S}=s.useEditorActions(),{setDataSource:C}=s.useEditorActions(),{assistantProfile:v}=s.useAssistantProfile(),{messages:T,setMessages:y,sendMessage:O,isLoading:E,stop:B,status:w,llmUsage:D,errorMessage:L,clearError:F}=fl(),[R,M]=A.useState(""),P=J=>{M(J.target.value)},W=J=>{J.preventDefault();const Z=R.trim();if(!Z&&g.length===0)return;const q=[];Z&&q.push({type:"text",text:Z}),g.forEach(ae=>{ae.data&&q.push({type:"file",mediaType:ae.type,filename:ae.name,url:`data:${ae.type};base64,${ae.data}`})}),O({role:"user",parts:q}),M(""),p("editor"),se({force:!0})},{visibleMessages:z,hasMoreMessages:X,totalMessageCount:te,loadMoreMessages:K,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:U,isAtBottom:ee,hasNewMessages:_,newMessageCount:V,scrollToBottom:se,handleScroll:ne,resetNewMessageCount:G}=s.useAutoScroll(z,{threshold:50,delay:0,dependencies:[w,T.length]});A.useEffect(()=>{var J;N&&((J=t.current)==null||J.focus(),m({selectedEntities:(x==null?void 0:x.selectedEntities)||[]}))},[N,x,m]),s.useAutoSubmitQueue({assistantType:"editor",status:w,isLoading:E,sendMessage:O});const{hasActiveTools:Y}=s.useActiveToolStatus(T);function re(J,Z){Z==="sql"?(b(J),f(!0)):Z==="python"&&(S(J),f(!0))}function oe(){var J;(J=j==null?void 0:j.selectedEntities)==null||J[0],d(!0)}function le(){u.selectedEntities.length===0&&m({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function xe(J){le();const Z={role:"user",parts:[{type:"text",text:J.title+" "+J.subtitle}]};O(Z)}function pe(J){le(),O({role:"user",parts:[{type:"text",text:J}]})}function me(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:a,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:r,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:c,children:"System Message"})]})]})}function fe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const $=(R==null?void 0:R.length)===0&&(T==null?void 0:T.filter(J=>J.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[fe(),k&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:k,children:(v==null?void 0:v.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[me(),s.isDevEnv,e.jsx(s.IconButton,{tooltip:"Add Context",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",onClick:oe,children:e.jsx(s.Settings,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",tooltip:"New Chat",onClick:()=>{y([]),h("editor"),F(),H()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground/50 hover:text-foreground",size:"sm",onClick:()=>{I(!1)},children:e.jsx(s.ArrowRightToLine,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:U,className:"mt-2 flex w-full grow basis-0",onScroll:ne,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[X&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:K,className:"text-xs",children:["Load ",Math.min(5,te-z.length)," more messages (",te-z.length," hidden)"]})}),e.jsx(s.PrintMessages,{messages:z,showTools:r,handleRun:re,showSystemMessage:l}),!Y&&e.jsx(s.AssistantStatus,{status:w,errorMessage:L})]})}),!ee&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),G()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),_&&V>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:V>9?"9+":V})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[$&&!v&&e.jsx(s.Placeholders,{onClick:xe,placeholders:gl}),e.jsx("div",{children:$&&v&&e.jsx(s.SeedQuestions,{seedQuestions:v.seedQuestions||[],handleSeedQuestionClick:pe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:t,setInput:M,stop:B,input:R,handleInputChange:P,handleSubmit:J=>{le(),W(J),se({force:!0})},isLoading:E,status:w,assistantType:"editor",onFocus:()=>{}})]}),D&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",D.inputTokens," prompt tokens, ",D.outputTokens," ","completion tokens, ",D.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(x==null?void 0:x.selectedEntities)||[],open:i,onOpenChange:d,dataSource:x||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}const Ls=t=>{var E;const{updateCardConfig:n,updateGroupByColumn:a,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:l,removeGroupByColumn:c,removeMetricColumn:i,removePivotByColumn:d,removeSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(B=>B.card.type),h=t==null?void 0:t.id,p=A.useCallback(B=>{if(!(t!=null&&t.config))return[];switch(B){case"groupBy":return(t.config.groupByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,dateFormat:w.dateFormat,customFormat:w.customFormat,granularity:w.granularity}));case"metrics":return t.config.metricColumns||[];case"pivotBy":return(t.config.pivotByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType}));case"sortBy":return(t.config.sortByColumns||[]).map(w=>({id:w.id,name:w.name,dataType:w.dataType,label:w.label!==void 0?w.label:w.name,qualifiedEntityName:w.qualifiedEntityName,entityId:w.entityId,entityName:w.entityName,entityType:w.entityType,direction:w.direction}));case"source":return[];default:return[]}},[t]),g=A.useCallback((B,w)=>{if(h)switch(B){case"groupBy":{n(h,{groupByColumns:w});break}case"metrics":{n(h,{metricColumns:w});break}case"pivotBy":{n(h,{pivotByColumns:w});break}case"sortBy":{n(h,{sortByColumns:w});break}}},[h,n]),j=A.useCallback((B,w,D)=>{if(!h)return;const F=p(B)[w];if(F)switch(B){case"groupBy":a(h,F.id,{label:D});break;case"metrics":r(h,F.id,{label:D});break;case"pivotBy":o(h,F.id,{label:D});break;case"sortBy":l(h,F.id,{label:D});break}},[h,p,a,r,o,l]),x=A.useCallback((B,w)=>{if(!h)return;const L=p("metrics")[B];L&&r(h,L.id,{aggregate:w,label:s.getAggregationLabel(L.name,w)})},[h,p,r]),b=A.useCallback((B,w,D)=>{if(!h)return;const F=p("groupBy")[B];if(!F)return;const R={dateFormat:w};w==="custom"&&D?R.customFormat=D:R.customFormat=void 0,a(h,F.id,R)},[h,p,a]),f=A.useCallback((B,w)=>{if(!h)return;const L=p("groupBy")[B];L&&a(h,L.id,{granularity:w})},[h,p,a]),N=A.useCallback((B,w)=>{if(!h)return;const L=p("metrics")[B];L&&r(h,L.id,{aliasTemplate:w})},[h,p,r]),k=A.useCallback((B,w)=>{if(console.log("handleValueAliasesChange",B,w),!h)return;console.log("handleValueAliasesChange",B,w);const L=p("metrics")[B];L&&(console.log("handleValueAliasesChange",w),r(h,L.id,{valueAliases:w}))},[h,p,r]),I=A.useCallback(B=>{h&&n(h,{comparisonType:B})},[h,n]),S=A.useCallback(B=>{h&&n(h,{showTrendline:B})},[h,n]),C=A.useCallback(B=>{h&&n(h,{trendlineWindow:B})},[h,n]),v=A.useCallback(B=>{h&&n(h,{trendlineGranularity:B})},[h,n]),T=A.useCallback(B=>{h&&n(h,{targetValue:B})},[h,n]),y=A.useCallback(B=>{var P;if(!h)return;const w=[...p("groupBy"),...p("pivotBy"),...p("metrics"),...p("sortBy")],D=(P=t==null?void 0:t.config)==null?void 0:P.joinPlan,L=s.validateEntityConsistency(B,w,D);if(!L.isValid){L.showError&&s.showJoinRequiredNotification();return}const F=s.getSmartContainerForField(B,w),R=p(F);if(s.fieldAlreadyExists(B,R))return;const M=s.getNewField(B,F,R);M&&g(F,[...R,M])},[h,(E=t==null?void 0:t.config)==null?void 0:E.joinPlan,p,g]),O=A.useCallback((B,w)=>{if(!h)return;const L=p(B)[w];if(L){if(B!=="sortBy"){const F=p("sortBy"),R=F.filter(M=>!(M.name===L.name&&M.qualifiedEntityName===L.qualifiedEntityName));R.length!==F.length&&n(h,{sortByColumns:R})}switch(B){case"groupBy":c(h,L.id);break;case"metrics":i(h,L.id);break;case"pivotBy":d(h,L.id);break;case"sortBy":u(h,L.id);break}}},[h,p,c,i,d,u,n]);return{getFieldsForContainer:p,setFieldsForContainer:g,updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:O,handleFieldClick:y,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:S,handleKpiTrendlineWindowChange:C,handleKpiTrendlineGranularityChange:v,handleKpiTargetValueChange:T,cardType:m}};function jl({field:t}){return e.jsxs("div",{className:"w-64 bg-background p-0",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-foreground",children:t.label||t.name}),e.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:t.dataType})]}),t.description&&e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:t.description}),e.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:t.name})})]})}function bl({field:t}){const{attributes:n,listeners:a,setNodeRef:r,transform:o,transition:l,isDragging:c}=s.useSortable({id:t.id}),[i,d]=A.useState(!1),u=s.useEditorStore(j=>j.card),{handleFieldClick:m}=Ls(u),h={transform:s.CSS.Transform.toString(o),transition:l};s.getDataType(t.dataType);const p=j=>{const x=(j||"").toLowerCase();switch(s.getDataType(x)){case"number":return De;case"date":return s.Calendar;case"boolean":return Re;case"json":return _e;case"geo":return $e;default:return ve}},g=j=>{const x=(j||"").toLowerCase(),b=s.getDataType(x);return b==="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"})}):b==="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"})}):b==="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"})}):b==="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"})}):b==="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(_e,{className:"h-3 w-3"})}):b==="geo"?e.jsx("div",{className:"bg-orange -100 flex size-6 shrink-0 items-center justify-center rounded-sm text-xs text-orange-700 dark:bg-orange-950 dark:text-orange-300",children:e.jsx($e,{className:"h-3 w-3"})}):b==="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(We,{className:"h-3 w-3"})}):null};return p(t.dataType),e.jsxs("div",{ref:r,style:h,...n,...a,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:bg-muted"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:()=>m(t),children:[g(t.dataType),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-xs text-foreground/80 hover:text-foreground dark:text-muted-foreground ${i?"whitespace-normal break-words":"truncate"}`,children:t.label||t.name})})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:e.jsx(jl,{field:t})})]})})]}),i&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(s.Card,{className:"",children:e.jsxs(s.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.label||t.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:t.name})]}),e.jsx(s.Badge,{variant:"outline",className:"mt-2 text-xs",children:t.dataType})]})})})]})}function vl(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),o=s.useEditorStore(k=>k.card.dataSource),{columns:l=[],columnGroups:c=[],isLoading:i,error:d}=s.useColumns(),u=l.filter(k=>k.name.toLowerCase().includes(t.toLowerCase())||k.dataType.toLowerCase().includes(t.toLowerCase())||k.qualifiedEntityName&&k.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),m=k=>{if(k.dataType==="number"||k.dataType==="integer"||k.dataType==="float"||k.dataType==="decimal"||k.dataType==="currency")return"metrics";const I=s.getDataType(k.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},p=(a==="all"?u:u.filter(k=>m(k)===a)).reduce((k,I)=>{const S=I.qualifiedEntityName||"Other Fields";return k[S]||(k[S]={label:s.toLabel(I.entityName),fields:[]}),k[S].fields.push(I),k},{}),j=Object.keys(p),x=u.filter(k=>m(k)==="dimensions").length,b=u.filter(k=>m(k)==="metrics").length,f=u.filter(k=>m(k)==="calculated").length,N=u.length>0;return i?e.jsx("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:d.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(s.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[l.length>0&&e.jsxs("div",{className:"relative mb-4",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(s.Input$1,{className:"pl-10",type:"text",placeholder:"Search fields...",value:t,onChange:k=>n(k.target.value)})]}),N&&e.jsx(s.Tabs,{defaultValue:"all",value:a,onValueChange:k=>r(k),className:"mb-4",children:e.jsxs(s.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(s.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(s.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(s.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x})]}),e.jsxs(s.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(s.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:b})]}),e.jsxs(s.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(We,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(s.CustomScrollArea,{className:"py-2",children:[e.jsx(s.Accordion,{type:"multiple",defaultValue:j,className:"space-y-2",children:Object.entries(p).map(([k,I])=>{const S=c.find(C=>C.entityName===k)||{entityName:k,label:I.label};return e.jsxs(s.AccordionItem,{value:k,className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:e.jsxs("div",{title:S.label||S.entityName,className:"flex items-center gap-2",children:[e.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:S.label||S.entityName}),e.jsx(s.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),e.jsx(s.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:I.fields.map(C=>e.jsx(bl,{field:C},C.id))})})]},k)})}),Object.keys(p).length===0&&l.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(p).length===0&&l.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(s.ScrollBar,{orientation:"horizontal"}),e.jsx(s.ScrollBar,{orientation:"vertical"})]})]})}function yl(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(vl,{})," "]})}function Nl({initialJoinPlan:t,availableDataSources:n}){const[a,r]=A.useState(t),[o,l]=A.useState(new Set),c=()=>{const C=a.joins.length>0?Math.max(...a.joins.map(T=>T.sequence))+1:1,v={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:C,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,v]}),l(new Set([...o,v.id]))},i=C=>{r({...a,joins:a.joins.filter(v=>v.id!==C)}),l(new Set([...o].filter(v=>v!==C)))},d=(C,v)=>{var E,B;const T=a.joins.find(w=>w.id===C);if(!T)return;const y={...T,...v},O=a.joins.map(w=>w.id===C?y:w);if((E=y.source)!=null&&E.name&&((B=y.target)!=null&&B.name)&&y.joinKeyGroups[0].keys.length===0){const w=n.find(R=>{var M;return R.name===((M=y.source)==null?void 0:M.name)}),D=n.find(R=>{var M;return R.name===((M=y.target)==null?void 0:M.name)}),L={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},operator:"="},F=[...y.joinKeyGroups];F[0]={...F[0],keys:[L]},y.joinKeyGroups=F,O[O.findIndex(R=>R.id===C)]=y}r({...a,joins:O})};return{joinPlan:a,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:i,updateJoin:d,moveJoinUp:C=>{const v=a.joins.findIndex(T=>T.id===C);if(v>0){const T=[...a.joins],y={...T[v]},O={...T[v-1]};T[v]=O,T[v-1]=y,T.forEach((B,w)=>{B.sequence=w+1});const E={...a,joins:T};r(E)}},moveJoinDown:C=>{const v=a.joins.findIndex(T=>T.id===C);if(v<a.joins.length-1){const T=[...a.joins],y={...T[v]},O={...T[v+1]};T[v]=O,T[v+1]=y,T.forEach((B,w)=>{B.sequence=w+1});const E={...a,joins:T};r(E)}},toggleJoinExpansion:C=>{const v=new Set(o);v.has(C)?v.delete(C):v.add(C),l(v)},getAvailableSourceEntities:C=>{if(a.joins.length===0)return n;const v=a.joins.findIndex(y=>y.id===C);if(v===0)return n;const T=new Set;return a.baseEntity.name&&T.add(a.baseEntity.name),a.joins.slice(0,v).forEach(y=>{T.add(y.source.name),T.add(y.target.name)}),n.filter(y=>T.has(y.name))},getAvailableTargetEntities:C=>n.filter(v=>v.name!==C),addJoinKeyGroup:C=>{const v=a.joins.find(y=>y.id===C);if(!v)return;const T=[...v.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];d(C,{joinKeyGroups:T})},updateGroupOperator:(C,v,T)=>{const y=a.joins.find(E=>E.id===C);if(!y)return;const O=[...y.joinKeyGroups];O[v]={...O[v],operator:T},d(C,{joinKeyGroups:O})},removeJoinKeyGroup:(C,v)=>{const T=a.joins.find(O=>O.id===C);if(!T)return;const y=[...T.joinKeyGroups];y.splice(v,1),d(C,{joinKeyGroups:y})},addJoinKey:(C,v)=>{const T=a.joins.find(w=>w.id===C);if(!T)return;const y=n.find(w=>w.name===T.source.name),O=n.find(w=>w.name===T.target.name),E=[...T.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(y==null?void 0:y.name)||"",entityName:(y==null?void 0:y.name)||"",entityType:(y==null?void 0:y.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(O==null?void 0:O.name)||"",entityName:(O==null?void 0:O.name)||"",entityType:(O==null?void 0:O.type)||"table"},operator:"="};E[v]={...E[v],keys:[...E[v].keys,B]},d(C,{joinKeyGroups:E})},updateJoinKey:(C,v,T,y,O)=>{const E=a.joins.find(F=>F.id===C);if(!E)return;const B=n.find(F=>F.name===E.source.name),w=n.find(F=>F.name===E.target.name),D=[...E.joinKeyGroups],L=D[v].keys[T];y==="sourceColumnName"&&B?D[v].keys[T]={...L,source:{...L.source,name:O}}:y==="targetColumnName"&&w?D[v].keys[T]={...L,target:{...L.target,name:O}}:y==="operator"&&(D[v].keys[T]={...L,operator:O}),d(C,{joinKeyGroups:D})},removeJoinKey:(C,v,T)=>{const y=a.joins.find(E=>E.id===C);if(!y)return;const O=[...y.joinKeyGroups];O[v].keys.splice(T,1),d(C,{joinKeyGroups:O})},generateSQLPreview:()=>{const C=[...a.joins].sort((y,O)=>y.sequence-O.sequence),v=a.baseEntity;if(!v.name)return"SELECT * FROM table -- Please select a base entity";let T=`SELECT *
349
349
  FROM ${v.name}`;return C.forEach(y=>{const O=n.find(w=>w.name===y.target.name);if(!O)return;const E=y.joinKeyGroups.filter(w=>w.keys&&w.keys.length>0).map(w=>{const D=w.keys.filter(L=>{var F,R,M,P;return((F=L.source)==null?void 0:F.name)&&((R=L.target)==null?void 0:R.name)&&((M=L.source)==null?void 0:M.entityName)&&((P=L.target)==null?void 0:P.entityName)}).map(L=>`${L.source.entityName}.${L.source.name} ${L.operator} ${L.target.entityName}.${L.target.name}`);return D.length>1?`(${D.join(` ${w.operator} `)})`:D[0]}).filter(Boolean),B=E.length>1?E.join(" OR "):E[0]||"condition_here";T+=`
350
350
  ${y.joinType} JOIN ${O.name}
351
351
  ON ${B}`}),T},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(y=>!y.source.name||!y.target.name)||a.joins.some(y=>y.joinKeyGroups.some(O=>O.keys.length===0))||a.joins.some(y=>y.joinKeyGroups.some(O=>O.keys.some(E=>!E.source.name||!E.target.name||!E.operator))))}}function Cl({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:o}){const{setCardConfig:l}=s.useEditorActions();s.useEditorStore(E=>E.card.config);const{columnGroups:c}=s.useColumns(),{joinPlan:i,expandedJoins:d,setJoinPlan:u,addJoin:m,removeJoin:h,updateJoin:p,moveJoinUp:g,moveJoinDown:j,toggleJoinExpansion:x,getAvailableSourceEntities:b,getAvailableTargetEntities:f,addJoinKeyGroup:N,updateGroupOperator:k,removeJoinKeyGroup:I,addJoinKey:S,updateJoinKey:C,removeJoinKey:v,generateSQLPreview:T,isValidConfiguration:y}=Nl({initialJoinPlan:t,availableDataSources:n}),O=E=>{const B=c.find(w=>w.entityName===E);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:E=>{const B=n.find(w=>w.name===E);u({...i,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:E,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(E=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:E.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:E.type}),E.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},E.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:T()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:m,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.joins.length===0?e.jsx("div",{className:"rounded-lg border border-dashed py-8 text-center text-muted-foreground",children:e.jsx("p",{children:"No joins configured. Add a join to connect multiple data sources."})}):e.jsx("div",{className:"max-h-[300px] space-y-4 overflow-y-auto",children:i.joins.map(E=>{const B=n.find(L=>L.name===E.source.name),w=n.find(L=>L.name===E.target.name),D=d.has(E.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{children:E.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",E.sequence,B&&w&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",w.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>g(E.id),disabled:E.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(E.id),disabled:E.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>x(E.id),children:D?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>h(E.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),D&&e.jsxs(s.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:E.source.name,onValueChange:L=>{const F=n.find(R=>R.name===L);p(E.id,{source:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:L,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:b(E.id).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name]})},L.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:E.joinType,onValueChange:L=>p(E.id,{joinType:L}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:E.target.name,onValueChange:L=>{const F=n.find(R=>R.name===L);p(E.id,{target:{connectionId:(F==null?void 0:F.connectionId)||"",connectionType:(F==null?void 0:F.connectionType)||"none",type:(F==null?void 0:F.type)||"table",name:L,database:F==null?void 0:F.database,schema:F==null?void 0:F.schema}})},disabled:!E.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:E.source.name?f(E.source.name).map(L=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:L.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:L.type}),L.name,L.name===E.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},L.name)):[]})]})]})]}),E.source.name&&E.target.name&&B&&w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>N(E.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),E.joinKeyGroups.length===0?e.jsx("div",{className:"rounded-md border p-3 text-center text-sm text-gray-500",children:"No join conditions defined. Add condition groups to specify how data sources should be joined."}):e.jsx("div",{className:"space-y-4",children:E.joinKeyGroups.map((L,F)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Label,{children:["Group ",F+1]}),F>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Select,{value:L.operator,onValueChange:R=>k(E.id,F,R),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(E.id,F),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[L.keys.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-center text-sm text-gray-500",children:"No conditions in this group. Add conditions to specify join criteria."}):e.jsx("div",{className:"space-y-2",children:L.keys.map((R,M)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[M>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:L.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:P=>C(E.id,F,M,"sourceColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:O(E.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(s.Select,{value:R.operator,onValueChange:P=>C(E.id,F,M,"operator",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.target.name,onValueChange:P=>C(E.id,F,M,"targetColumnName",P),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:O(E.target.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:P.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:P.dataType})]})},P.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>v(E.id,F,M),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||M))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>S(E.id,F),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},L.id))})]})]})]},E.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!y(),children:"Save"})]})]})}function Qs({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:o,onRemove:l,onSave:c,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Cl,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:i,onRemove:l})]}),t]})}function Sl({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...t].sort((c,i)=>c.sequence-i.sequence),l=a.find(c=>c.name===n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:l==null?void 0:l.type}),e.jsx("span",{className:"text-xs font-medium",children:l==null?void 0:l.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const i=a.find(d=>d.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(s.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((o,l)=>o.sequence-l.sequence).map((o,l)=>{const c=a.find(d=>d.name===o.source.name),i=a.find(d=>d.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:l+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)," ","condition",o.joinKeyGroups.reduce((d,u)=>d+u.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function wl(){var m,h;const t=s.useEditorStore(p=>p.card),n=s.useEditorStore(p=>p.actions.updateCardConfig),a=((m=t==null?void 0:t.config)==null?void 0:m.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=A.useState(!1),l=((h=t==null?void 0:t.dataSource)==null?void 0:h.selectedEntities)||[],c=p=>{n(t.id,{...t==null?void 0:t.config,joinPlan:p}),o(!1)},i=()=>{n(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},d=()=>{o(!1)},u=()=>{const p=[...a.joins].sort((x,b)=>x.sequence-b.sequence),g=a.baseEntity;if(!g.name)return"SELECT * FROM table -- Please select a base entity";let j=`SELECT *
352
352
  FROM ${g.name}`;return p.forEach(x=>{const b=l.find(k=>k.name===x.target.name);if(!b)return;const f=x.joinKeyGroups.filter(k=>k.keys&&k.keys.length>0).map(k=>{const I=k.keys.filter(S=>{var C,v,T,y;return((C=S.source)==null?void 0:C.name)&&((v=S.target)==null?void 0:v.name)&&((T=S.source)==null?void 0:T.entityName)&&((y=S.target)==null?void 0:y.entityName)}).map(S=>`${S.source.entityName}.${S.source.name} ${S.operator} ${S.target.entityName}.${S.target.name}`);return I.length>1?`(${I.join(` ${k.operator} `)})`:I[0]}).filter(Boolean),N=f.length>1?f.join(" OR "):f[0]||"condition_here";j+=`
353
353
  ${x.joinType} JOIN ${b.name}
354
- ON ${N}`}),j};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[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:()=>o(!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(Sl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(Qs,{open:r,onOpenChange:o,joinPlan:a,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Qs,{open:r,onOpenChange:o,joinPlan:a,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Dl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:o}=s.useEditorActions(),l=s.useDashboardStore(x=>x.dashboard.aiContext),c=(l==null?void 0:l.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(b=>b.some(N=>N.name===x.name&&N.type===x.type)?b.filter(N=>!(N.name===x.name&&N.type===x.type)):[...b,x])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],b=x.connectionId||"",f=x.connectionType||"",k=a.some(S=>S.type==="dataset")?"semanticDomain":"database";o({connectionId:b,connectionType:f,mode:k,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ha,{className:"h-4 w-4"});case"model":return e.jsx(pa,{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"})}},p=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const b=[];return x.database&&b.push(x.database),x.schema&&b.push(x.schema),x.name&&b.push(x.name),b.join(".")},j=x=>a.some(b=>b.name===x.name&&b.type===x.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((x,b)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${b}`))})})]}),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 Tl({entity:t,title:n,maxDetails:a=10}){const o=s.getEntityDetails(t).slice(0,a),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function kl({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),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function El({isVisible:t,onToggleVisibility:n}){const[a,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(p=>p.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((p,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(p),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(b=>!(b.name===p.name&&b.type===p.type));u({...m,...d,selectedEntities:x})},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(Tl,{entity:p})]},`${p.type}-${p.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(kl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(wl,{})]})]}),e.jsx(yl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(Dl,{open:o,onOpenChange:l})]})}const Il="chart-selector-standard-first";function Al(){const[t,n]=s.useLocalStorageState(Il,!0);return{standardFirst:t,updatePreference:n}}const Js=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=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"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Xs=["default","standardPlugin","customPlugin"];function Ml({selectedChart:t,onChartChange:n}){var I;const[a,r]=A.useState(!1),{data:o}=kt();Al();const c=((I=s.useEditorStore(S=>S.card).customCardPreferences)==null?void 0:I.url)||"";ws(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(S=>S.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...Xs.filter(S=>S!==g)]:Xs,[g]);function b(S){m(null),d({}),i(S),["custom","map"].includes(S)&&(u(!0),p(void 0)),n(S),r(!1)}function f(S){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:S.url,componentName:S.name,icon:S.icon,pluginChartType:S.chartType}),p(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 S=s.chartTypes.find(v=>v.id===t);return(S==null?void 0:S.label)||"Select chart type"},k=()=>{var C,v;if(t==="custom"){const T=s.useEditorStore.getState().card,y=(C=T==null?void 0:T.customCardPreferences)==null?void 0:C.icon,O=(v=T==null?void 0:T.customCardPreferences)==null?void 0:v.componentName;if(y&&O)return e.jsx(Ll,{icon:y,componentName:O});if(O){const E=s.getAutoDetectedChartIcon(O);if(E)return E}return e.jsx(qe,{className:"h-4 w-4"})}const S=s.chartTypes.find(T=>T.id===t);if(S){const T=S.icon;return e.jsx(T,{className:"h-4 w-4"})}return e.jsx(qe,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",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:[k(),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."}),x.map(S=>{if(S==="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=>j(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:()=>b(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(S==="standardPlugin"){const C=o.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=>j(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,T)=>e.jsx(Js,{pluginVisual:v,index:T,onSelect:()=>f(v)},`${v.url}-${v.name}-${T}`))},"standardPlugin"):null}if(S==="customPlugin"){const C=o.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=>j(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,T)=>e.jsx(Js,{pluginVisual:v,index:T,onSelect:()=>f(v)},`${v.url}-${v.name}-${T}`))},"customPlugin"):null}return null})]})]})})]})})}const Ll=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},Rl=[{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 Ol({selectedChart:t,onChartChange:n}){var o;const a=s.useEditorStore(l=>l.card),r=((o=a==null?void 0:a.config)==null?void 0:o.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:Rl.map(l=>{if(l.requiresPivot&&!r)return null;const c=l.icon,i=t===l.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(l.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:l.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:l.label})})]},l.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 Fl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[o,l]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?a:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&a!==t?(n(a),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&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),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Bl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[o,l]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const p={...t};delete p[h],n(p)},m=h=>{const p={...t};delete p[h],p[o]=c,n(p),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,p],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:o,onChange:j=>l(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(p)},"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 Pl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),o=s.useEditorStore(d=>d.card),l=o==null?void 0:o.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={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},u={connection_id:l.connectionId,cardConfig:d,cardDataSource:l,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",u);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",u);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function zl({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:o,onSave:l}){var k,I;const c=!!o,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,p]=A.useState({id:(o==null?void 0:o.id)||s.v4(),field:(o==null?void 0:o.field)||null,selectedValues:o?Array.isArray(o.value)?o.value:[o.value]:[]}),g=a.filter(S=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(T=>T.field.id===S.id))&&S.label.toLowerCase().includes(u.toLowerCase())}),j=S=>{p({...h,field:S}),d("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const S={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let C;if(c){const v=((r==null?void 0:r.conditions)||[]).map(T=>T.id===o.id?S:T);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,S],groups:[]}}l(C),n(!1)}},b=()=>{if(!c||!o)return;const S=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==o.id);if(S.length>0){const C={...r,conditions:S};l(C)}else l(void 0);n(!1)},f=S=>{p({...h,selectedValues:S})},N=()=>{c&&o?(p({id:o.id,field:o.field,selectedValues:Array.isArray(o.value)?o.value:[o.value]}),d("values")):(p({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&N()},[t,c,o]),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: ${(k=h.field)==null?void 0:k.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(S=>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:[S.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(S.value)?`${S.value.length} values`:String(S.value)})]},S.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:S=>m(S.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(S=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(S),children:[e.jsx(Rs,{dataType:s.getDataType(S.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:S.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[S.entityName,".",S.name]})]})]},S.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(_l,{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:b,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:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function _l({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[o,l]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Pl({field:t,searchQuery:o,limit:500}),u=o?c.filter(p=>String(p.value).toLowerCase().includes(o.toLowerCase())):c,m=p=>{const g=n.includes(p);a(g?n.filter(j=>j!==p):[...n,p])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.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:o,onChange:p=>l(p.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(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>m(p.value)}),e.jsx(cs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Vl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var Bs,Ps,zs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(Q=>Q.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:I,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:T,handleKpiTargetValueChange:y}=Ls(g),[O,E]=A.useState(!1),[B,w]=A.useState(!1),[D,L]=A.useState(null),[F,R]=A.useState(t.dateFormat||"YYYY-MM-DD"),[M,P]=A.useState(t.customFormat||""),[W,z]=A.useState(!!t.customFormat),[X,te]=A.useState(t.granularity||"day"),[K,H]=A.useState(t.aliasTemplate||""),[U,ee]=A.useState(t.valueAliases||{}),[_,V]=A.useState((Bs=t.parameters)==null?void 0:Bs.filters),se=Q=>{Q==="custom"?z(!0):(z(!1),R(Q),n==="groupBy"&&b(a,Q,""))},ne=Q=>{P(Q),n==="groupBy"&&b(a,"custom",Q)},G=Q=>{var ge;te(Q);const ue=(ge=J(Q)[0])==null?void 0:ge.value;ue&&!W&&(R(ue),n==="groupBy"&&b(a,ue,"")),n==="groupBy"&&f(a,Q)},Y=Q=>{H(Q),n==="metrics"&&N(a,Q)},re=Q=>{ee(Q),n==="metrics"&&k(a,Q)},oe=Q=>{j(n,a,Q)},le=Q=>{var de;if(V(Q),n==="metrics"){const ue={...t,parameters:{...t.parameters,filters:Q}},ge=[...((de=g.config)==null?void 0:de.metricColumns)||[]];ge[a]=ue,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ge})}w(!1)},xe=()=>{I(n,a)},pe={transform:s.CSS.Transform.toString(m),transition:h},me=s.getDataType(t.dataType),fe=me==="date",$=c==="kpi",J=Q=>{switch(Q){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..."}]}},Z=J(X),q=n!=="pivotBy",ae=fe&&n==="groupBy",ie=!$&&fe&&n==="groupBy",ce=$&&fe&&n==="groupBy",Ee=$&&n==="metrics"&&((Ps=g.config)==null?void 0:Ps.comparisonType)==="target",Be=n==="metrics",Te=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Q=>{Q.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}`}),he=()=>q?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:oe,placeholder:"Display label...",type:"text"})]}):null,Fs=()=>ae?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:X,onValueChange:G,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(Q=>e.jsx(s.SelectItem,{className:"text-xs",value:Q,children:s.toTitleCase(Q)},Q))})]})]}):null,Ht=()=>ie?e.jsxs(e.Fragment,{children:[Fs(),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:W?"custom":F,onValueChange:se,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:Z.map(Q=>e.jsx(s.SelectItem,{className:"text-xs",value:Q.value,children:Q.label},Q.value))})]}),W&&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:M,onChange:Q=>{Q.stopPropagation(),ne(Q.target.value)},onClick:Q=>Q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Wt=()=>{var Q,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:((Q=g.config)==null?void 0:Q.comparisonType)||"none",onValueChange:S,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:Ke=>{const Zt=parseInt(Ke.target.value)||30;v(Zt)},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:T,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},Kt=()=>{var Q,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:((Q=g.config)==null?void 0:Q.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},Qt=()=>Be?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:Q=>{x(a,Q)},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(Q=>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(Q),w(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.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(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.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 (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.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!==Q.id);if(ue.length>0){const ke={..._,conditions:ue};le(ke)}else if(V(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Ke=[...((ge=g.config)==null?void 0:ge.metricColumns)||[]];Ke[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ke})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{L(null),w(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Ut,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Fl,{aliasTemplate:K,onAliasTemplateChange:Y}),e.jsx(Bl,{valueAliases:U,onValueAliasesChange:re})]})]}):null,{columns:Jt=[]}=s.useColumns(),Xt=(_==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 ${p?"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-sm",Xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((zs=_==null?void 0:_.conditions)==null?void 0:zs.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(Q=>e.jsxs("div",{children:[Q.field.label,":"," ",Array.isArray(Q.value)?`${Q.value.length} values`:String(Q.value)]},Q.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Q=>{Q.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 group-hover:opacity-100",onClick:Q=>{Q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const de=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",de),o(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 opacity-0 group-hover:opacity-100",onClick:Q=>{Q.stopPropagation(),xe()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[Te(),he(),c==="kpi"&&Fs(),Ht(),Wt(),Kt(),Qt()]})]}),B&&e.jsx(zl,{open:B,onOpenChange:Q=>{w(Q),Q||L(null)},availableFields:Jt,existingFilters:_,editingCondition:D,onSave:Q=>{var de;if(Q)le(Q);else if(V(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 Gl({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 Xe({zone:t,fields:n,label:a,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(j=>j.card),m=s.useEditorStore(j=>j.card.type),h=n.length>0,p=(j,x)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(N=>N.id===j)===-1||d(u.id,j,{direction:x})};if(t==="sortBy"&&o===!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(Gl,{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(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,x)=>{const f=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Vl,{field:j,zone:t,index:x,sortDirection:f,onSortDirectionChange:N=>p(j.id,N),hasPivotColumns:l,cardType:m})})},j.id)})})})})]})}const Zs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Ul=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,o]=A.useState(!1),[l,c]=A.useState(!1),i=()=>{const d=Zs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Zs[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:o,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:Ul.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),o(!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),o(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),l&&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(Bt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const Ze={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%
355
- 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 Yl(){var i,d,u,m,h,p,g,j,x,b;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 l=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var k;const N={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...l,...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(va,{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:l.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!l.calculationType?{calculationType:"difference"}:{}})})]}),l.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:l.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(Ze).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,k,I;const f=l.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=Ze[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:(k=Ze[f])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(I=Ze[f])==null?void 0:I.example]})]})})()]}),e.jsx(As,{formatOptions:l.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:l.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:l.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:l.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(js,{value:((h=l.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...l.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((p=l.colorConfig)==null?void 0:p.decrease)||"red",onChange:f=>c({colorConfig:{...l.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=l.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...l.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:l.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.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:((j=l.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:f=>c({conditionalLabels:{...l.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:((x=l.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...l.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:((b=l.conditionalLabels)==null?void 0:b.noChange)??"No change",onChange:f=>c({conditionalLabels:{...l.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:l.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function $l(){var o,l;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((l=(o=t.preferences)==null?void 0:o.kpiVisualOptions)==null?void 0:l.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 ql({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const o=s.useEditorStore(j=>{var x;return((x=j.card.customCardPreferences)==null?void 0:x.url)&&j.card.type==="custom"}),l=s.useEditorStore(j=>j.card),c=l==null?void 0:l.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,p=()=>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(tt,{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(Xe,{zone:"groupBy",fields:t,label:p().label,placeholder:p().placeholder}),h&&e.jsx(Xe,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Xe,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Xe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!o&&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($l,{}),e.jsx(Yl,{}),e.jsx(Pt,{}),e.jsx(zt,{}),e.jsx(_t,{}),e.jsx(Vt,{})]})})]})]})}function Hl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-4 px-6 pt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})}),e.jsx(Ml,{selectedChart:t,onChartChange:n}),e.jsx(Ol,{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(ql,{groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Wl({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(S=>S.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=n||o||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=S=>{const C=v=>{if(v.id===S){const T=i[0]||d,y=s.getDataType(T.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:T,operator:y?"between":"=",value:y?[]:""}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},m=S=>{const C=v=>{if(v.id===S){const T=i[0]||d,y=s.getDataType(T.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},h=(S,C)=>{const v=T=>T.id===S?{...T,conditions:T.conditions.filter(y=>y.id!==C)}:{...T,groups:T.groups.map(v)};r(v(a))},p=(S,C)=>{const v=T=>T.id===S?{...T,groups:T.groups.filter(y=>y.id!==C)}:{...T,groups:T.groups.map(v)};r(v(a))},g=(S,C,v,T)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=O=>O.id===S?{...O,conditions:O.conditions.map(E=>E.id===C?{...E,[v]:T}:E)}:{...O,groups:O.groups.map(y)};r(y(a))},j=(S,C,v)=>{const T=y=>y.id===S?{...y,conditions:y.conditions.map(O=>O.id===C?{...O,...v}:O)}:{...y,groups:y.groups.map(T)};r(T(a))},x=(S,C)=>{const v=T=>T.id===S?{...T,logicalOperator:C}:{...T,groups:T.groups.map(v)};r(v(a))},b=(S,C)=>{const v=T=>T.id===S?{...T,negate:C}:{...T,groups:T.groups.map(v)};r(v(a))},f=(S,C,v)=>{const T=y=>y.id===S?{...y,conditions:s.arrayMove(y.conditions,C,v)}:{...y,groups:y.groups.map(T)};r(T(a))},N=(S,C,v)=>{const T=y=>y.id===S?{...y,groups:s.arrayMove(y.groups,C,v)}:{...y,groups:y.groups.map(T)};r(T(a))},k=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const C=T=>{let y="";typeof T.field=="object"?y=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:y=String(T.field);const O=T.operator;let E=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof E=="string"?E=`'${E}'`:Array.isArray(E)&&(E=`'${E.join(", ")}'`);else if(T.field.dataType==="date"||T.field.dataType==="datetime"||T.field.dataType==="timestamp")if(T.operator==="between"&&Array.isArray(E)&&E.length===2){const B=E[0]?`'${E[0]}'`:"NULL",w=E[1]?`'${E[1]}'`:"NULL";return`${y} BETWEEN ${B} AND ${w}`}else if((T.operator==="in"||T.operator==="not in")&&Array.isArray(E)){const B=E.map(w=>w?`'${w}'`:"NULL").join(", ");return`${y} ${O} (${B})`}else typeof E=="string"||E instanceof Date?E=`'${E}'`:Array.isArray(E)&&E.length>0&&(E=`'${E[0]}'`);else if(["in","not in"].includes(T.operator)){let B=[];Array.isArray(E)?B=E.map(w=>typeof w=="string"?`'${w}'`:String(w)):typeof E=="string"?B=E.split(",").map(w=>{const D=w.trim();return T.field.dataType==="string"?`'${D}'`:D}):typeof E=="number"&&(B=[String(E)]),E=`(${B.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=T=>{const y=T.conditions.map(C),O=T.groups.map(D=>v(D)),E=[...y,...O].filter(Boolean);if(E.length===0)return"";const B=E.join(` ${T.logicalOperator} `),w=E.length>1?`(${B})`:B;return T.negate?`NOT ${w}`:w};return v(S)},I=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:p,updateCondition:g,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:b,reorderConditions:f,reorderGroups:N,generateSQLPreview:k,hasAnyFilters:I}}function Kl({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 Ql=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"})}},Jl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Xl({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:o="w-64"}){const[l,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Jl(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:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Kl,{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:[Ql(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var j;const n=s.useEditorStore(x=>x.card),{authToken:a}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:m,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(a==null?void 0:a.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:n.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x.value||"BLANK",value:x.value||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function Zl({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:o}){const[l,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",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(p=>p.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:p=>{p.key==="Enter"&&d(m)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.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 eo({field:t,value:n,onChange:a,placeholder:r="Select value...",className:o}){const{filterValues:l,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:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function so({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:o}=s.useSemaphorContext(),l=(d=o==null?void 0:o.params)==null?void 0:d.timeZone,c=A.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:l,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const to=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],no=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ro=["=","!=","isNull","isNotNull"],lo=["between","isNull","isNotNull"],oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function et(t){return oo[t]||s.titleCase(t)}function io(t){switch(t){case"string":return ao;case"number":return no;case"boolean":return ro;case"date":return lo;default:return to}}function $t({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:b}=Os(t.field),f={transform:s.CSS.Transform.toString(p),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 ${j?"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(Xl,{value:t.field,onValueChange:N=>{const k=N,I=s.getDataType(k.dataType)==="date";d(a,t.id,{field:k,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?et(t.operator):""})}),e.jsx(s.SelectContent,{children:io(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:et(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"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Zl,{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(eo,{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(so,{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=>o(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:()=>l(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function co({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:p,availableFields:g,renderFilterGroup:j,updateConditionFields:x}){const{attributes:b,listeners:f,setNodeRef:N,transform:k,transition:I,isDragging:S}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(k),transition:I},v=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id){const B=t.conditions.findIndex(D=>D.id===O.id),w=t.conditions.findIndex(D=>D.id===E.id);B!==-1&&w!==-1&&u(t.id,B,w)}},T=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id&&a){const B=t.groups.findIndex(D=>D.id===O.id),w=t.groups.findIndex(D=>D.id===E.id);B!==-1&&w!==-1&&m(a,B,w)}};return e.jsxs("div",{ref:N,style:C,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${S?"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",{...b,...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:()=>o(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&&l(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($t,{condition:y,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},y.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:T,children:e.jsx(s.SortableContext,{items:t.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>j(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:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function uo({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:b,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:k,setCurrentFilters:I}=Wl({initialFilters:t,availableFields:n}),S=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,v]=A.useState(!1),T=(E,B,w)=>{const D=L=>L.id===E?{...L,conditions:L.conditions.map(F=>F.id===B?{...F,field:w,dataType:w.dataType}:F)}:{...L,groups:L.groups.map(D)};I(D(l))},y=(E,B=0,w)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:L,over:F}=D;if(F&&L.id!==F.id){const R=E.conditions.findIndex(P=>P.id===L.id),M=E.conditions.findIndex(P=>P.id===F.id);R!==-1&&M!==-1&&b(E.id,R,M)}},children:e.jsx(s.SortableContext,{items:E.conditions.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:E.conditions.map((D,L)=>e.jsx($t,{condition:D,index:L,groupId:E.id,groupLogicalOperator:E.logicalOperator,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},D.id))})}),e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:L,over:F}=D;if(F&&L.id!==F.id){const R=E.groups.findIndex(P=>P.id===L.id),M=E.groups.findIndex(P=>P.id===F.id);R!==-1&&M!==-1&&f(E.id,R,M)}},children:e.jsx(s.SortableContext,{items:E.groups.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:E.groups.map(D=>y(D,B+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(co,{group:E,depth:B,parentGroupId:w,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:m,onReorderConditions:b,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(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked: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)"})]})}),k&&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(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,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(k?l:null),children:"Apply Filters"})]})]})}function mo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(uo,{filters:n,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ho({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[o,l]=A.useState(null),c=s.useEditorStore(j=>j.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=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(x=>x.id===j)?"source":a("groupBy").find(x=>x.id===j)?"groupBy":a("metrics").find(x=>x.id===j)?"metrics":a("pivotBy").find(x=>x.id===j)?"pivotBy":a("sortBy").find(x=>x.id===j)?"sortBy":null,[n,a]),m=A.useCallback(j=>{l(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:b}=j;if(!b||!t){l(null);return}const f=x.id,N=b.id,k=u(f),I=u(N)||N;if(I==="sortBy"){if(k==="source"){const S=n.find(v=>v.id===f);if(!S){l(null);return}if(!(a("groupBy").some(v=>v.name===S.name&&v.qualifiedEntityName===S.qualifiedEntityName)||a("metrics").some(v=>v.name===S.name&&v.qualifiedEntityName===S.qualifiedEntityName))){l(null);return}}else if(k==="pivotBy"){l(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"){l(null);return}}if(k==="source"&&I==="sortBy"){const S=[...n].find(T=>T.id===f);if(!S){l(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(S,C)){l(null);return}const v=s.getNewField(S,"sortBy",C);l(null),r("sortBy",[...C,v]);return}if(k==="source"&&I!=="source"&&I!=="sortBy"){const S=[...n].find(y=>y.id===f);if(!S){l(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const y=C[0].qualifiedEntityName;if(!y){l(null);return}if(y!==S.qualifiedEntityName&&S.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(y,S.qualifiedEntityName,i)){s.showJoinRequiredNotification(),l(null);return}}else{s.showJoinRequiredNotification(),l(null);return}}const v=a(I);if(s.fieldAlreadyExists(S,v)){l(null);return}const T=s.getNewField(S,I,v);l(null),r(I,[...v,T]);return}if(k&&I&&k!=="source"&&I!=="source"&&k!==I){const S=a(k),C=a(I),v=S.find(O=>O.id===f);if(!v){l(null);return}const T=s.getNewField(v,I,C);if(l(null),I==="sortBy"){s.fieldAlreadyExists(v,C)||r(I,[...C,T]);return}const y=S.filter(O=>O.id!==f);r(k,y),r(I,[...C,T]);return}if(k&&I&&k===I&&k!=="source"){const S=a(k),C=S.findIndex(T=>T.id===f),v=S.findIndex(T=>T.id===N);if(C!==v){const T=s.arrayMove(S,C,v);r(k,T)}}l(null)},[t,n,a,r,u,i]),p=o?d.find(j=>j.id===o):null;return{activeId:o,activeField:p,handleDragStart:m,handleDragEnd:h}}function xo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:o,showIcon:l=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[l&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),p=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",o),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:p}),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":""]})]})]})})]})}):p}function po({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[o,l]=A.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}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),j=s.useManagementStore(f=>f.selectedVisual),x=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:b}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!m&&"justify-end"),children:[m&&t&&!p&&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&&!x&&e.jsx(ks,{variant:"default"}),x&&e.jsx(ar,{}),n&&s.isDevEnv]}),o&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:o,onOpenChange:l,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function fo({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,o=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:l}=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"&&o&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",l&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:l?"Error":"Info"})]})})}const go=[{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 jo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[o,l]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(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:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:go.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function bo({isOpen:t,onClose:n}){const a=mt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=A.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(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function vo(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async o=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...o,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:o=>{s.ue.success(`Feedback sent successfully! Issue: ${o.issueNumber}`,{duration:5e3})},onError:o=>{console.error("Feedback submission error:",o),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 yo(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 No({open:t,onOpenChange:n,feedbackData:a}){var x,b,f,N,k,I;const[r,o]=A.useState(""),[l,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=vo(),p=()=>{const S={...a,userMessage:r.trim()||void 0};i(S)},g=()=>{o(""),c(!1),h(),n(!1)},j={category:a.category,error:{message:(x=a.systemState)==null?void 0:x.errorMessage,sql:(b=a.systemState)==null?void 0:b.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(k=a.systemState)==null?void 0:k.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:S=>o(S.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:l,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"}),l?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(j,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:p,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(da,{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 qt=(t=>(t.QUERY_GENERATION="query-generation",t))(qt||{});function Co({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:p}){var _;const g=s.useEditorStore(V=>V.card),j=s.useDashboardStore(V=>V.filterValues),x=(j==null?void 0:j.length)||0,{updateCardConfig:b,setCard:f,updateCardInFrame:N,setCardId:k}=s.useEditorActions(),{updateCardId:I}=s.useDashboardActions(),[S,C]=A.useState(null),v=s.useEditorStore(V=>V.showAIDialog),[T,y]=A.useState(!1),[O,E]=A.useState(!1),[B,w]=A.useState(null),{isConsoleMode:D}=s.useDashboardPreferences(),{config:L}=A.useContext(s.SemaphorContext).tokenProps,F=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(V=>{var se;return((se=V.card.customCardPreferences)==null?void 0:se.url)&&V.card.type==="custom"}),{data:M,errorMessage:P,isLoading:W,isFetching:z,errorSql:X,pagination:te}=s.useDashboardCardQuery(u),K=(V,se)=>{const ne={...u,paginationConfig:{page:V+1,pageSize:se}};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(j||{},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...":p?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const U=V=>{if(!g.config)return;if(!V.length){b(g.id,{...g.config,sortByColumns:[]});return}const se=g.config,ne=V.map(({id:G,desc:Y})=>{var xe,pe;const re=(xe=se.metricColumns)==null?void 0:xe.find(me=>me.label===G),oe=(pe=se.groupByColumns)==null?void 0:pe.find(me=>me.label===G),le=re||oe;return le?{id:s.getFieldId("sortBy",le),name:le.name,dataType:le.dataType,label:le.label,qualifiedEntityName:le.qualifiedEntityName,entityId:le.entityId,entityName:le.entityName,entityType:le.entityType,role:"sortby",direction:Y?"desc":"asc"}:null}).filter(G=>G!==null);b(g.id,{...se,sortByColumns:ne})},ee=A.useMemo(()=>{var V,se;return(se=(V=g.config)==null?void 0:V.sortByColumns)==null?void 0:se.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(po,{showDebug:a,onDebugToggle:r,onAccept:o,onClear:l,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(It,{variant:"outline"}),e.jsx(fo,{activeView:t,onViewChange:n}),i&&e.jsx(xo,{dashboardFilterCount:x,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(jo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(At,{})})]}),!T&&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(Mt,{})}),t==="table"&&(M==null?void 0:M.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:(M==null?void 0:M.records)||[],paginationMetadata:te,onPaginationChange:K,isLoading:W||z,onSortChange:U,sortState:ee})}),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:[D&&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:V=>{const se=s.sanitizeCardId(V);if(!se){C("Card ID cannot be empty");return}const ne=I(g.id,se);if(ne.success){k(se);const G={...g,id:se};f(G),N(G),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"})]}),S&&e.jsx("p",{className:"text-xs text-destructive",children:S})]}),P||X?e.jsx(Nt,{error:P,errorSql:X,onSendFeedback:()=>{const V=yo(qt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:j,errorMessage:P,errorSql:X,generatedSql:M==null?void 0:M.sql});w(V),E(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(Ct,{sql:M==null?void 0:M.sql,error:P,errorSql:X})]})]})})]}),e.jsx(bo,{isOpen:T,onClose:()=>y(!1)}),B&&e.jsx(No,{open:O,onOpenChange:E,feedbackData:B})]})]})}function So({activeField:t}){const[n,a]=A.useState(!0);return A.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 wo=()=>{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 o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Do(){var te,K;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.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);A.useEffect(()=>wo(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},b=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:k,removeCard:I,updateCard:S,setActiveCard:C,updateFilters:v}=s.useEditorActions(),{columns:T=[],isLoading:y,error:O}=s.useColumns(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=N,{getFieldsForContainer:w,setFieldsForContainer:D}=Ls(B),{activeField:L,handleDragStart:F,handleDragEnd:R}=ho({activeCardId:f.activeCardId,sourceFields:T,getFieldsForContainer:w,setFieldsForContainer:D}),M=(H,U)=>{U&&v(H,U)},P=H=>{var U;S(H,{config:{...(U=f.cards.find(ee=>ee.id===H))==null?void 0:U.config,filters:void 0}})},W=T,z=H=>{if(!H)return 0;let U=H.conditions.length;return H.groups.forEach(ee=>{U+=z(ee)}),U},X=z(((te=B==null?void 0:B.config)==null?void 0:te.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(El,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Hl,{selectedChart:h,onChartChange:b,groupByFields:w("groupBy"),pivotByFields:w("pivotBy"),metricsFields:w("metrics"),sortByFields:w("sortBy")}),e.jsx(Co,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:p,onClear:g,onAdvancedToggle:j,onFiltersClick:x,filterCount:X,activeCard:B,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:T,columnsLoading:y,columnsError:O,getFieldsForContainer:w,cards:f.cards,activeCardId:f.activeCardId,addCard:k,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"})})})]}),B&&e.jsx(mo,{cardId:B.id,filters:((K=B.config)==null?void 0:K.filters)||null,onFiltersChange:M,onClearFilters:P,availableFields:W,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(So,{activeField:L||null})})]})}function To({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),o=s.useEditorStore(N=>N.showAIDialog),l=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:p,handleDragCancel:g,sensors:j}=Qn();A.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,k;o?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[o,i]);function x(N){N<1?i(!1):o||i(!0)}function b(){return e.jsxs(e.Fragment,{children:[e.jsx(yt,{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(pl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ks,{})})]})]})}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(Do,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ks,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:b()})}):f()})}function ko(){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 o(c){t&&(r(t,c),n(!1))}function l(){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(To,{onSave:o,onClose:l})})}function Eo({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(ca,{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 Io(){const t=s.useEditorStore(l=>l.selectedDatabaseName),n=s.useEditorStore(l=>l.selectedTableName),a=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(l.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ao({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(_e,{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($e,{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(We,{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 Mo(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),o=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:l}=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")},p=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,j=m.filter(f=>h(f)==="metrics").length,x=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};l(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 b=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)})]}),b&&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:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[p.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),p.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),p.map(f=>{const N=o==null?void 0:o.some(k=>{var I;return k.title===f.name||((I=k.column)==null?void 0:I.includes(f.name))});return e.jsx("div",{onClick:()=>x(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(Ao,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Lo(){var r;const t=s.useDashboardStore(o=>o.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(Mo,{}):e.jsx(yt,{type:"filter",ColumnsComponent:()=>e.jsx(Io,{})})})]})}function Ro(){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 Oo(){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(Ro,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Lo,{})})]})}function Fo(){const t=s.useDashboardStore(o=>o.dashboard),n=s.useDashboardStore(o=>o.actions.setDashboard),a=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.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:o=>{if(o)try{JSON.parse(o),n(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Bo({showControls:t=!1,showFooter:n=!0,...a}){if(typeof window>"u")return null;const{preferences:r}=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:r,children:[e.jsx(Fo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Yn,{}),e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(ko,{}),e.jsx(Oo,{})]})]})]})})]})})}exports.DashboardPlus=Bo;exports.ResourceManagementPanel=bt;exports.ScheduleDashboard=ot;exports.SelectComponent=Pe;exports.ShareDialog=ls;exports.cleanCard=lt;exports.getDashbaordStateWithoutData=ss;
354
+ ON ${N}`}),j};return l.length<2?null:e.jsx(e.Fragment,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[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:()=>o(!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(Sl,{joins:a.joins,baseEntityId:a.baseEntity.name,availableDataSources:l,generateSQLPreview:u})})]})}),e.jsx(Qs,{open:r,onOpenChange:o,joinPlan:a,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsx("div",{})})]}),a.joins.length===0&&e.jsx(Qs,{open:r,onOpenChange:o,joinPlan:a,availableDataSources:l,onSave:c,onCancel:d,onRemove:i,children:e.jsxs(s.Button,{onClick:()=>o(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function Dl({open:t,onOpenChange:n}){const[a,r]=A.useState([]),{updateDataSource:o}=s.useEditorActions(),l=s.useDashboardStore(x=>x.dashboard.aiContext),c=(l==null?void 0:l.selectedEntities)||[];A.useEffect(()=>{t&&r([])},[t]);const i=x=>{r(b=>b.some(N=>N.name===x.name&&N.type===x.type)?b.filter(N=>!(N.name===x.name&&N.type===x.type)):[...b,x])},d=()=>{r([...c])},u=()=>{r([])},m=()=>{if(a.length===0)return;const x=a[0],b=x.connectionId||"",f=x.connectionType||"",k=a.some(S=>S.type==="dataset")?"semanticDomain":"database";o({connectionId:b,connectionType:f,mode:k,selectedEntities:a}),n(!1)},h=x=>{switch(x.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(Ha,{className:"h-4 w-4"});case"model":return e.jsx(pa,{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"})}},p=x=>"label"in x&&x.label?x.label:x.name,g=x=>{if("description"in x&&x.description)return x.description;const b=[];return x.database&&b.push(x.database),x.schema&&b.push(x.schema),x.name&&b.push(x.name),b.join(".")},j=x=>a.some(b=>b.name===x.name&&b.type===x.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((x,b)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",j(x)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:j(x),onCheckedChange:()=>i(x)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:h(x)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:p(x)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:g(x)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type})]},`${x.type}-${x.name}-${b}`))})})]}),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 Tl({entity:t,title:n,maxDetails:a=10}){const o=s.getEntityDetails(t).slice(0,a),l=o.find(i=>i.label==="Description"),c=o.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),l&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:l.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((i,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},d))})]})})}function kl({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),o=r.find(c=>c.label==="Description"),l=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),o&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:o.value})]}),l.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:l.map((c,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function El({isVisible:t,onToggleVisibility:n}){const[a,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.useState(!0),d=s.useEditorStore(p=>p.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((p,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(p),e.jsx("button",{onClick:j=>{j.stopPropagation();const x=h.selectedEntities.filter(b=>!(b.name===p.name&&b.type===p.type));u({...m,...d,selectedEntities:x})},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(Tl,{entity:p})]},`${p.type}-${p.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(kl,{entities:h.selectedEntities.slice(3)})]})]})}),e.jsx(wl,{})]})]}),e.jsx(yl,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:h,fallbackDataSource:m}),e.jsx(Dl,{open:o,onOpenChange:l})]})}const Il="chart-selector-standard-first";function Al(){const[t,n]=s.useLocalStorageState(Il,!0);return{standardFirst:t,updatePreference:n}}const Js=({pluginVisual:t,index:n,onSelect:a})=>{const r=is(t.icon||""),o=t.name.charAt(0).toUpperCase(),l=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"}):l||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:o}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Xs=["default","standardPlugin","customPlugin"];function Ml({selectedChart:t,onChartChange:n}){var I;const[a,r]=A.useState(!1),{data:o}=kt();Al();const c=((I=s.useEditorStore(S=>S.card).customCardPreferences)==null?void 0:I.url)||"";ws(c);const{setCardType:i,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(S=>S.actions),{setCardCustomCfg:m,setCustomCardPreferences:h,setQueryConfig:p}=s.useEditorActions(),[g,j]=s.useLocalStorageState("chart-section-active",null),x=A.useMemo(()=>g?[g,...Xs.filter(S=>S!==g)]:Xs,[g]);function b(S){m(null),d({}),i(S),["custom","map"].includes(S)&&(u(!0),p(void 0)),n(S),r(!1)}function f(S){m(null),d({}),i("custom"),h({type:"component",visualType:"single",url:S.url,componentName:S.name,icon:S.icon,pluginChartType:S.chartType}),p(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 S=s.chartTypes.find(v=>v.id===t);return(S==null?void 0:S.label)||"Select chart type"},k=()=>{var C,v;if(t==="custom"){const T=s.useEditorStore.getState().card,y=(C=T==null?void 0:T.customCardPreferences)==null?void 0:C.icon,O=(v=T==null?void 0:T.customCardPreferences)==null?void 0:v.componentName;if(y&&O)return e.jsx(Ll,{icon:y,componentName:O});if(O){const E=s.getAutoDetectedChartIcon(O);if(E)return E}return e.jsx(qe,{className:"h-4 w-4"})}const S=s.chartTypes.find(T=>T.id===t);if(S){const T=S.icon;return e.jsx(T,{className:"h-4 w-4"})}return e.jsx(qe,{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:[k(),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."}),x.map(S=>{if(S==="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=>j(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:()=>b(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(S==="standardPlugin"){const C=o.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=>j(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,T)=>e.jsx(Js,{pluginVisual:v,index:T,onSelect:()=>f(v)},`${v.url}-${v.name}-${T}`))},"standardPlugin"):null}if(S==="customPlugin"){const C=o.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=>j(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,T)=>e.jsx(Js,{pluginVisual:v,index:T,onSelect:()=>f(v)},`${v.url}-${v.name}-${T}`))},"customPlugin"):null}return null})]})]})})]})})}const Ll=({icon:t,componentName:n})=>{const a=is(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(qe,{className:"h-4 w-4"})},Rl=[{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 Ol({selectedChart:t,onChartChange:n}){var o;const a=s.useEditorStore(l=>l.card),r=((o=a==null?void 0:a.config)==null?void 0:o.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center gap-1",children:Rl.map(l=>{if(l.requiresPivot&&!r)return null;const c=l.icon,i=t===l.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(l.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:l.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:l.label})})]},l.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 Fl({aliasTemplate:t,onAliasTemplateChange:n}){var d;const[a,r]=A.useState(t),[o,l]=A.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],i=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:i,value:o?a:t,onChange:u=>{r(u.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&a!==t?(n(a),l(!1)):u.key==="Escape"&&(r(t),l(!1))},"aria-label":"Edit alias template"}),o&&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),l(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),l(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Bl({valueAliases:t,onValueAliasesChange:n}){const[a,r]=A.useState(null),[o,l]=A.useState(""),[c,i]=A.useState(""),d=()=>{n({...t,"":""})},u=h=>{const p={...t};delete p[h],n(p)},m=h=>{const p={...t};delete p[h],p[o]=c,n(p),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,p],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:o,onChange:j=>l(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(h):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>m(h),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(p)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),l(h),i(p)},"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 Pl({field:t,searchQuery:n="",limit:a=500}){const{authToken:r}=s.useSemaphorContext(),o=s.useEditorStore(d=>d.card),l=o==null?void 0:o.dataSource,c=["attribute-values",t.entityName,t.name,n,a],i=s.useQuery({queryKey:c,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const d={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},u={connection_id:l.connectionId,cardConfig:d,cardDataSource:l,cache_config:s.getCacheConfig({card:o})};console.log("requestBody",u);const m=await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(r==null?void 0:r.accessToken)||"",u);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const h=t.name;return((m==null?void 0:m.records)||[]).map(g=>{const j=g[h]||g[t.alias||h]||g[t.label];return{id:j||"",value:j||"",label:String(j||"(empty)")}})}catch(d){return console.error("Error fetching attribute values:",d),[]}},enabled:!!t&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:i.data||[],isLoading:i.isLoading,isFetching:i.isFetching,isError:i.isError,error:i.error,refetch:i.refetch}}function zl({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:o,onSave:l}){var k,I;const c=!!o,[i,d]=A.useState(c?"values":"fields"),[u,m]=A.useState(""),[h,p]=A.useState({id:(o==null?void 0:o.id)||s.v4(),field:(o==null?void 0:o.field)||null,selectedValues:o?Array.isArray(o.value)?o.value:[o.value]:[]}),g=a.filter(S=>{var v;return c?!1:!((v=r==null?void 0:r.conditions)==null?void 0:v.some(T=>T.field.id===S.id))&&S.label.toLowerCase().includes(u.toLowerCase())}),j=S=>{p({...h,field:S}),d("values")},x=()=>{if(h.field&&h.selectedValues.length>0){const S={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let C;if(c){const v=((r==null?void 0:r.conditions)||[]).map(T=>T.id===o.id?S:T);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,S],groups:[]}}l(C),n(!1)}},b=()=>{if(!c||!o)return;const S=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==o.id);if(S.length>0){const C={...r,conditions:S};l(C)}else l(void 0);n(!1)},f=S=>{p({...h,selectedValues:S})},N=()=>{c&&o?(p({id:o.id,field:o.field,selectedValues:Array.isArray(o.value)?o.value:[o.value]}),d("values")):(p({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return A.useEffect(()=>{t&&N()},[t,c,o]),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: ${(k=h.field)==null?void 0:k.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(S=>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:[S.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(S.value)?`${S.value.length} values`:String(S.value)})]},S.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:S=>m(S.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:g.map(S=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(S),children:[e.jsx(Rs,{dataType:s.getDataType(S.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:S.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[S.entityName,".",S.name]})]})]},S.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(_l,{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:b,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:x,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function _l({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[o,l]=A.useState(""),{values:c,isLoading:i,isFetching:d}=Pl({field:t,searchQuery:o,limit:500}),u=o?c.filter(p=>String(p.value).toLowerCase().includes(o.toLowerCase())):c,m=p=>{const g=n.includes(p);a(g?n.filter(j=>j!==p):[...n,p])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(p=>p.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:o,onChange:p=>l(p.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(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(p.value),children:[e.jsx(s.Checkbox,{checked:n.includes(p.value),onCheckedChange:()=>m(p.value)}),e.jsx(cs,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Vl({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:l=!1,cardType:c}){var Bs,Ps,zs;const{attributes:i,listeners:d,setNodeRef:u,transform:m,transition:h,isDragging:p}=s.useSortable({id:t.id}),g=s.useEditorStore(Q=>Q.card),{updateLabel:j,handleAggregationChange:x,handleDateFormatChange:b,handleGranularityChange:f,handleAliasTemplateChange:N,handleValueAliasesChange:k,removeField:I,handleKpiComparisonTypeChange:S,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:T,handleKpiTargetValueChange:y}=Ls(g),[O,E]=A.useState(!1),[B,w]=A.useState(!1),[D,L]=A.useState(null),[F,R]=A.useState(t.dateFormat||"YYYY-MM-DD"),[M,P]=A.useState(t.customFormat||""),[W,z]=A.useState(!!t.customFormat),[X,te]=A.useState(t.granularity||"day"),[K,H]=A.useState(t.aliasTemplate||""),[U,ee]=A.useState(t.valueAliases||{}),[_,V]=A.useState((Bs=t.parameters)==null?void 0:Bs.filters),se=Q=>{Q==="custom"?z(!0):(z(!1),R(Q),n==="groupBy"&&b(a,Q,""))},ne=Q=>{P(Q),n==="groupBy"&&b(a,"custom",Q)},G=Q=>{var ge;te(Q);const ue=(ge=J(Q)[0])==null?void 0:ge.value;ue&&!W&&(R(ue),n==="groupBy"&&b(a,ue,"")),n==="groupBy"&&f(a,Q)},Y=Q=>{H(Q),n==="metrics"&&N(a,Q)},re=Q=>{ee(Q),n==="metrics"&&k(a,Q)},oe=Q=>{j(n,a,Q)},le=Q=>{var de;if(V(Q),n==="metrics"){const ue={...t,parameters:{...t.parameters,filters:Q}},ge=[...((de=g.config)==null?void 0:de.metricColumns)||[]];ge[a]=ue,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:ge})}w(!1)},xe=()=>{I(n,a)},pe={transform:s.CSS.Transform.toString(m),transition:h},me=s.getDataType(t.dataType),fe=me==="date",$=c==="kpi",J=Q=>{switch(Q){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..."}]}},Z=J(X),q=n!=="pivotBy",ae=fe&&n==="groupBy",ie=!$&&fe&&n==="groupBy",ce=$&&fe&&n==="groupBy",Ee=$&&n==="metrics"&&((Ps=g.config)==null?void 0:Ps.comparisonType)==="target",Be=n==="metrics",Te=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:Q=>{Q.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}`}),he=()=>q?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:oe,placeholder:"Display label...",type:"text"})]}):null,Fs=()=>ae?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:X,onValueChange:G,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(Q=>e.jsx(s.SelectItem,{className:"text-xs",value:Q,children:s.toTitleCase(Q)},Q))})]})]}):null,Ht=()=>ie?e.jsxs(e.Fragment,{children:[Fs(),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:W?"custom":F,onValueChange:se,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:Z.map(Q=>e.jsx(s.SelectItem,{className:"text-xs",value:Q.value,children:Q.label},Q.value))})]}),W&&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:M,onChange:Q=>{Q.stopPropagation(),ne(Q.target.value)},onClick:Q=>Q.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Wt=()=>{var Q,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:((Q=g.config)==null?void 0:Q.comparisonType)||"none",onValueChange:S,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:Ke=>{const Zt=parseInt(Ke.target.value)||30;v(Zt)},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:T,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},Kt=()=>{var Q,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:((Q=g.config)==null?void 0:Q.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},Qt=()=>Be?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:Q=>{x(a,Q)},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(Q=>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(Q),w(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.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(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.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 (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.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!==Q.id);if(ue.length>0){const ke={..._,conditions:ue};le(ke)}else if(V(void 0),n==="metrics"){const ke={...t,parameters:{...t.parameters,filters:void 0}},Ke=[...((ge=g.config)==null?void 0:ge.metricColumns)||[]];Ke[a]=ke,s.useEditorStore.getState().actions.updateCardConfig(g.id,{metricColumns:Ke})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{L(null),w(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Ut,{column:t}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Fl,{aliasTemplate:K,onAliasTemplateChange:Y}),e.jsx(Bl,{valueAliases:U,onValueAliasesChange:re})]})]}):null,{columns:Jt=[]}=s.useColumns(),Xt=(_==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 ${p?"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",Xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((zs=_==null?void 0:_.conditions)==null?void 0:zs.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(Q=>e.jsxs("div",{children:[Q.field.label,":"," ",Array.isArray(Q.value)?`${Q.value.length} values`:String(Q.value)]},Q.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:Q=>{Q.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 group-hover:opacity-100",onClick:Q=>{Q.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const de=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",de),o(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 opacity-0 group-hover:opacity-100",onClick:Q=>{Q.stopPropagation(),xe()},children:e.jsx(s.X,{className:"h-3 w-3"})})]}),O&&e.jsxs("div",{className:"space-y-3",children:[Te(),he(),c==="kpi"&&Fs(),Ht(),Wt(),Kt(),Qt()]})]}),B&&e.jsx(zl,{open:B,onOpenChange:Q=>{w(Q),Q||L(null)},availableFields:Jt,existingFilters:_,editingCondition:D,onSave:Q=>{var de;if(Q)le(Q);else if(V(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 Gl({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 Xe({zone:t,fields:n,label:a,placeholder:r,shouldShow:o,hasPivotColumns:l=!1}){const{isOver:c,setNodeRef:i}=s.useDroppable({id:t}),{updateSortByColumn:d}=s.useEditorActions(),u=s.useEditorStore(j=>j.card),m=s.useEditorStore(j=>j.card.type),h=n.length>0,p=(j,x)=>{var f;!((f=u.config)!=null&&f.sortByColumns)||u.config.sortByColumns.findIndex(N=>N.id===j)===-1||d(u.id,j,{direction:x})};if(t==="sortBy"&&o===!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(Gl,{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(j=>j.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((j,x)=>{const f=j.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(Vl,{field:j,zone:t,index:x,sortDirection:f,onSortDirectionChange:N=>p(j.id,N),hasPivotColumns:l,cardType:m})})},j.id)})})})})]})}const Zs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Ul=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function js({value:t,onChange:n,label:a}){const[r,o]=A.useState(!1),[l,c]=A.useState(!1),i=()=>{const d=Zs.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Zs[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:o,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:Ul.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),o(!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),o(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),l&&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(Bt,{color:i(),onColorChange:d=>{n(d),c(!1)},onClose:()=>c(!1)})})]})]})}const Ze={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%
355
+ 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 Yl(){var i,d,u,m,h,p,g,j,x,b;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 l=((m=(u=t.preferences)==null?void 0:u.kpiVisualOptions)==null?void 0:m.metricComparison)||{},c=f=>{var k;const N={...t.preferences,kpiVisualOptions:{...(k=t.preferences)==null?void 0:k.kpiVisualOptions,metricComparison:{...l,...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(va,{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:l.enabled||!1,onCheckedChange:f=>c({enabled:f,...f&&!l.calculationType?{calculationType:"difference"}:{}})})]}),l.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:l.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(Ze).map(([f,N])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:N.label},f))})]}),(()=>{var N,k,I;const f=l.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=Ze[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:(k=Ze[f])==null?void 0:k.formula})]}),e.jsxs("div",{className:"border-t pt-1 italic text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",(I=Ze[f])==null?void 0:I.example]})]})})()]}),e.jsx(As,{formatOptions:l.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:l.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:l.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:l.showColor!==!1,onCheckedChange:f=>c({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(js,{value:((h=l.colorConfig)==null?void 0:h.increase)||"green",onChange:f=>c({colorConfig:{...l.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(js,{value:((p=l.colorConfig)==null?void 0:p.decrease)||"red",onChange:f=>c({colorConfig:{...l.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(js,{value:((g=l.colorConfig)==null?void 0:g.noChange)||"neutral",onChange:f=>c({colorConfig:{...l.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:l.conditionalLabel||!1,onCheckedChange:f=>c({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.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:((j=l.conditionalLabels)==null?void 0:j.increase)??"Increase",onChange:f=>c({conditionalLabels:{...l.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:((x=l.conditionalLabels)==null?void 0:x.decrease)??"Decrease",onChange:f=>c({conditionalLabels:{...l.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:((b=l.conditionalLabels)==null?void 0:b.noChange)??"No change",onChange:f=>c({conditionalLabels:{...l.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:l.labelName??"",onChange:f=>c({labelName:f.target.value}),placeholder:"e.g. Versus, Compared to",className:"h-7 text-xs"})]})]})]})]})]})}function $l(){var o,l;const t=s.useEditorStore(c=>c.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((l=(o=t.preferences)==null?void 0:o.kpiVisualOptions)==null?void 0:l.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 ql({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r}){const o=s.useEditorStore(j=>{var x;return((x=j.card.customCardPreferences)==null?void 0:x.url)&&j.card.type==="custom"}),l=s.useEditorStore(j=>j.card),c=l==null?void 0:l.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,p=()=>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(tt,{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(Xe,{zone:"groupBy",fields:t,label:p().label,placeholder:p().placeholder}),h&&e.jsx(Xe,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Xe,{zone:"metrics",fields:a,label:g().label,placeholder:g().placeholder,hasPivotColumns:n.length>0}),u&&e.jsx(Xe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})]}),!o&&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($l,{}),e.jsx(Yl,{}),e.jsx(Pt,{}),e.jsx(zt,{}),e.jsx(_t,{}),e.jsx(Vt,{})]})})]})]})}function Hl({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:l}){const c=s.useEditorStore(h=>h.showAIDialog),i=a.length>0||r.length>0||o.length>0,{setShowAIDialog:d}=s.useEditorActions(),u=s.useEditorStore(h=>h.card),{data:m}=s.useDashboardCardQuery(u);return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col",children:[e.jsxs("div",{className:"space-y-2 px-6 pt-4",children:[e.jsx(Ml,{selectedChart:t,onChartChange:n}),e.jsx(Ol,{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(ql,{groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:l}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Wl({initialFilters:t,availableFields:n}={}){const[a,r]=A.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(S=>S.card.dataSource);const{columns:o,isLoading:l}=s.useColumns(),i=n||o||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=S=>{const C=v=>{if(v.id===S){const T=i[0]||d,y=s.getDataType(T.dataType)==="date";return{...v,conditions:[...v.conditions,{id:`condition-${Date.now()}`,field:T,operator:y?"between":"=",value:y?[]:""}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},m=S=>{const C=v=>{if(v.id===S){const T=i[0]||d,y=s.getDataType(T.dataType)==="date";return{...v,groups:[...v.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:T,operator:y?"between":"=",value:y?[]:""}],groups:[]}]}}return{...v,groups:v.groups.map(C)}};r(C(a))},h=(S,C)=>{const v=T=>T.id===S?{...T,conditions:T.conditions.filter(y=>y.id!==C)}:{...T,groups:T.groups.map(v)};r(v(a))},p=(S,C)=>{const v=T=>T.id===S?{...T,groups:T.groups.filter(y=>y.id!==C)}:{...T,groups:T.groups.map(v)};r(v(a))},g=(S,C,v,T)=>{if(v==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const y=O=>O.id===S?{...O,conditions:O.conditions.map(E=>E.id===C?{...E,[v]:T}:E)}:{...O,groups:O.groups.map(y)};r(y(a))},j=(S,C,v)=>{const T=y=>y.id===S?{...y,conditions:y.conditions.map(O=>O.id===C?{...O,...v}:O)}:{...y,groups:y.groups.map(T)};r(T(a))},x=(S,C)=>{const v=T=>T.id===S?{...T,logicalOperator:C}:{...T,groups:T.groups.map(v)};r(v(a))},b=(S,C)=>{const v=T=>T.id===S?{...T,negate:C}:{...T,groups:T.groups.map(v)};r(v(a))},f=(S,C,v)=>{const T=y=>y.id===S?{...y,conditions:s.arrayMove(y.conditions,C,v)}:{...y,groups:y.groups.map(T)};r(T(a))},N=(S,C,v)=>{const T=y=>y.id===S?{...y,groups:s.arrayMove(y.groups,C,v)}:{...y,groups:y.groups.map(T)};r(T(a))},k=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const C=T=>{let y="";typeof T.field=="object"?y=T.field.entityName?`${T.field.entityName}.${T.field.name}`:T.field.name:y=String(T.field);const O=T.operator;let E=T.value;if(T.field.dataType==="string"&&!["in","not in"].includes(T.operator))typeof E=="string"?E=`'${E}'`:Array.isArray(E)&&(E=`'${E.join(", ")}'`);else if(T.field.dataType==="date"||T.field.dataType==="datetime"||T.field.dataType==="timestamp")if(T.operator==="between"&&Array.isArray(E)&&E.length===2){const B=E[0]?`'${E[0]}'`:"NULL",w=E[1]?`'${E[1]}'`:"NULL";return`${y} BETWEEN ${B} AND ${w}`}else if((T.operator==="in"||T.operator==="not in")&&Array.isArray(E)){const B=E.map(w=>w?`'${w}'`:"NULL").join(", ");return`${y} ${O} (${B})`}else typeof E=="string"||E instanceof Date?E=`'${E}'`:Array.isArray(E)&&E.length>0&&(E=`'${E[0]}'`);else if(["in","not in"].includes(T.operator)){let B=[];Array.isArray(E)?B=E.map(w=>typeof w=="string"?`'${w}'`:String(w)):typeof E=="string"?B=E.split(",").map(w=>{const D=w.trim();return T.field.dataType==="string"?`'${D}'`:D}):typeof E=="number"&&(B=[String(E)]),E=`(${B.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=T=>{const y=T.conditions.map(C),O=T.groups.map(D=>v(D)),E=[...y,...O].filter(Boolean);if(E.length===0)return"";const B=E.join(` ${T.logicalOperator} `),w=E.length>1?`(${B})`:B;return T.negate?`NOT ${w}`:w};return v(S)},I=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:h,removeGroup:p,updateCondition:g,updateConditionFields:j,updateGroupOperator:x,updateGroupNegate:b,reorderConditions:f,reorderGroups:N,generateSQLPreview:k,hasAnyFilters:I}}function Kl({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 Ql=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"})}},Jl=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Xl({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:o="w-64"}){const[l,c]=A.useState(!1),i=A.useMemo(()=>{const d={};return a.forEach(u=>{const m=Jl(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:l,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Kl,{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:[Ql(h[0].entityType),e.jsx("span",{children:h[0].entityName})]}),h.map((p,g)=>e.jsxs(s.CommandItem,{value:p.id,onSelect:()=>{n(p),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)===p.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:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+g))]},`${d}-${m}`))},d))})]})})]})}function Os(t){var j;const n=s.useEditorStore(x=>x.card),{authToken:a}=s.useSemaphorContext(),r=s.useEditorStore(x=>x.card.config),o=r==null?void 0:r.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},i={...l,role:"sortby",direction:"asc"},d={joinPlan:o,groupByColumns:[l],metricColumns:[c],sortByColumns:[i]},u=((j=n.dataSource)==null?void 0:j.connectionId)||n.connectionId,{data:m,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular("https://semaphor.cloud/api/v1/query",(a==null?void 0:a.accessToken)||"",{connection_id:u,cardConfig:d,cardDataSource:n.dataSource})}catch(x){console.log(t),console.error("error",x)}},enabled:!!u,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(x=>({label:x.value||"BLANK",value:x.value||"BLANK",count:(x==null?void 0:x.count)||0})),isPending:h,error:p}}function Zl({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:o}){const[l,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",o),children:e.jsxs(s.Popover,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(m=>{const h=i.find(p=>p.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:p=>{p.key==="Enter"&&d(m)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.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 eo({field:t,value:n,onChange:a,placeholder:r="Select value...",className:o}){const{filterValues:l,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:o||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:l.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function so({value:t,operator:n,onChange:a,className:r}){var d;const{tokenProps:o}=s.useSemaphorContext(),l=(d=o==null?void 0:o.params)==null?void 0:d.timeZone,c=A.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:l,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const to=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ao=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],no=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ro=["=","!=","isNull","isNotNull"],lo=["between","isNull","isNotNull"],oo={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null"};function et(t){return oo[t]||s.titleCase(t)}function io(t){switch(t){case"string":return ao;case"number":return no;case"boolean":return ro;case"date":return lo;default:return to}}function $t({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:l,onUpdateGroupOperator:c,availableFields:i,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:h,transform:p,transition:g,isDragging:j}=s.useSortable({id:t.id}),{isPending:x,error:b}=Os(t.field),f={transform:s.CSS.Transform.toString(p),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 ${j?"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(Xl,{value:t.field,onValueChange:N=>{const k=N,I=s.getDataType(k.dataType)==="date";d(a,t.id,{field:k,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?et(t.operator):""})}),e.jsx(s.SelectContent,{children:io(s.getDataType(t.field.dataType)).map(N=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:N,children:et(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"?x?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Zl,{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(eo,{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(so,{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=>o(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:()=>l(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function co({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:l,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:h,onAddGroup:p,availableFields:g,renderFilterGroup:j,updateConditionFields:x}){const{attributes:b,listeners:f,setNodeRef:N,transform:k,transition:I,isDragging:S}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(k),transition:I},v=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id){const B=t.conditions.findIndex(D=>D.id===O.id),w=t.conditions.findIndex(D=>D.id===E.id);B!==-1&&w!==-1&&u(t.id,B,w)}},T=y=>{const{active:O,over:E}=y;if(E&&O.id!==E.id&&a){const B=t.groups.findIndex(D=>D.id===O.id),w=t.groups.findIndex(D=>D.id===E.id);B!==-1&&w!==-1&&m(a,B,w)}};return e.jsxs("div",{ref:N,style:C,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${S?"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",{...b,...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:()=>o(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&&l(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($t,{condition:y,index:O,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:i,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:g,updateConditionFields:x},y.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:T,children:e.jsx(s.SortableContext,{items:t.groups.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(y=>j(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:()=>p(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function uo({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:o}){const{currentFilters:l,availableFields:c,isLoading:i,addCondition:d,addGroup:u,removeCondition:m,removeGroup:h,updateCondition:p,updateConditionFields:g,updateGroupOperator:j,updateGroupNegate:x,reorderConditions:b,reorderGroups:f,generateSQLPreview:N,hasAnyFilters:k,setCurrentFilters:I}=Wl({initialFilters:t,availableFields:n}),S=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,v]=A.useState(!1),T=(E,B,w)=>{const D=L=>L.id===E?{...L,conditions:L.conditions.map(F=>F.id===B?{...F,field:w,dataType:w.dataType}:F)}:{...L,groups:L.groups.map(D)};I(D(l))},y=(E,B=0,w)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:L,over:F}=D;if(F&&L.id!==F.id){const R=E.conditions.findIndex(P=>P.id===L.id),M=E.conditions.findIndex(P=>P.id===F.id);R!==-1&&M!==-1&&b(E.id,R,M)}},children:e.jsx(s.SortableContext,{items:E.conditions.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:E.conditions.map((D,L)=>e.jsx($t,{condition:D,index:L,groupId:E.id,groupLogicalOperator:E.logicalOperator,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:g},D.id))})}),e.jsx(s.DndContext,{sensors:S,collisionDetection:s.closestCenter,onDragEnd:D=>{const{active:L,over:F}=D;if(F&&L.id!==F.id){const R=E.groups.findIndex(P=>P.id===L.id),M=E.groups.findIndex(P=>P.id===F.id);R!==-1&&M!==-1&&f(E.id,R,M)}},children:e.jsx(s.SortableContext,{items:E.groups.map(D=>D.id),strategy:s.verticalListSortingStrategy,children:E.groups.map(D=>y(D,B+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(co,{group:E,depth:B,parentGroupId:w,onUpdateGroupOperator:j,onUpdateGroupNegate:x,onRemoveGroup:h,onUpdateCondition:p,onUpdateField:T,onRemoveCondition:m,onReorderConditions:b,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(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{id:"advanced-mode",checked: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)"})]})}),k&&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(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,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(k?l:null),children:"Apply Filters"})]})]})}function mo({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:o,isOpen:l,onOpenChange:c}){const i=u=>{a(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:l,onOpenChange:c,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(uo,{filters:n,availableFields:o,onSave:i,onCancel:()=>c(!1),onClearAll:d})]})]})}function ho({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var g;const[o,l]=A.useState(null),c=s.useEditorStore(j=>j.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=A.useCallback(j=>j.startsWith("card-")?null:j.startsWith("source-")||n.find(x=>x.id===j)?"source":a("groupBy").find(x=>x.id===j)?"groupBy":a("metrics").find(x=>x.id===j)?"metrics":a("pivotBy").find(x=>x.id===j)?"pivotBy":a("sortBy").find(x=>x.id===j)?"sortBy":null,[n,a]),m=A.useCallback(j=>{l(j.active.id)},[]),h=A.useCallback(j=>{const{active:x,over:b}=j;if(!b||!t){l(null);return}const f=x.id,N=b.id,k=u(f),I=u(N)||N;if(I==="sortBy"){if(k==="source"){const S=n.find(v=>v.id===f);if(!S){l(null);return}if(!(a("groupBy").some(v=>v.name===S.name&&v.qualifiedEntityName===S.qualifiedEntityName)||a("metrics").some(v=>v.name===S.name&&v.qualifiedEntityName===S.qualifiedEntityName))){l(null);return}}else if(k==="pivotBy"){l(null);return}else if(k!=="groupBy"&&k!=="metrics"&&k!=="sortBy"){l(null);return}}if(k==="source"&&I==="sortBy"){const S=[...n].find(T=>T.id===f);if(!S){l(null);return}const C=a("sortBy");if(s.fieldAlreadyExists(S,C)){l(null);return}const v=s.getNewField(S,"sortBy",C);l(null),r("sortBy",[...C,v]);return}if(k==="source"&&I!=="source"&&I!=="sortBy"){const S=[...n].find(y=>y.id===f);if(!S){l(null);return}const C=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(C.length>0){const y=C[0].qualifiedEntityName;if(!y){l(null);return}if(y!==S.qualifiedEntityName&&S.qualifiedEntityName)if(i){if(!s.areEntitiesJoined(y,S.qualifiedEntityName,i)){s.showJoinRequiredNotification(),l(null);return}}else{s.showJoinRequiredNotification(),l(null);return}}const v=a(I);if(s.fieldAlreadyExists(S,v)){l(null);return}const T=s.getNewField(S,I,v);l(null),r(I,[...v,T]);return}if(k&&I&&k!=="source"&&I!=="source"&&k!==I){const S=a(k),C=a(I),v=S.find(O=>O.id===f);if(!v){l(null);return}const T=s.getNewField(v,I,C);if(l(null),I==="sortBy"){s.fieldAlreadyExists(v,C)||r(I,[...C,T]);return}const y=S.filter(O=>O.id!==f);r(k,y),r(I,[...C,T]);return}if(k&&I&&k===I&&k!=="source"){const S=a(k),C=S.findIndex(T=>T.id===f),v=S.findIndex(T=>T.id===N);if(C!==v){const T=s.arrayMove(S,C,v);r(k,T)}}l(null)},[t,n,a,r,u,i]),p=o?d.find(j=>j.id===o):null;return{activeId:o,activeField:p,handleDragStart:m,handleDragEnd:h}}function xo({dashboardFilterCount:t=0,cardFilterCount:n=0,clickFilterCount:a=0,onClick:r,className:o,showIcon:l=!0}){const c=t+n+a,i=c>0,d=t>0,u=n>0,m=a>0,h=e.jsxs(e.Fragment,{children:[l&&e.jsx(s.Filter,{className:"h-3.5 w-3.5"}),i&&e.jsx("span",{className:"font-medium",children:c})]}),p=e.jsx(s.Button,{variant:i?"secondary":"outline",size:"sm",onClick:r,className:s.cn("h-8 gap-1.5 transition-all",o),children:h});return i?e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:p}),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":""]})]})]})})]})}):p}function po({onAdvancedToggle:t,onDebugToggle:n,onAccept:a}){const{currentUser:r}=s.useCurrentUserInfo();r==null||r.role;const[o,l]=A.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}=A.useContext(s.SemaphorContext).tokenProps,m=(u==null?void 0:u.showAdvancedMode)!==!1,{setIsDevMode:h}=s.useEditorActions(),p=s.useEditorStore(f=>f.showAIDialog),g=s.useEditorStore(f=>f.frame),j=s.useManagementStore(f=>f.selectedVisual),x=(j==null?void 0:j.id)===(g==null?void 0:g.id),{setShowAIDialog:b}=s.useEditorActions();return e.jsxs("div",{className:s.cn("flex items-center justify-between px-6 py-3",p&&"justify-end",!m&&"justify-end"),children:[m&&t&&!p&&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&&!x&&e.jsx(ks,{variant:"default"}),x&&e.jsx(ar,{}),n&&s.isDevEnv]}),o&&e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(d==null?void 0:d.selectedEntities)||[],open:o,onOpenChange:l,dataSource:d||s.EMPTY_DATA_SOURCE,fallbackDataSource:s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function fo({activeView:t,onViewChange:n}){const a=s.useEditorStore(c=>c.card),{config:r}=A.useContext(s.SemaphorContext).tokenProps,o=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:l}=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"&&o&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",l&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:l?"Error":"Info"})]})})}const go=[{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 jo(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=A.useState(!1),[o,l]=A.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),n(t.id,parseInt(m))},i=m=>{const h=m.target.value;l(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:o,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:go.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function bo({isOpen:t,onClose:n}){const a=mt(n,{enabled:t}),r=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(m=>m.card),l=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),c=s.useEditorStore(m=>{var h;return((h=m.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:i}=s.useDashboardCardQuery(o),{getCard:d}=s.useCustomVisual(r),u=A.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(A.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(i==null?void 0:i.records)||[],chartType:l,settings:c})})})]})})}function vo(){const{authToken:t,tokenProps:n}=s.useSemaphorContext(),{currentUser:a}=s.useCurrentUserInfo(),r=s.useMutation({mutationFn:async o=>{if(!(t!=null&&t.accessToken))throw new Error("No authentication token available");const c="https://semaphor.cloud/api/v1/feedback",i={...o,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:o=>{s.ue.success(`Feedback sent successfully! Issue: ${o.issueNumber}`,{duration:5e3})},onError:o=>{console.error("Feedback submission error:",o),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 yo(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 No({open:t,onOpenChange:n,feedbackData:a}){var x,b,f,N,k,I;const[r,o]=A.useState(""),[l,c]=A.useState(!1),{sendFeedback:i,isLoading:d,isSuccess:u,data:m,reset:h}=vo(),p=()=>{const S={...a,userMessage:r.trim()||void 0};i(S)},g=()=>{o(""),c(!1),h(),n(!1)},j={category:a.category,error:{message:(x=a.systemState)==null?void 0:x.errorMessage,sql:(b=a.systemState)==null?void 0:b.generatedSql,errorSql:(f=a.systemState)==null?void 0:f.errorSql},cardConfig:(N=a.systemState)==null?void 0:N.cardConfig,dataSource:(k=a.systemState)==null?void 0:k.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:S=>o(S.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:l,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"}),l?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(j,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:p,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(da,{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 qt=(t=>(t.QUERY_GENERATION="query-generation",t))(qt||{});function Co({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onAccept:o,onClear:l,onAdvancedToggle:c,onFiltersClick:i,filterCount:d,activeCard:u,columns:m,columnsLoading:h,columnsError:p}){var _;const g=s.useEditorStore(V=>V.card),j=s.useDashboardStore(V=>V.filterValues),x=(j==null?void 0:j.length)||0,{updateCardConfig:b,setCard:f,updateCardInFrame:N,setCardId:k}=s.useEditorActions(),{updateCardId:I}=s.useDashboardActions(),[S,C]=A.useState(null),v=s.useEditorStore(V=>V.showAIDialog),[T,y]=A.useState(!1),[O,E]=A.useState(!1),[B,w]=A.useState(null),{isConsoleMode:D}=s.useDashboardPreferences(),{config:L}=A.useContext(s.SemaphorContext).tokenProps,F=(L==null?void 0:L.showInfoTab)!==!1,R=s.useEditorStore(V=>{var se;return((se=V.card.customCardPreferences)==null?void 0:se.url)&&V.card.type==="custom"}),{data:M,errorMessage:P,isLoading:W,isFetching:z,errorSql:X,pagination:te}=s.useDashboardCardQuery(u),K=(V,se)=>{const ne={...u,paginationConfig:{page:V+1,pageSize:se}};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(j||{},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...":p?"Error loading columns":JSON.stringify(m.slice(0,5),null,2)})]})]})})}const U=V=>{if(!g.config)return;if(!V.length){b(g.id,{...g.config,sortByColumns:[]});return}const se=g.config,ne=V.map(({id:G,desc:Y})=>{var xe,pe;const re=(xe=se.metricColumns)==null?void 0:xe.find(me=>me.label===G),oe=(pe=se.groupByColumns)==null?void 0:pe.find(me=>me.label===G),le=re||oe;return le?{id:s.getFieldId("sortBy",le),name:le.name,dataType:le.dataType,label:le.label,qualifiedEntityName:le.qualifiedEntityName,entityId:le.entityId,entityName:le.entityName,entityType:le.entityType,role:"sortby",direction:Y?"desc":"asc"}:null}).filter(G=>G!==null);b(g.id,{...se,sortByColumns:ne})},ee=A.useMemo(()=>{var V,se;return(se=(V=g.config)==null?void 0:V.sortByColumns)==null?void 0:se.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(po,{showDebug:a,onDebugToggle:r,onAccept:o,onClear:l,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(It,{variant:"outline"}),e.jsx(fo,{activeView:t,onViewChange:n}),i&&e.jsx(xo,{dashboardFilterCount:x,cardFilterCount:d,onClick:i,className:"h-8"}),e.jsx("div",{className:"ml-2",children:e.jsx(jo,{})}),v&&e.jsx(os,{})]}),e.jsx("div",{className:s.cn("flex grow items-center justify-end"),children:t==="chart"&&e.jsx(At,{})})]}),!T&&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(Mt,{})}),t==="table"&&(M==null?void 0:M.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:(M==null?void 0:M.records)||[],paginationMetadata:te,onPaginationChange:K,isLoading:W||z,onSortChange:U,sortState:ee})}),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:[D&&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:V=>{const se=s.sanitizeCardId(V);if(!se){C("Card ID cannot be empty");return}const ne=I(g.id,se);if(ne.success){k(se);const G={...g,id:se};f(G),N(G),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"})]}),S&&e.jsx("p",{className:"text-xs text-destructive",children:S})]}),P||X?e.jsx(Nt,{error:P,errorSql:X,onSendFeedback:()=>{const V=yo(qt.QUERY_GENERATION,{cardConfig:g.config,dataSource:u.dataSource,dashboardFilters:j,errorMessage:P,errorSql:X,generatedSql:M==null?void 0:M.sql});w(V),E(!0)}}):e.jsxs(e.Fragment,{children:[(M==null?void 0:M.sql)&&e.jsx("h3",{className:"mb-1 px-2 font-mono text-xs font-medium",children:"Generated SQL Query"}),e.jsx(Ct,{sql:M==null?void 0:M.sql,error:P,errorSql:X})]})]})})]}),e.jsx(bo,{isOpen:T,onClose:()=>y(!1)}),B&&e.jsx(No,{open:O,onOpenChange:E,feedbackData:B})]})]})}function So({activeField:t}){const[n,a]=A.useState(!0);return A.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 wo=()=>{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 o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Do(){var te,K;const[t,n]=A.useState("chart"),[a,r]=A.useState(!1),[o,l]=A.useState(!1),[c,i]=A.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);A.useEffect(()=>wo(),[]);const p=()=>{console.log("Accept clicked - would save/apply current configuration")},g=()=>{console.log("Clear clicked - would reset all configurations")},j=()=>{console.log("Advanced mode toggled")},x=()=>{l(!0)},b=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:k,removeCard:I,updateCard:S,setActiveCard:C,updateFilters:v}=s.useEditorActions(),{columns:T=[],isLoading:y,error:O}=s.useColumns(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),B=N,{getFieldsForContainer:w,setFieldsForContainer:D}=Ls(B),{activeField:L,handleDragStart:F,handleDragEnd:R}=ho({activeCardId:f.activeCardId,sourceFields:T,getFieldsForContainer:w,setFieldsForContainer:D}),M=(H,U)=>{U&&v(H,U)},P=H=>{var U;S(H,{config:{...(U=f.cards.find(ee=>ee.id===H))==null?void 0:U.config,filters:void 0}})},W=T,z=H=>{if(!H)return 0;let U=H.conditions.length;return H.groups.forEach(ee=>{U+=z(ee)}),U},X=z(((te=B==null?void 0:B.config)==null?void 0:te.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(El,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(Hl,{selectedChart:h,onChartChange:b,groupByFields:w("groupBy"),pivotByFields:w("pivotBy"),metricsFields:w("metrics"),sortByFields:w("sortBy")}),e.jsx(Co,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onAccept:p,onClear:g,onAdvancedToggle:j,onFiltersClick:x,filterCount:X,activeCard:B,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:T,columnsLoading:y,columnsError:O,getFieldsForContainer:w,cards:f.cards,activeCardId:f.activeCardId,addCard:k,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"})})})]}),B&&e.jsx(mo,{cardId:B.id,filters:((K=B.config)==null?void 0:K.filters)||null,onFiltersChange:M,onClearFilters:P,availableFields:W,isOpen:o,onOpenChange:l}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(So,{activeField:L||null})})]})}function To({authToken:t,onSave:n,onClose:a}){const r=A.useRef(null),o=s.useEditorStore(N=>N.showAIDialog),l=s.useEditorStore(N=>N.isDevMode),{setAuthToken:c}=s.useDashboardActions(),{setShowAIDialog:i,setOnSave:d,setOnClose:u}=s.useEditorActions(),{handleDragOver:m,handleDragEnd:h,handleDragStart:p,handleDragCancel:g,sensors:j}=Qn();A.useEffect(()=>{n&&d(n),a&&u(a)},[n,d,a,u]),A.useEffect(()=>{t&&t.accessToken&&c(t)},[t,c]),A.useEffect(()=>{var N,k;o?((N=r.current)==null||N.resize(40),i(!0)):(i(!1),(k=r.current)==null||k.resize(0))},[o,i]);function x(N){N<1?i(!1):o||i(!0)}function b(){return e.jsxs(e.Fragment,{children:[e.jsx(yt,{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(pl,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ks,{})})]})]})}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(Do,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:x,defaultSize:0,children:e.jsx(Ks,{})})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:l?e.jsx(s.DndContext,{sensors:j,onDragStart:p,onDragEnd:h,onDragOver:m,onDragCancel:g,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:b()})}):f()})}function ko(){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 o(c){t&&(r(t,c),n(!1))}function l(){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(To,{onSave:o,onClose:l})})}function Eo({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(ca,{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 Io(){const t=s.useEditorStore(l=>l.selectedDatabaseName),n=s.useEditorStore(l=>l.selectedTableName),a=s.useDashboardStore(l=>l.dashboard.filters)||[],{columns:r}=s.useEditorAside(),{assignFilter:o}=Is();return e.jsx(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(l=>{const c=a==null?void 0:a.find(i=>i.column===s.fmt(l.column_name)&&i.table===n&&i.database===t);return e.jsx("div",{onClick:()=>o(l),className:s.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{column:l}),e.jsx("span",{children:l.column_name})]})},l.column_name)})})}function Ao({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(_e,{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($e,{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(We,{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 Mo(){const[t,n]=A.useState(""),[a,r]=A.useState("all"),o=s.useDashboardStore(f=>f.dashboard.filters)||[],{assignFilter:l}=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")},p=a==="all"?m:m.filter(f=>h(f)===a),g=m.filter(f=>h(f)==="dimensions").length,j=m.filter(f=>h(f)==="metrics").length,x=f=>{const N={column_name:f.name,data_type:f.dataType,label:f.label,description:f.description};l(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 b=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)})]}),b&&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:j})]})]})})]}),e.jsxs(s.ScrollArea,{className:"flex-1 basis-0 flex-col px-3 pt-3",children:[p.length===0&&t&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:['No fields found matching "',t,'"']}),p.length===0&&!t&&a!=="all"&&e.jsxs("div",{className:"py-4 text-center text-sm text-gray-500",children:["No ",a," fields found"]}),p.map(f=>{const N=o==null?void 0:o.some(k=>{var I;return k.title===f.name||((I=k.column)==null?void 0:I.includes(f.name))});return e.jsx("div",{onClick:()=>x(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(Ao,{dataType:f.dataType}),e.jsx("span",{children:f.label||f.name})]})},f.id)})]})]})}function Lo(){var r;const t=s.useDashboardStore(o=>o.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(Mo,{}):e.jsx(yt,{type:"filter",ColumnsComponent:()=>e.jsx(Io,{})})})]})}function Ro(){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 Oo(){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(Ro,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Lo,{})})]})}function Fo(){const t=s.useDashboardStore(o=>o.dashboard),n=s.useDashboardStore(o=>o.actions.setDashboard),a=s.useDashboardStore(o=>o.showDashboardJSON),r=s.useDashboardStore(o=>o.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:o=>{if(o)try{JSON.parse(o),n(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Bo({showControls:t=!1,showFooter:n=!0,...a}){if(typeof window>"u")return null;const{preferences:r}=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:r,children:[e.jsx(Fo,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Yn,{}),e.jsxs(s.Container,{...a,type:"dashboard",children:[e.jsx(ko,{}),e.jsx(Oo,{})]})]})]})})]})})}exports.DashboardPlus=Bo;exports.ResourceManagementPanel=bt;exports.ScheduleDashboard=ot;exports.SelectComponent=Pe;exports.ShareDialog=ls;exports.cleanCard=lt;exports.getDashbaordStateWithoutData=ss;