react-semaphor 0.1.137 → 0.1.139

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.
Files changed (24) hide show
  1. package/dist/chunks/{dashboard-controls-hLb7d4n_.js → dashboard-controls-CycUpkzN.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-CxQYnkax.js → dashboard-controls-FAtMQrth.js} +3 -3
  3. package/dist/chunks/{dashboard-export-dialog-XQQow9XX.js → dashboard-export-dialog-BOeaIkB4.js} +3 -3
  4. package/dist/chunks/{dashboard-export-dialog-JVjnwTLv.js → dashboard-export-dialog-BkGfu2Ur.js} +1 -1
  5. package/dist/chunks/{dashboard-json-CSK4231d.js → dashboard-json-CUnn97AA.js} +1 -1
  6. package/dist/chunks/{dashboard-json-W8a-T1U3.js → dashboard-json-vWf6j3ir.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-C8ZQJfdk.js → edit-dashboard-visual-QX1EfVIC.js} +2 -2
  8. package/dist/chunks/{edit-dashboard-visual-BGH8yv2A.js → edit-dashboard-visual-WvBAW290.js} +9 -6
  9. package/dist/chunks/{editor-action-buttons-BmBNyNxY.js → editor-action-buttons-BaYDKpMq.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-zUsKxZMu.js → editor-action-buttons-hyOjCHRm.js} +2 -2
  11. package/dist/chunks/{index-MdpD3qo9.js → index-BAZxSdVh.js} +1 -1
  12. package/dist/chunks/{index-NjRBKdZ2.js → index-C0aUsTJw.js} +4 -4
  13. package/dist/chunks/{resource-management-panel-C_q7Ilyi.js → resource-management-panel-B2XgOmvv.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-Di5Mg69T.js → resource-management-panel-Chg6-H5n.js} +1 -1
  15. package/dist/chunks/{use-visual-utils-oliZ5xcR.js → use-visual-utils-DIuorLLH.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-CmKlc7fo.js → use-visual-utils-DyjCJ47j.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/style.css +1 -1
  22. package/dist/surfboard/index.cjs +1 -1
  23. package/dist/surfboard/index.js +1 -1
  24. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-MdpD3qo9.js"),D=require("react"),_e=require("./editor-action-buttons-BmBNyNxY.js"),nt=require("react-dom"),at=require("./use-visual-utils-CmKlc7fo.js"),rt=require("./use-click-outside-B9T3lmcw.js");function lt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const qe=lt(D);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-BAZxSdVh.js"),D=require("react"),_e=require("./editor-action-buttons-BaYDKpMq.js"),nt=require("react-dom"),at=require("./use-visual-utils-DyjCJ47j.js"),rt=require("./use-click-outside-B9T3lmcw.js");function lt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const qe=lt(D);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -195,6 +195,6 @@ ${p.joinType} JOIN ${j.name}
195
195
 
196
196
  ${c?`Python:
197
197
  ${c}`:""}
198
- `;B(V)}function G(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Pt,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(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(Vt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){var V,z,H,P,W,Y;return e.jsx("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-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:y||b,onClick:()=>{R()},className:"h-8 shrink-0",size:"sm",children:[y||b?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(Ot,{errorSql:L,sql:M==null?void 0:M.sql,error:K,onDebugWithAssistant:_}),e.jsx(_e.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ee=>r(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Rt,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{O(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((z=(V=o.preferences)==null?void 0:V.tablePrefs)==null?void 0:z.enableDevModePagination)??!1,onCheckedChange:ee=>{var J;v({...o.preferences,tablePrefs:{...(J=o.preferences)==null?void 0:J.tablePrefs,enableDevModePagination:ee}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((P=(H=o.preferences)==null?void 0:H.tablePrefs)==null?void 0:P.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((Y=(W=o.preferences)==null?void 0:W.tablePrefs)==null?void 0:Y.pageSize)||50),onValueChange:ee=>{var le,Z,oe;const J=Number(ee),ne={...o,preferences:{...o.preferences,tablePrefs:{...(le=o.preferences)==null?void 0:le.tablePrefs,pageSize:J}},paginationConfig:{page:1,pageSize:J}};E(ne),N(ne),o.sql&&((oe=(Z=o.preferences)==null?void 0:Z.tablePrefs)!=null&&oe.enableDevModePagination)&&j(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),l&&l.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:G()}),q()]})}const $t=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Kt({className:t}){const n=s.useEditorStore(l=>l.card),{setCardType:a,setCard:r,updateCardInFrame:o}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!d||!i)return null;const c=l=>{var x;const u=l;if(u==="aggregateTable"&&((x=n.config)!=null&&x.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:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:$t.map(l=>{const u=l.icon,x=n.type===l.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:l.value,id:`table-type-${l.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${l.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),l.label]})]},l.value)})})})}function Gt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(g=>g.selectedFrameId),o=s.useManagementStore(g=>g.selectedVisual),d=s.useEditorStore(g=>g.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(d!=null&&d.visualId||o!=null&&o.id)&&r)i="local";else if(o&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(o!=null&&o.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},l={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(bt,{className:"h-3.5 w-3.5"}),library:e.jsx(jt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],a),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:l[i]})]})]})})}function Ds({className:t,...n}){var G,q,V;const a=s.useEditorStore(z=>z.card),r=((G=a.customCardPreferences)==null?void 0:G.showCardHeader)??!0,o=((V=(q=a.preferences)==null?void 0:q.displayOptions)==null?void 0:V.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),i=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[l,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),g=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(z=>z.id===d.filterId),{data:f,isLoading:v,isFetching:C,errorMessage:A,errorSql:B,pagination:O}=s.useDashboardCardQuery(a),E=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:N,updateCardInFrame:p,setIsDevMode:j,setCardSql:S}=s.useEditorActions(),{data:M}=s.useTopoJson(a),y=D.useMemo(()=>{var z;return a.type!=="pivotTable"||!((z=f==null?void 0:f.records)!=null&&z.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[a.type,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),b=s.usePivotTableConfig(a,y),I=z=>{j(!0),S(z||B||a.sql||a.python||""),setTimeout(()=>{g(!0)},100)},F=()=>{u(!0)},T=D.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",P=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:i,errorMessage:A||void 0,errorSql:B||a.sql||a.python,generatedSql:B||a.sql},metadata:{url:z,userAgent:H,timestamp:new Date().toISOString(),viewport:P}}},[x,h,a,i,A,B]),L=(z,H)=>{var W,Y;const P={...a,paginationConfig:{page:z+1,pageSize:H}};N(P),p(P),a.sql&&((Y=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&Y.enableDevModePagination)&&g(!0)},w=z=>{var W,Y,ee,J;const H=s.sortStateToSortByColumns(z,(W=a.config)==null?void 0:W.metricColumns,(Y=a.config)==null?void 0:Y.groupByColumns),P={...a,config:{...a.config||{},sortByColumns:H}};N(P),p(P),a.sql&&((J=(ee=a.preferences)==null?void 0:ee.tablePrefs)!=null&&J.enableDevModePagination)&&g(!0)},R=D.useMemo(()=>!a.id||!(f!=null&&f.records)?null:s.createChartConfig({card:a,data:f==null?void 0:f.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:M}),[a.id,f==null?void 0:f.records,a.type,a.customCfg,a.preferences,M]);function K(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function _(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!v&&!C)return A?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Je,{error:A,errorSql:B||a.sql||a.python,onOpenInEditor:I,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):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((v||C)&&(!(f!=null&&f.records)||f.records.length===0))return a.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):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 K(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&R)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:v||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:R})});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:E,paginationMetadata:O,onPaginationChange:L,onSortChange:w,isLoading:v||C})});if(a.type==="pivotTable"&&b)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:b.data,options:b.options,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},onAggregationLabelChange:z=>{const H=s.handleAggregationLabelChange(z,a.config),P={...a,config:H};N(P),p(P)}})});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:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:O,onPaginationChange:L,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},isLoading:v||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(v||C)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&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 gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:z=>N({...a,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Gt,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Kt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:z=>N({...a,description:z}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:z=>k({...m,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),o&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:_()}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:u,feedbackData:T,showDebugInfo:!0})]})}const Ke=({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}),qt=()=>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."})]})]}),Ut=({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(Ke,{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(Ke,{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(Ke,{language:"javascript",value:t,onChange:o})})]}),_t=({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 Ht(){const[t,n]=D.useState(!1),[a,r]=D.useState(""),[o,d]=D.useState(""),[i,c]=D.useState(""),[l,u]=D.useState(""),x=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),g=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:v}=s.useEditorActions(),C=E=>{var N,p;return JSON.stringify({...E,data:{...E.data,datasets:(p=(N=E.data)==null?void 0:N.datasets)==null?void 0:p.map(j=>({...j,data:[]}))}},null,2)},A=()=>{var N,p;if(!((N=k==null?void 0:k.records)!=null&&N.length))return;const E=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(E){r(C(E)),c(((p=x.preferences)==null?void 0:p.customVisualCode)||"");const j=s.merge(E,h);d(C(j))}},B=()=>{try{if(i&&v(i),o){const E=JSON.parse(o),N=s.getObjectDiff(JSON.parse(a),E);f(N),u("")}}catch{u("Invalid JSON configuration")}},O=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:A,className:O?"":"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(qt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ut,{customCode:i,cardCustomCfgString:g,mergedConfig:o,onConfigChange:E=>d(E??""),onCodeChange:E=>c(E??"")})]}),e.jsx(_t,{error:l,hasCardCustomConfig:!!h,onReset:()=>{d(a),f(null)},onApply:B,onClose:()=>n(!1)})]})]})}function Jt({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:o}=s.useEditorActions(),{data:d,isLoading:i,isError:c}=s.useCustomVisualsQuery(),l=D.useCallback((u,x)=>{n(null),a({}),r(u),x&&o({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,o,t]);return i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!d||d.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:d.map((u,x)=>e.jsx(Qt,{text:u.name,onClick:()=>l("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const Qt=({text:t,icon:n,onClick:a})=>{const r=s.useDynamicIcon();return e.jsxs("button",{onClick:a,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(De,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function Yt({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:o,setIsDevMode:d}=s.useEditorStore(g=>g.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function u(g,k){i(null),o({}),r(g),["custom","text","map"].includes(g)&&(d(!0),l(void 0)),t==null||t()}const h=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:De}].filter(g=>g.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:h.map(g=>{const k=g.icon;return e.jsxs("button",{onClick:()=>u(g.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(k,{className:s.cn("h-6 w-6",n),strokeWidth:g.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:g.name})]},g.type)})})}function Wt({chartType:t,className:n,customIcon:a,componentName:r}){const o=s.useDynamicIcon();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"treemap":return e.jsx(s.TbChartTreemap,{className:n});case"bullet":return e.jsx(s.BulletChartIcon,{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(s.Type,{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(De,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Ms({variant:t="ghost"}){var c,l;const[n,a]=D.useState(!1),[r,o]=D.useState(""),d=s.useEditorStore(u=>u.card),i=d.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||o("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Wt,{className:"size-4",chartType:i,customIcon:(c=d.customCardPreferences)==null?void 0:c.icon,componentName:(l=d.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:r,onChange:u=>o(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(Yt,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Jt,{onChartTypeChange:()=>a(!1)})]})]})]})}function Xt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[o,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function l(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(g){(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),l())}function x(){const g=window.getSelection();if(g&&g.toString().trim()!==""){const k=g.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:l,onKeyDown:u,onMouseUp:x,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 Zt(){const t=s.useEditorStore(l=>{var u,x;return(x=(u=l.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),o=l=>{if(a(l),n!=="bullet")return;const u=l==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const l=t??"x",u=()=>{o(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="x"?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function i(){const l=()=>{o(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function c(){const l=t??"y",u=()=>{o(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="y"?e.jsx(ze,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?i():n==="bullet"?c():d()})}function en({className:t}){var k,m,f,v,C,A,B,O,E,N;const n=s.useEditorStore(p=>p.card),{setCardPreferences:a,updateCardInFrame:r,setCard:o}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,l=((v=(f=n.preferences)==null?void 0:f.displayOptions)==null?void 0:v.showCardToolbar)??!0,u=((A=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:A.showChrome)??!0,x=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,h=((N=(E=n.preferences)==null?void 0:E.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,g=(p,j)=>{var y;const S={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[p]:j}};a(S);const M={...n,preferences:S};o(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ks,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:p=>{g("showFilterInfo",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:p=>{g("showCardToolbar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p=>{g("showChrome",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:p=>{g("allowScroll",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:p=>{g("showInlineFilterBar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function sn(){const[t,n]=D.useState(!1),a=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:o}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(a==null?void 0:a.inlineFilters)||[];function c(h){const g=h.qualifiedFieldName||h.name;if(i.find(A=>A.column===g))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),v=h.qualifiedFieldName||f,C={id:s.v4(),column:g,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,v),width:250};o({...a,inlineFilters:[...i,C]})}function l(h){const g=i.filter(k=>k.id!==h);o({...a,inlineFilters:g}),d(a.id,h)}function u(h,g){const k=i.map(m=>m.id===h?{...m,...g}:m);o({...a,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("",{"text-primary":i.length>0}),children:e.jsx(yt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(tn,{filter:h,onUpdate:g=>u(h.id,g),onRemove:()=>l(h.id)},h.id))})]})]})})]})}):null}function tn({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function o(){const d=["xy","none","x","y"],c=(d.indexOf(a)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Zt,{})}),!["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:o,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Ss,{className:"size-4"}),a==="y"&&e.jsx(He,{className:"size-4"}),a==="none"&&e.jsx(At,{className:"size-4"})]}),e.jsx(sn,{}),e.jsx(en,{})]})}function nn(){const t=s.useEditorStore(m=>m.frame),n=s.useEditorStore(m=>m.card),{setFrame:a,setActiveTabCardId:r,setCard:o,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},l=(m,f)=>{const v=m.dataTransfer.getData("tabIndex");if(v===f.toString())return;const C=Array.from(t.cards),[A]=C.splice(parseInt(v),1);C.splice(f,0,A),a({...t,cards:C})};function u(m){const f=t.cards.filter(A=>A.id!==m),v=f[0],C={...t,cards:f,activeCardId:v.id};a(C),r(v.id),o(v)}function x(m,f){const v={...t,cards:[...t.cards,f],activeCardId:m.id};a(v),r(f.id)}function h(){const m={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,m)}function g(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=f.displayTab===void 0?!1:!f.displayTab;o({...f,displayTab:v}),d({...f,displayTab:v})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(mt,{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((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,f),onDragOver:c,onDrop:v=>l(v,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:v=>{o({...n,tabTitle:v}),d({...n,tabTitle:v})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>g(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ue(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:o,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:l}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:g}=s.useDashboardCardQuery(n);function k(v){const C=t.cards.find(A=>A.id===v);if(C!=null&&C.sql){r||c(!0),d(v);return}if(C!=null&&C.queryConfig){r&&c(!1),m(v),d(v);return}r||m(v),d(v)}function m(v){const C={...t,cards:t.cards.map(B=>B.id===n.id?n:B),activeCardId:v};o(C);const A=C.cards.find(B=>B.id===v);A.sql&&l(!0),i(A)}function f(){return n.type==="kpi"?x||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:x||h,isError:g})})}):n.type==="text"?x||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(Ds,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:f()},v.id)),e.jsx(nn,{})]})}function os({children:t}){const n=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),o=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:l,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:g,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:v,errorMessage:C,refetch:A,pagination:B}=s.useDashboardCardQuery(a),O=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[E,N]=D.useState(!1);D.useEffect(()=>{v||N(!1)},[v]);function p(b,I){var L,w;const F={...a,paginationConfig:{page:b+1,pageSize:I}};u(F);const T={...n,cards:n.cards.map(R=>R.id===a.id?F:R)};l(T),a.sql&&((w=(L=a.preferences)==null?void 0:L.tablePrefs)!=null&&w.enableDevModePagination)&&c(!0)}function j(b){var L,w,R,K;const I=s.sortStateToSortByColumns(b,(L=a.config)==null?void 0:L.metricColumns,(w=a.config)==null?void 0:w.groupByColumns),F={...a,config:{...a.config||{},sortByColumns:I}};u(F);const T={...n,cards:n.cards.map(_=>_.id===a.id?F:_)};l(T),a.sql&&((K=(R=a.preferences)==null?void 0:R.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function S(){const b=JSON.stringify(m==null?void 0:m.records,null,2),I=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(I),T=document.createElement("a");T.href=F,T.download=`${a.title}.json`,T.click()}function M(){const I=[Object.keys(m==null?void 0:m.records.reduce((w,R)=>({...w,...R}),{})).join(","),...((m==null?void 0:m.records)||[]).map(w=>Object.values(w).join(","))].join(`
198
+ `;B(V)}function G(){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:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(Pt,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(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(Vt,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){var V,z,H,P,W,Y;return e.jsx("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-4",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:y||b,onClick:()=>{R()},className:"h-8 shrink-0",size:"sm",children:[y||b?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(Ot,{errorSql:L,sql:M==null?void 0:M.sql,error:K,onDebugWithAssistant:_}),e.jsx(_e.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:ee=>r(ee),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Rt,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!d&&e.jsxs("button",{disabled:d,onClick:()=>{O(!0)},className:"flex h-8 w-full cursor-text items-center justify-start rounded-md bg-muted/50 px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((z=(V=o.preferences)==null?void 0:V.tablePrefs)==null?void 0:z.enableDevModePagination)??!1,onCheckedChange:ee=>{var J;v({...o.preferences,tablePrefs:{...(J=o.preferences)==null?void 0:J.tablePrefs,enableDevModePagination:ee}})}}),e.jsx(s.Label,{htmlFor:"pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((P=(H=o.preferences)==null?void 0:H.tablePrefs)==null?void 0:P.enableDevModePagination)&&e.jsxs(s.Select,{value:String(((Y=(W=o.preferences)==null?void 0:W.tablePrefs)==null?void 0:Y.pageSize)||50),onValueChange:ee=>{var le,Z,oe;const J=Number(ee),ne={...o,preferences:{...o.preferences,tablePrefs:{...(le=o.preferences)==null?void 0:le.tablePrefs,pageSize:J}},paginationConfig:{page:1,pageSize:J}};E(ne),N(ne),o.sql&&((oe=(Z=o.preferences)==null?void 0:Z.tablePrefs)!=null&&oe.enableDevModePagination)&&j(!0)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"10",children:"10"}),e.jsx(s.SelectItem,{value:"25",children:"25"}),e.jsx(s.SelectItem,{value:"50",children:"50"}),e.jsx(s.SelectItem,{value:"100",children:"100"}),e.jsx(s.SelectItem,{value:"500",children:"500"}),e.jsx(s.SelectItem,{value:"1000",children:"1000"})]})]})]}),l&&l.length>0&&e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",className:"h-8 gap-2 px-2",children:[e.jsx(s.Filter,{className:"size-4"}),e.jsx(s.Badge,{className:"h-5 min-w-5 bg-purple-100 px-1.5 text-purple-700 hover:bg-purple-100 dark:bg-purple-950 dark:text-purple-300",children:l.length})]})}),e.jsx(s.HoverCardContent,{className:"mr-4 max-h-[400px] w-[500px] overflow-auto p-0",children:e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"mb-2 text-sm font-semibold",children:"Active Dashboard Filters"}),e.jsx(s.CodeHighlighter,{code:JSON.stringify(l,null,2),language:"json"})]})})]})]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsx("div",{className:"relative flex grow overflow-y-scroll",children:G()}),q()]})}const $t=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Kt({className:t}){const n=s.useEditorStore(l=>l.card),{setCardType:a,setCard:r,updateCardInFrame:o}=s.useEditorActions(),d=["table","aggregateTable","pivotTable"].includes(n.type),i=s.hasValidCardConfig(n.config);if(!d||!i)return null;const c=l=>{var x;const u=l;if(u==="aggregateTable"&&((x=n.config)!=null&&x.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:c,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:$t.map(l=>{const u=l.icon,x=n.type===l.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:l.value,id:`table-type-${l.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${l.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",x?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),l.label]})]},l.value)})})})}function Gt({type:t,isLinked:n,className:a}){const r=s.useDashboardStore(g=>g.selectedFrameId),o=s.useManagementStore(g=>g.selectedVisual),d=s.useEditorStore(g=>g.frame);let i;if(t)i=t;else if(n!==void 0)i=n?"linked":"library";else if(!!!(d!=null&&d.visualId||o!=null&&o.id)&&r)i="local";else if(o&&!r)i="library";else if(d!=null&&d.visualId&&r)i="linked";else if(o!=null&&o.id&&r)i="library";else return null;if(i==="local")return null;const c={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},l={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},x={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},h={linked:e.jsx(bt,{className:"h-3.5 w-3.5"}),library:e.jsx(jt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",c[i],a),children:h[i]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[i]),children:[e.jsx(s.TooltipArrow,{className:x[i]}),e.jsx("p",{children:l[i]})]})]})})}function Ds({className:t,...n}){var G,q,V;const a=s.useEditorStore(z=>z.card),r=((G=a.customCardPreferences)==null?void 0:G.showCardHeader)??!0,o=((V=(q=a.preferences)==null?void 0:q.displayOptions)==null?void 0:V.showInlineFilterBar)??!0,d=s.useEditorStore(z=>z.frame),i=s.useDashboardStore(z=>z.dashboard.filters),c=s.useDashboardStore(z=>z.selectedSheetId),[l,u]=D.useState(!1),{currentUser:x}=s.useCurrentUserInfo(),{tokenProps:h}=D.useContext(s.SemaphorContext),g=s.useEditorStore(z=>z.actions.setRunSql),{updateFilter:k}=s.useDashboardActions(),m=i==null?void 0:i.find(z=>z.id===d.filterId),{data:f,isLoading:v,isFetching:C,errorMessage:A,errorSql:B,pagination:O}=s.useDashboardCardQuery(a),E=D.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:N,updateCardInFrame:p,setIsDevMode:j,setCardSql:S}=s.useEditorActions(),{data:M}=s.useTopoJson(a),y=D.useMemo(()=>{var z;return a.type!=="pivotTable"||!((z=f==null?void 0:f.records)!=null&&z.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[a.type,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),b=s.usePivotTableConfig(a,y),I=z=>{j(!0),S(z||B||a.sql||a.python||""),setTimeout(()=>{g(!0)},100)},F=()=>{u(!0)},T=D.useMemo(()=>{const z=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",P=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:i,errorMessage:A||void 0,errorSql:B||a.sql||a.python,generatedSql:B||a.sql},metadata:{url:z,userAgent:H,timestamp:new Date().toISOString(),viewport:P}}},[x,h,a,i,A,B]),L=(z,H)=>{var W,Y;const P={...a,paginationConfig:{page:z+1,pageSize:H}};N(P),p(P),a.sql&&((Y=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&Y.enableDevModePagination)&&g(!0)},w=z=>{var W,Y,ee,J;const H=s.sortStateToSortByColumns(z,(W=a.config)==null?void 0:W.metricColumns,(Y=a.config)==null?void 0:Y.groupByColumns),P={...a,config:{...a.config||{},sortByColumns:H}};N(P),p(P),a.sql&&((J=(ee=a.preferences)==null?void 0:ee.tablePrefs)!=null&&J.enableDevModePagination)&&g(!0)},R=D.useMemo(()=>!a.id||!(f!=null&&f.records)?null:s.createChartConfig({card:a,data:f==null?void 0:f.records,cardType:a.type,queryConfig:a.queryConfig,customCfg:a.customCfg,preferences:a.preferences,topoJson:M}),[a.id,f==null?void 0:f.records,a.type,a.customCfg,a.preferences,M]);function K(z){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:z})})}function _(){if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!v&&!C)return A?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(Je,{error:A,errorSql:B||a.sql||a.python,onOpenInEditor:I,onSendFeedback:F,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):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((v||C)&&(!(f!=null&&f.records)||f.records.length===0))return a.type==="table"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):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 K(a);if(!["table","pivotTable","aggregateTable","custom"].includes(a.type)&&R)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:v||C?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:R})});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:E,paginationMetadata:O,onPaginationChange:L,onSortChange:w,isLoading:v||C})});if(a.type==="pivotTable"&&b)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:b.data,options:b.options,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},onAggregationLabelChange:z=>{const H=s.handleAggregationLabelChange(z,a.config),P={...a,config:H};N(P),p(P)}})});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:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:O,onPaginationChange:L,onAggregationChange:z=>{const H=s.handleAggregationChange(z,a.config),P={...a,config:H};N(P),p(P)},isLoading:v||C})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(v||C)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&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 gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:z=>N({...a,title:z}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Gt,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Kt,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:a.description||"",onSave:z=>N({...a,description:z}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),m&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:m.title||m.column,onSave:z=>k({...m,title:z}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:m})]})]}),o&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:c||""})}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:_()}),e.jsx(s.FeedbackDialog,{open:l,onOpenChange:u,feedbackData:T,showDebugInfo:!0})]})}const Ke=({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}),qt=()=>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."})]})]}),Ut=({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(Ke,{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(Ke,{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(Ke,{language:"javascript",value:t,onChange:o})})]}),_t=({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 Ht(){const[t,n]=D.useState(!1),[a,r]=D.useState(""),[o,d]=D.useState(""),[i,c]=D.useState(""),[l,u]=D.useState(""),x=s.useEditorStore(E=>E.card),h=s.useEditorStore(E=>E.card.customCfg),g=h?JSON.stringify(h,null,2):"",{data:k}=s.useDashboardCardQuery(x),{data:m}=s.useTopoJson(x),{setCardCustomCfg:f,setCustomVisualCode:v}=s.useEditorActions(),C=E=>{var N,p;return JSON.stringify({...E,data:{...E.data,datasets:(p=(N=E.data)==null?void 0:N.datasets)==null?void 0:p.map(j=>({...j,data:[]}))}},null,2)},A=()=>{var N,p;if(!((N=k==null?void 0:k.records)!=null&&N.length))return;const E=s.createChartConfig({card:x,data:k.records,cardType:x.type,queryConfig:x.queryConfig,preferences:x.preferences,topoJson:m});if(E){r(C(E)),c(((p=x.preferences)==null?void 0:p.customVisualCode)||"");const j=s.merge(E,h);d(C(j))}},B=()=>{try{if(i&&v(i),o){const E=JSON.parse(o),N=s.getObjectDiff(JSON.parse(a),E);f(N),u("")}}catch{u("Invalid JSON configuration")}},O=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:A,className:O?"":"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(qt,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Ds,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Ut,{customCode:i,cardCustomCfgString:g,mergedConfig:o,onConfigChange:E=>d(E??""),onCodeChange:E=>c(E??"")})]}),e.jsx(_t,{error:l,hasCardCustomConfig:!!h,onReset:()=>{d(a),f(null)},onApply:B,onClose:()=>n(!1)})]})]})}function Jt({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:o}=s.useEditorActions(),{data:d,isLoading:i,isError:c}=s.useCustomVisualsQuery(),l=D.useCallback((u,x)=>{n(null),a({}),r(u),x&&o({type:"component",visualType:"single",url:x.url,componentName:x.name,icon:x.icon}),t==null||t()},[n,a,r,o,t]);return i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):c?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!d||d.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:d.map((u,x)=>e.jsx(Qt,{text:u.name,onClick:()=>l("custom",u),icon:u.icon},`${u.url}-${u.name}-${x}`))})]})}const Qt=({text:t,icon:n,onClick:a})=>{const r=s.useDynamicIcon();return e.jsxs("button",{onClick:a,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(De,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function Yt({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:o,setIsDevMode:d}=s.useEditorStore(g=>g.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:l}=s.useEditorActions();function u(g,k){i(null),o({}),r(g),["custom","text","map"].includes(g)&&(d(!0),l(void 0)),t==null||t()}const h=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:De}].filter(g=>g.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:h.map(g=>{const k=g.icon;return e.jsxs("button",{onClick:()=>u(g.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(k,{className:s.cn("h-6 w-6",n),strokeWidth:g.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:g.name})]},g.type)})})}function Wt({chartType:t,className:n,customIcon:a,componentName:r}){const o=s.useDynamicIcon();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"treemap":return e.jsx(s.TbChartTreemap,{className:n});case"bullet":return e.jsx(s.BulletChartIcon,{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(s.Type,{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(De,{className:n});default:return e.jsx(s.Table2,{className:n})}}function Ms({variant:t="ghost"}){var c,l;const[n,a]=D.useState(!1),[r,o]=D.useState(""),d=s.useEditorStore(u=>u.card),i=d.type;return e.jsxs(s.Popover,{open:n,onOpenChange:u=>{a(u),u||o("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(Wt,{className:"size-4",chartType:i,customIcon:(c=d.customCardPreferences)==null?void 0:c.icon,componentName:(l=d.customCardPreferences)==null?void 0:l.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search charts...",value:r,onChange:u=>o(u.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(Yt,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Jt,{onChartTypeChange:()=>a(!1)})]})]})]})}function Xt({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[o,d]=D.useState(!1),i=D.useRef(null),c=D.useRef(!1);function l(){t&&!c.current&&navigator.clipboard.writeText(t)}function u(g){(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),l())}function x(){const g=window.getSelection();if(g&&g.toString().trim()!==""){const k=g.toString();navigator.clipboard.writeText(k),d(!0),c.current=!0,setTimeout(()=>{d(!1),c.current=!1},1e3)}else c.current=!1}function h(){d(!1),c.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:i,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:l,onKeyDown:u,onMouseUp:x,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 Zt(){const t=s.useEditorStore(l=>{var u,x;return(x=(u=l.card.preferences)==null?void 0:u.chartOptions)==null?void 0:x.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),o=l=>{if(a(l),n!=="bullet")return;const u=l==="y"?"horizontal":"vertical",x=s.useEditorStore.getState().card.preferences,h={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:u}};r(h)};function d(){const l=t??"x",u=()=>{o(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="x"?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function i(){const l=()=>{o(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx($e,{className:"size-4"}):e.jsx(ze,{className:"size-4"})})}function c(){const l=t??"y",u=()=>{o(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="y"?e.jsx(ze,{className:"size-4"}):e.jsx($e,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?i():n==="bullet"?c():d()})}function en({className:t}){var k,m,f,v,C,A,B,O,E,N;const n=s.useEditorStore(p=>p.card),{setCardPreferences:a,updateCardInFrame:r,setCard:o}=s.useEditorActions(),[d,i]=D.useState(!1),c=((m=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:m.showFilterInfo)??!0,l=((v=(f=n.preferences)==null?void 0:f.displayOptions)==null?void 0:v.showCardToolbar)??!0,u=((A=(C=n.preferences)==null?void 0:C.displayOptions)==null?void 0:A.showChrome)??!0,x=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,h=((N=(E=n.preferences)==null?void 0:E.displayOptions)==null?void 0:N.showInlineFilterBar)??!0,g=(p,j)=>{var y;const S={...n.preferences,displayOptions:{...(y=n.preferences)==null?void 0:y.displayOptions,[p]:j}};a(S);const M={...n,preferences:S};o(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:d,onOpenChange:i,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(ks,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:p=>{g("showFilterInfo",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:p=>{g("showCardToolbar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p=>{g("showChrome",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:p=>{g("allowScroll",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:p=>{g("showInlineFilterBar",p)},onSelect:p=>p.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function sn(){const[t,n]=D.useState(!1),a=s.useEditorStore(h=>h.card),r=s.useEditorStore(h=>h.selectedConnectionId),{setCard:o}=s.useEditorActions(),d=s.useDashboardStore(h=>h.actions.removeCardInlineFilterValue),i=(a==null?void 0:a.inlineFilters)||[];function c(h){const g=h.qualifiedFieldName||h.name;if(i.find(A=>A.column===g))return;const m=h.qualifiedFieldName?h.qualifiedFieldName.split(".").slice(0,-1).join("."):h.qualifiedEntityName||h.entityName,f=s.fmt(h.name),v=h.qualifiedFieldName||f,C={id:s.v4(),column:g,title:h.label||h.name,dataType:h.dataType,table:h.entityName||"",database:"",connectionId:r||"",operation:"in",sql:s.getDefaultFilterSql(h.dataType,m,v),width:250};o({...a,inlineFilters:[...i,C]})}function l(h){const g=i.filter(k=>k.id!==h);o({...a,inlineFilters:g}),d(a.id,h)}function u(h,g){const k=i.map(m=>m.id===h?{...m,...g}:m);o({...a,inlineFilters:k})}return["bar","line","pie","doughnut","table","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":i.length>0}),children:[e.jsx(yt,{className:"h-4 w-4"}),i.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground",children:i.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:c,inlineFilters:i})})})}),i.length>0&&e.jsxs("div",{className:"border-t px-4 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Active Filters"}),e.jsx("div",{className:"space-y-1",children:i.map(h=>e.jsx(tn,{filter:h,onUpdate:g=>u(h.id,g),onRemove:()=>l(h.id)},h.id))})]})]})})]})}):null}function tn({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function Ls(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var i,c;return(c=(i=d.card)==null?void 0:i.preferences)==null?void 0:c.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function o(){const d=["xy","none","x","y"],c=(d.indexOf(a)+1)%d.length;r(d[c])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Zt,{})}),!["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:o,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Ss,{className:"size-4"}),a==="y"&&e.jsx(He,{className:"size-4"}),a==="none"&&e.jsx(At,{className:"size-4"})]}),e.jsx(sn,{}),e.jsx(en,{})]})}function nn(){const t=s.useEditorStore(m=>m.frame),n=s.useEditorStore(m=>m.card),{setFrame:a,setActiveTabCardId:r,setCard:o,updateCardInFrame:d}=s.useEditorActions(),i=(m,f)=>{m.dataTransfer.setData("tabIndex",f.toString())},c=m=>{m.preventDefault()},l=(m,f)=>{const v=m.dataTransfer.getData("tabIndex");if(v===f.toString())return;const C=Array.from(t.cards),[A]=C.splice(parseInt(v),1);C.splice(f,0,A),a({...t,cards:C})};function u(m){const f=t.cards.filter(A=>A.id!==m),v=f[0],C={...t,cards:f,activeCardId:v.id};a(C),r(v.id),o(v)}function x(m,f){const v={...t,cards:[...t.cards,f],activeCardId:m.id};a(v),r(f.id)}function h(){const m={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};x(n,m)}function g(m){const f={dataSource:m.dataSource,connectionId:m.connectionId,lastSelectedDatabase:m.lastSelectedDatabase,lastSelectedSchema:m.lastSelectedSchema,lastSelectedTable:m.lastSelectedTable,lastSelectedDatamodelId:m.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};x(m,f)}function k(m,f){return m.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||m.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=f.displayTab===void 0?!1:!f.displayTab;o({...f,displayTab:v}),d({...f,displayTab:v})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(mt,{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((m,f)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>i(v,f),onDragOver:c,onDrop:v=>l(v,f),className:"",value:m.id,children:[k(t,m),e.jsx(s.Editable,{enabled:t.activeCardId===m.id,text:m.tabTitle||m.title,onSave:v=>{o({...n,tabTitle:v}),d({...n,tabTitle:v})},children:m.tabTitle||m.title},m.id),t.activeCardId===m.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),h()}}),t.activeCardId===m.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(m.id)})]},m.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>g(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ue(){const t=s.useEditorStore(v=>v.frame),n=s.useEditorStore(v=>v.card),a=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:o,setActiveTabCardId:d,setCard:i,setIsDevMode:c,setRunSql:l}=s.useEditorActions(),{data:u,isLoading:x,isFetching:h,isError:g}=s.useDashboardCardQuery(n);function k(v){const C=t.cards.find(A=>A.id===v);if(C!=null&&C.sql){r||c(!0),d(v);return}if(C!=null&&C.queryConfig){r&&c(!1),m(v),d(v);return}r||m(v),d(v)}function m(v){const C={...t,cards:t.cards.map(B=>B.id===n.id?n:B),activeCardId:v};o(C);const A=C.cards.find(B=>B.id===v);A.sql&&l(!0),i(A)}function f(){return n.type==="kpi"?x||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:x||h,isError:g})})}):n.type==="text"?x||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(Ds,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:k,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:f()},v.id)),e.jsx(nn,{})]})}function os({children:t}){const n=s.useEditorStore(b=>b.frame),a=s.useEditorStore(b=>b.card),r=s.useEditorStore(b=>b.isDevMode),o=s.useEditorStore(b=>b.isShowingVisual),d=s.useDashboardStore(b=>b.isVisualEditing),i=s.useEditorStore(b=>b.pythonStdOut),c=s.useEditorStore(b=>b.actions.setRunSql),{setFrame:l,setCard:u,setActiveTabCardId:x,runAssistant:h,setIsDevMode:g,setCardPreferences:k}=s.useEditorActions(),{data:m,isLoading:f,isFetching:v,errorMessage:C,refetch:A,pagination:B}=s.useDashboardCardQuery(a),O=D.useMemo(()=>(m==null?void 0:m.records)||[],[m==null?void 0:m.records]),[E,N]=D.useState(!1);D.useEffect(()=>{v||N(!1)},[v]);function p(b,I){var L,w;const F={...a,paginationConfig:{page:b+1,pageSize:I}};u(F);const T={...n,cards:n.cards.map(R=>R.id===a.id?F:R)};l(T),a.sql&&((w=(L=a.preferences)==null?void 0:L.tablePrefs)!=null&&w.enableDevModePagination)&&c(!0)}function j(b){var L,w,R,K;const I=s.sortStateToSortByColumns(b,(L=a.config)==null?void 0:L.metricColumns,(w=a.config)==null?void 0:w.groupByColumns),F={...a,config:{...a.config||{},sortByColumns:I}};u(F);const T={...n,cards:n.cards.map(_=>_.id===a.id?F:_)};l(T),a.sql&&((K=(R=a.preferences)==null?void 0:R.tablePrefs)!=null&&K.enableDevModePagination)&&c(!0)}function S(){const b=JSON.stringify(m==null?void 0:m.records,null,2),I=new Blob([b],{type:"application/json"}),F=URL.createObjectURL(I),T=document.createElement("a");T.href=F,T.download=`${a.title}.json`,T.click()}function M(){const I=[Object.keys(m==null?void 0:m.records.reduce((w,R)=>({...w,...R}),{})).join(","),...((m==null?void 0:m.records)||[]).map(w=>Object.values(w).join(","))].join(`
199
199
  `),F=new Blob([I],{type:"text/csv"}),T=URL.createObjectURL(F),L=document.createElement("a");L.href=T,L.download=`${a.title}.csv`,L.click()}function y(){const b=`Can you get the documentation for ${a.type} chart?`;h(b)}return a?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:[o&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ms,{}),d&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:y,children:e.jsx(ct,{className:"size-4"})}),!["table","custom"].includes(a.type)&&d&&e.jsx(Ht,{})]}),!o&&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:M,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:S,children:e.jsx(xt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(m==null?void 0:m.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(s.IconButton,{tooltip:"Refresh",disabled:f||v,onClick:()=>{N(!0),A()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":E})})}),e.jsx(Ls,{})]}),r&&e.jsx(rn,{})]}),o?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(an,{})}),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":i}),children:[(m==null?void 0:m.records)&&(m==null?void 0:m.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:O,paginationMetadata:B,onPaginationChange:p,onSortChange:j,isLoading:f||v}),C&&e.jsx(Xt,{error:C})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function an(){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 rn(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>n(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function ce({value:t,onCommit:n,type:a="text",placeholder:r,className:o}){const[d,i]=D.useState(t),c=D.useRef(!1);D.useEffect(()=>{i(t)},[t]);const l=()=>{if(c.current){c.current=!1;return}d!==t&&n(d)},u=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(t),x.currentTarget.blur())};return e.jsx(s.Input$1,{type:a,placeholder:r,value:d,onChange:x=>i(x.target.value),onBlur:l,onKeyDown:u,className:o})}function he({defaultValue:t,label:n,options:a,value:r,onValueChange:o,className:d,icon:i,showPlaceholderLabel:c=!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",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function Fs(){var f,v;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(C=>C.card),o=s.useEditorStore(C=>C.frame),d=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:i}=s.useEditorActions(),{components:c,manifest:l}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(f=l==null?void 0:l.visuals)==null?void 0:f.find(C=>C.name===(t==null?void 0:t.componentName));function x(C,A){if(!t)return;const O={...(t==null?void 0:t.dataInputCardIds)||{},[C]:{cardId:A,hookRef:null}};i({...t,dataInputCardIds:O})}function h(C){var B,O;const A=(B=o==null?void 0:o.cards)==null?void 0:B.filter(E=>{var N;return((N=E==null?void 0:E.customCardPreferences)==null?void 0:N.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(O=C==null?void 0:C.dataInputs)==null?void 0:O.map((E,N)=>{var p,j;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(he,{className:"col-span-6 h-8 w-full justify-between",label:"",options:A||[],value:((j=(p=t==null?void 0:t.dataInputCardIds)==null?void 0:p[N])==null?void 0:j.cardId)||"",onValueChange:S=>x(N,S)})]},N+Math.random())})})}function g(C,A,B=[],O=""){var E,N;return t?C==="input"?e.jsx(ce,{className:`h-8 w-full ${s.removeRing}`,value:String(((E=t==null?void 0:t.settings)==null?void 0:E[A])??O??""),onCommit:p=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:p}})}},A):C==="select"?e.jsx(he,{className:"h-8 w-full",label:"",options:B,value:((N=t==null?void 0:t.settings)==null?void 0:N[A])||O,onValueChange:p=>{i({...t,settings:{...t==null?void 0:t.settings,[A]:p}})}}):null:null}function k(C){const A=Object.entries((C==null?void 0:C.settings)||{});return e.jsx("div",{className:"space-y-3",children:A.map(([B,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:O.title}),g(O.ui,B,O.options,O.defaultValue)]},B))})}function m(C){t&&i({...t,visualType:C,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",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(he,{icon:e.jsx(Ns,{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:C=>i({...t||{url:"",componentName:""},url:C})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:d,onValueChange:m,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:c&&e.jsx(he,{icon:e.jsx(ut,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(c==null?void 0:c.filter(C=>C.type===d).map(C=>({value:C.name,label:C.name})))||[],value:t.componentName,onValueChange:C=>{console.log("changing value",C),i({...t,componentName:C})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.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:k(u)})})]})]})]})}function Se(){const[t,n]=D.useState([]),a=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=s.useEditorStore(u=>u.actions),d=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),D.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function i(u,x){var h,g;x?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:(g=a==null?void 0:a.onClickFilter)==null?void 0:g.filter(k=>k.columnIndex!==u)}),n(k=>{const m=[...k];return m[u]=!1,m}))}function c(u,x){var g;const h=(g=a==null?void 0:a.onClickFilter)==null?void 0:g.map(k=>k.columnIndex===u?{...k,expression:x.target.value}:k);o({...a,onClickFilter:h})}function l(u){var x,h,g,k;if(t!=null&&t[u]||(h=(x=a==null?void 0:a.onClickFilter)==null?void 0:x.find(m=>m.columnIndex===u))!=null&&h.expression)return e.jsx(s.Input$1,{value:(k=(g=a==null?void 0:a.onClickFilter)==null?void 0:g.find(m=>m.columnIndex===u))==null?void 0:k.expression,onChange:m=>c(u,m),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:d==null?void 0:d.map((u,x)=>{var h,g;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((h=a==null?void 0:a.onClickFilter)!=null&&h.find(k=>k.columnIndex===x)),onCheckedChange:k=>i(x,k)}),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:((g=a==null?void 0:a.onClickFilter)==null?void 0:g.find(k=>k.columnIndex===x))&&e.jsx(s.Pencil,{onClick:()=>{n(k=>{const m=[...k];return m[x]=!k[x],m})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(x)]})},u)})})}function ln({idx:t}){var c;const n=s.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=s.useEditorStore(l=>{var u;return(u=l.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),o=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,d=a==null?void 0:a.find(l=>l.idx===t);function i(l,u){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const x={display:l!=="none",align:l,anchor:l,clamp:!0};if(!d)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:x}]});else{const h={...d};h.datalabels=x;const g=a==null?void 0:a.map(k=>k.idx===u?h:k);r({...n,datasetOptions:g})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{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:()=>i("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vt,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>i("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ct,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>i("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nt,{className:s.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function on(){const t=s.useEditorStore(d=>d.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(d=>!s.METADATA_KEYS.includes(d));let o=r;if(["stackedBar","stackedLine"].includes(t.type)){const d=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:i}=s.getKeys(d);o=i.slice(1)}return{transformedMetricKeys:o,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}function Qe({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 Bs(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var u,x,h;return(h=(x=(u=l==null?void 0:l.card)==null?void 0:u.preferences)==null?void 0:x.chartOptions)==null?void 0:h.indexAxis}),{data:a}=s.useDashboardCardQuery(t),r=n==="y"?"Metric":"Dimension",o=n==="y"?"Dimension":"Metric",{dimensionKeys:d,transformedMetricKeys:i,keys:c}=on();return c.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:d.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:Os(l)},l))})]}),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:i.map((l,u)=>e.jsx(Rs,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:u},l))})]})]})}function Os(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function Rs({col:t,idx:n,className:a,iconClassName:r,children:o}){const d=s.useEditorStore(x=>{var h;return(h=x.card)==null?void 0:h.preferences}),i=s.useEditorStore(x=>{var h,g;return(g=(h=x.card)==null?void 0:h.preferences)==null?void 0:g.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===n),{setCardPreferences:l}=s.useEditorStore(x=>x.actions);function u(x){if(!c)l({...d,datasetOptions:[...i||[],{idx:n,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const h={...c};h.type=x==="area"?"line":x,h.fill=x==="area"?"origin":"";const g=i==null?void 0:i.map(k=>k.idx===n?h:k);l({...d,datasetOptions:g})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[o||e.jsx(Qe,{className:"max-w-[100px]",title:t,children:Os(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(ln,{idx:n})]})]})}function Me(){const t=s.useDashboardStore(c=>c.dashboard.filters),n=s.useEditorStore(c=>c.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:o}=s.useAssignFilter();function d(c){const l=o(c,"frame");a({...n,filterId:l})}const i=t==null?void 0:t.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(cn,{onSelect:d,columns:r}),i&&e.jsx(s.FilterHeader,{filter:i})]})}function cn({columns:t,onSelect:n}){var i;const[a,r]=qe.useState(!1),[o,d]=qe.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?(i=t.find(c=>c.column_name===o))==null?void 0:i.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(c=>e.jsxs(s.CommandItem,{value:c.column_name,onSelect:l=>{const u=l===o?"":l;d(u),r(!1),u&&n(c)},children:[c.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",o===c.column_name?"opacity-100":"opacity-0")})]},c.column_name))})]})]})})]})}function dn({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(Bs,{})})]}),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(Se,{}),e.jsx(Me,{})]})]})]})})}function un({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:d=>d.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(Se,{}),e.jsx(Me,{})]})]})]})})}function Ps(){const t=s.useEditorStore(c=>c.card.type),n=s.useEditorStore(c=>c.isDevMode),a=s.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=s.useEditorStore(c=>c.actions);function o(c){var x;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(x=a==null?void 0:a.chartOptions)==null?void 0:x.plugins,...l}}};r(u)}function d(){var c,l,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=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.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 i(){var c,l,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(l=(c=a==null?void 0:a.chartOptions)==null?void 0:c.plugins)==null?void 0:l.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?d():i()})}const mn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},xn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function hn(){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:pn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ps,{}),e.jsx(Se,{}),e.jsx(Me,{})]})]})}function pn(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(mn,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(xn,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 fn({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(i,c,l){const u=[...t];u[i]={...u[i],[c]:l},n(u)}function o(i){const c=[...t];c.splice(i,1),n(c)}function d(){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:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input$1,{onChange:l=>r(c,"start",l.target.value),value:i.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input$1,{value:i.end,onChange:l=>r(c,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input$1,{onChange:l=>r(c,"color",l.target.value),value:i.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(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},c))]})}function gn(){var x,h,g,k,m;const t=s.useEditorStore(f=>f.card.preferences),n=s.useEditorStore(f=>f.actions.setCardPreferences),a=s.useEditorStore(f=>f.card),r=s.hasValidCardConfig(a.config),o=s.useEditorStore(f=>f.actions.setNumberFormat);s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.decimalPlaces});const d=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.locale}),i=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.currency});s.useEditorStore(f=>f.actions.setFilterOnClickField);const c=s.useEditorStore(f=>{var v,C;return(C=(v=f.card.preferences)==null?void 0:v.formatNumber)==null?void 0:C.colorRanges})||[],l=s.useEditorStore(f=>f.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(f=>f.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((x=t==null?void 0:t.formatNumber)!=null&&x.enabled),onCheckedChange:f=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:f}})}}),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:d||"none",onValueChange:f=>{var v,C,A;return o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",f,((A=t==null?void 0:t.formatNumber)==null?void 0:A.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(f=>e.jsx(s.SelectItem,{value:f.locale,children:f.locale},f.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:i||"none",onValueChange:f=>{var v,C,A;console.log("currency",f),o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,f==="none"?"":f,((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))]})})]})]})]}),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:((k=(g=t==null?void 0:t.formatNumber)==null?void 0:g.decimalPlaces)==null?void 0:k.toString())||"0",onValueChange:f=>{var v,C,A;return o(Number(f),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.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(f=>e.jsx(s.SelectItem,{value:f,children:f},f))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input$1,{value:((m=t==null?void 0:t.formatNumber)==null?void 0:m.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:f=>{var v,C,A;return o(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((C=t==null?void 0:t.formatNumber)==null?void 0:C.currency)||"",((A=t==null?void 0:t.formatNumber)==null?void 0:A.locale)||"",f.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(fn,{colorRanges:c,setColorRanges:l})]})]})}function jn(){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(gn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function Ge({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 bn=[{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"}],vn=["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"],yn=vn.map(t=>({label:t,value:t}));function Nn(){var l,u,x,h,g,k,m,f,v,C,A,B,O,E,N,p,j,S;const t=s.useEditorStore(M=>M.card),n=(u=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=D.useState(((h=(x=t==null?void 0:t.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:h.customTopoJsonUrl)||""),{setCardPreferences:o}=s.useEditorActions(),{data:d}=s.useTopoJson(t),i=Object.keys((d==null?void 0:d.objects)||{}).map(M=>({label:M,value:M}))||[],c=[{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(Ge,{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(Ge,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(he,{className:"h-9",options:c,onValueChange:M=>{console.log("value",M),o({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input$1,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),o({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(he,{className:"h-9",options:i,value:((k=(g=t.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:k.objectKey)||"",label:"Map Object",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(he,{className:"h-9",options:bn,value:((f=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(he,{className:"h-9",options:yn,value:((C=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Ge,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(A=t.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var y;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(E=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:N[0])||0,onChange:M=>{var y,b,I,F;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[Number(M.target.value),((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input$1,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((S=(j=(p=t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:j.projectionOffset)==null?void 0:S[1])||0,onChange:M=>{var y,b,I,F;o({...t.preferences,mapVisualOptions:{...(y=t.preferences)==null?void 0:y.mapVisualOptions,projectionOffset:[((F=(I=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:F[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Se,{})]})}function Cn(){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 Oe({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(Cn,{})})]}),!["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(Se,{}),e.jsx(Me,{})]})]})]})})}function Sn(){const t=s.useEditorStore(r=>{var o,d;return(d=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=s.useEditorActions();function a(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(he,{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(Bs,{})]})]}),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(Se,{}),e.jsx(Me,{})]})]})]})})}function wn({cardType:t="table"}){console.log("cardType",t);const n=s.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.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(Se,{}),e.jsx(Me,{})]})]})}),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 Vs({color:t,onColorChange:n,onClose:a}){const[r,o]=D.useState(0),[d,i]=D.useState(100),[c,l]=D.useState(50),[u,x]=D.useState(t);D.useEffect(()=>{const v=is(t);if(v){const C=cs(v.r,v.g,v.b);o(C.h),i(C.s),l(C.l),x(t)}},[t]);const h=v=>{o(v),k(v,d,c)},g=v=>{const C=v.currentTarget.getBoundingClientRect(),A=Math.max(0,Math.min(1,(v.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(v.clientY-C.top)/C.height)),O=A*100,E=(1-B)*100;i(O),l(E),k(r,O,E)},k=(v,C,A)=>{const B=Tn(v,C,A),O=kn(B.r,B.g,B.b);x(O)},m=v=>{if(x(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const C=is(v);if(C){const A=cs(C.r,C.g,C.b);o(A.h),i(A.s),l(A.l)}}},f=()=>{/^#[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:g,onMouseMove:v=>{v.buttons===1&&g(v)},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:`${d}%`,top:`${100-c}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>h(Number(v.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$1,{value:u,onChange:v=>m(v.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:f,children:"OK"})]})]})}function is(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 kn(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function cs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),o=Math.min(t,n,a);let d=0,i=0;const c=(r+o)/2;if(r!==o){const l=r-o;switch(i=c>.5?l/(2-r-o):l/(r+o),r){case t:d=((n-a)/l+(n<a?6:0))/6;break;case n:d=((a-t)/l+2)/6;break;case a:d=((t-n)/l+4)/6;break}}return{h:Math.round(d*360),s:Math.round(i*100),l:Math.round(c*100)}}function Tn(t,n,a){t/=360,n/=100,a/=100;let r,o,d;if(n===0)r=o=d=a;else{const i=(u,x,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?u+(x-u)*6*h:h<.5?x:h<.6666666666666666?u+(x-u)*(.6666666666666666-h)*6:u),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=i(l,c,t+1/3),o=i(l,c,t),d=i(l,c,t-1/3)}return{r:Math.round(r*255),g:Math.round(o*255),b:Math.round(d*255)}}const En=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function zs(){var B,O,E,N,p,j,S,M,y,b;const t=s.useEditorStore(I=>I.card),n=s.useEditorStore(I=>{var F;return(F=I.card)==null?void 0:F.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),{data:o}=s.useDashboardCardQuery(t),[d,i]=D.useState({}),[c,l]=D.useState(null),[u,x]=D.useState(null),h=D.useMemo(()=>{var L,w,R,K,_,G,q;if(!(o!=null&&o.records)||o.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",F=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",T=((L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||F)&&T){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const V=new Set;return o.pivotSchema.forEach(z=>{z.alias&&V.add(z.alias)}),Array.from(V)}if(o.records.length>0){const V=o.records[0],z=Object.keys(V),H=new Set;(w=t==null?void 0:t.config)!=null&&w.groupByColumns&&t.config.groupByColumns.forEach(Y=>{H.add(Y.label||Y.name),H.add(Y.alias||Y.name)});const P=new Set;return(R=t==null?void 0:t.config)!=null&&R.metricColumns&&t.config.metricColumns.forEach(Y=>{const ee=Y.alias||Y.name;P.add(ee),P.add(`${ee}_count`),P.add(`${ee}_sum`),P.add(`${ee}_avg`),P.add(`${ee}_min`),P.add(`${ee}_max`);const J=Y.entityName||Y.qualifiedEntityName;J&&(P.add(`${J}_${ee}`),P.add(`${J}_${ee}_count`))}),z.filter(Y=>!H.has(Y)&&!P.has(Y))}}if((F||I)&&!T&&((_=(K=t==null?void 0:t.config)==null?void 0:K.metricColumns)!=null&&_.length))return t.config.metricColumns.map(V=>V.alias||V.label||V.name);if((q=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&q.length){const V=t.config.groupByColumns[0],z=V.label||V.name,H=new Set;return o.records.forEach(P=>{const W=P[z];W!=null&&H.add(String(W))}),Array.from(H)}return[]},[o,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(O=t==null?void 0:t.config)==null?void 0:O.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),g=D.useMemo(()=>s.getDefaultChartColors(),[]);D.useEffect(()=>{const I={};h.forEach((F,T)=>{I[F]=s.getColorForValue(F,T,n==null?void 0:n.colorConfig)}),i(I)},[h,n==null?void 0:n.colorConfig,g]);const k=(I,F)=>{const T={...d,[I]:F};i(T);const L={...n||{},colorConfig:{segments:T}};a(L);const w={...t,preferences:L};r(w)},m=(I,F)=>{var _;const T=g[F%g.length],{[I]:L,...w}=((_=n==null?void 0:n.colorConfig)==null?void 0:_.segments)||{},R={...n||{},colorConfig:{segments:w}};a(R);const K={...t,preferences:R};r(K),i(G=>({...G,[I]:T}))};if(!h.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((p=(N=t==null?void 0:t.config)==null?void 0:N.groupByColumns)==null?void 0:p.length)||((S=(j=t==null?void 0:t.config)==null?void 0:j.pivotByColumns)==null?void 0:S.length):(y=(M=t==null?void 0:t.config)==null?void 0:M.groupByColumns)==null?void 0:y.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const C=()=>{const I={...n||{},colorConfig:{segments:{}}};a(I);const F={...t,preferences:I};r(F);const T={};h.forEach((L,w)=>{T[L]=s.getColorForValue(L,w,void 0)}),i(T)},A=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(St,{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:A&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:C,children:[e.jsx(as,{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((I,F)=>{const T=s.isDefaultColor(d[I],F),L=!T;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:c===I,onOpenChange:w=>l(w?I: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:d[I]}})}),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:g.slice(0,10).map((w,R)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[I]===w?"border-gray-900":"border-transparent"),style:{backgroundColor:w},onClick:()=>{k(I,w),l(null)},children:[R===F%g.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:w})]},`default-${R}`))})]}),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:En.map((w,R)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[I]===w?"border-2 border-gray-900":w==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:w},onClick:()=>{k(I,w),l(null)},children:e.jsx("span",{className:"sr-only",children:w})},`preset-${R}`))})]}),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:()=>{x({value:I,color:d[I]}),l(null)},children:"Custom color"}),!T&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{m(I,F),l(null)},children:[e.jsx(as,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),L&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),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:()=>x(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:u.color,onColorChange:I=>{k(u.value,I),x(null)},onClose:()=>x(null)})})]})]})})]})}function pe({value:t,onSave:n,placeholder:a="",type:r="text",className:o=""}){const[d,i]=D.useState(t??""),[c,l]=D.useState(!1);D.useEffect(()=>{i(t??"")},[t]);const u=()=>{n(d),l(!1)},x=()=>{i(t??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(s.Input,{placeholder:a,type:r,value:c?d:t??"",onChange:h=>{i(h.target.value),l(!0)},onFocus:()=>l(!0),onClick:h=>h.stopPropagation(),className:"h-8 text-xs",onPointerDown:h=>h.stopPropagation(),onKeyDown:h=>{h.stopPropagation(),h.key==="Enter"&&c&&d!==t?u():h.key==="Escape"&&x()},"aria-label":a||"Edit field"}),c&&d!==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:x,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const An=["auto","number","currency","percent","scientific","date"],In=[{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"}],Dn=[{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"}],Mn=t=>t.charAt(0).toUpperCase()+t.slice(1);function Ye({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const o=t.type||"auto",d=(c,l)=>{n({...t,[c]:l})},i=()=>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:c=>d("type",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:An.map(c=>e.jsx(s.SelectItem,{value:c,className:"text-xs",children:c==="auto"?"Auto (Default)":Mn(c)},c))})]})]}),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$1,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??i(),onChange:c=>d("decimalPlaces",parseInt(c.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:c=>d("currency",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:In.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.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:c=>d("useSuffix",c)})]}),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:c=>d("locale",c),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(c=>e.jsx(s.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.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$1,{placeholder:"e.g., $",value:t.prefix||"",onChange:c=>d("prefix",c.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$1,{placeholder:"e.g., units",value:t.suffix||"",onChange:c=>d("suffix",c.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:c=>d("negativeInParentheses",c)})]}),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$1,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:c=>d("multiplyBy",c.target.value?parseFloat(c.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$1,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:c=>d("dateFormat",c.target.value),className:"h-8 text-xs"})})]})]})]})}function ds({axis:t,label:n,type:a,config:r,onChange:o}){var h,g,k,m,f,v,C,A,B,O,E,N;const d=(p,j)=>{o({...r,[p]:j})},i=(p,j)=>{var S,M;o({...r,name:{enabled:p==="enabled"?j:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:p==="text"?j:(M=r==null?void 0:r.name)==null?void 0:M.text}})},c=(p,j)=>{var S,M;o({...r,labels:{enabled:p==="enabled"?j:((S=r==null?void 0:r.labels)==null?void 0:S.enabled)??!0,rotation:p==="rotation"?j:(M=r==null?void 0:r.labels)==null?void 0:M.rotation}})},l=(p,j)=>{o({...r,scale:{...r==null?void 0:r.scale,[p]:j===""?"auto":Number(j)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],x=["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:p=>d("enabled",p),onClick:p=>p.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:p=>i("enabled",p)})]}),((g=r==null?void 0:r.name)==null?void 0:g.enabled)&&e.jsx(pe,{placeholder:`${n} title`,value:((k=r==null?void 0:r.name)==null?void 0:k.text)||"",onSave:p=>i("text",p),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:p=>d("position",p),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":s.titleCase(p)},p))})]})]}),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:((m=r==null?void 0:r.labels)==null?void 0:m.enabled)!==!1,onCheckedChange:p=>c("enabled",p)})]}),((f=r==null?void 0:r.labels)==null?void 0:f.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(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:p=>c("rotation",p==="auto"?"auto":Number(p)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(p=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:p==="auto"?"Auto (Default)":`${p}°`},p))})]})]})]}),a==="value"&&e.jsx(Ye,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:p=>o({...r,formatOptions:p}),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(pe,{type:"number",placeholder:"auto",value:((C=r==null?void 0:r.scale)==null?void 0:C.min)==="auto"||((A=r==null?void 0:r.scale)==null?void 0:A.min)===void 0?"":String(r.scale.min),onSave:p=>l("min",p),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(pe,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((O=r==null?void 0:r.scale)==null?void 0:O.max)===void 0?"":String(r.scale.max),onSave:p=>l("max",p),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(pe,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((N=r==null?void 0:r.scale)==null?void 0:N.stepSize)===void 0?"":String(r.scale.stepSize),onSave:p=>l("stepSize",p),className:""})})]})]})]})]})]})}function $s(){const t=s.useEditorStore(i=>i.card),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const o=s.AxisConfigurator.getAxisInfo(t.type,n);if(!o.hasXAxis&&!o.hasYAxis)return null;const d=(i,c)=>{const u={...n||{},[i==="x"?"xAxisConfig":"yAxisConfig"]:c};a(u);const x={...t,preferences:u};r(x)};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(ks,{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(ds,{axis:"x",label:"X-Axis",type:o.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),n==null?void 0:n.xAxisConfig),onChange:i=>d("x",i)}),o.hasYAxis&&e.jsx(ds,{axis:"y",label:"Y-Axis",type:o.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),n==null?void 0:n.yAxisConfig),onChange:i=>d("y",i)})]})})]})}function Ks(){const t=s.useEditorStore(x=>x.card),n=s.useEditorStore(x=>{var h,g,k,m;return(m=(k=(g=(h=x.card)==null?void 0:h.preferences)==null?void 0:g.chartOptions)==null?void 0:k.plugins)==null?void 0:m.legend}),{setLegendOptions:a}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),o=(r==null?void 0:r.display)??!0,d=(r==null?void 0:r.position)??"top",i=(r==null?void 0:r.align)??"center",c=(x,h)=>{const g={...n,[x]:h};a(g)},l=["top","bottom","left","right"],u=["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(gt,{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)??o,onCheckedChange:x=>c("display",x)})]}),((n==null?void 0:n.display)??o)&&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)||d,onValueChange:x=>c("position",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:l.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]}),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)||i,onValueChange:x=>c("align",x),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(x=>e.jsx(s.SelectItem,{value:x,className:"text-xs",children:s.titleCase(x)},x))})]})]})]})]})})]})}function Gs(){var T,L,w,R,K,_,G,q,V,z,H;const t=s.useEditorStore(P=>P.card),n=s.useEditorStore(P=>{var W,Y;return(Y=(W=P.card)==null?void 0:W.preferences)==null?void 0:Y.dataLabelsConfig}),a=s.useEditorStore(P=>{var W;return(W=P.card)==null?void 0:W.preferences}),{setCardPreferences:r,updateCardInFrame:o}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const d=t.type==="bullet"?((T=a==null?void 0:a.bulletConfig)==null?void 0:T.orientation)??(((L=a==null?void 0:a.chartOptions)==null?void 0:L.indexAxis)==="x"?"vertical":"horizontal"):void 0,i=d!=null?d==="horizontal":((w=a==null?void 0:a.chartOptions)==null?void 0:w.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",l=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",u=!l,x=t.type==="bubble"||t.type==="scatter",h=(K=(R=a==null?void 0:a.chartOptions)==null?void 0:R.plugins)==null?void 0:K.datalabels,g=(h==null?void 0:h.display)!==!1&&((h==null?void 0:h.anchor)||(h==null?void 0:h.align)),k=s.getDefaultDataLabelsConfig(t.type,t.preferences),m=n??k,f=(k==null?void 0:k.enabled)??g??!1,v=(n==null?void 0:n.enabled)!==void 0?n.enabled:f,C=(P,W)=>{const J={...k??{},...n??{},[P]:W};P==="enabled"&&(J.display=W,W&&x&&!J.position&&(J.position="bottom")),P==="position"&&x&&(J.position="bottom");const ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},A=(P,W)=>{const Y=n??{},J={...k??{},...Y,font:{...Y.font||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},B=(P,W)=>{const Y=n??{},J={...k??{},...Y,formatOptions:{...Y.formatOptions||{},[P]:W}},ne={...t.preferences||{},dataLabelsConfig:J};r(ne);const le={...t,preferences:ne};o(le)},O=()=>{const P=t.type;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":i?"right":"top"},E=t.type!=="treemap"&&t.type!=="heatmap",N=t.type!=="treemap",p=O();let j=[];if(E)if(x)j=["bottom"];else if(c||l)j=["center"];else{const P=i?["center","left","right"]:["center","top","bottom"];j=["auto",...t.type==="bullet"?P:P.filter(Y=>Y!==p),"custom"]}const S=()=>s.titleCase(p),M=["center","start","end"],y=["center","start","end","top","bottom"],b=u?["auto","number","currency","percent","none"]:["number","currency","percent","none"],I=[{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"}],F=[{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(It,{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:v,onCheckedChange:P=>C("enabled",P)})]}),v&&e.jsxs(e.Fragment,{children:[E&&!c&&!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:x?(m==null?void 0:m.position)||"bottom":(m==null?void 0:m.position)||"auto",onValueChange:P=>C("position",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"?S():P==="custom"?"Custom (Advanced)":s.titleCase(P)},P))})]})]}),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:P=>C("showTotal",P)})]}),(m==null?void 0:m.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:(m==null?void 0:m.anchor)||"center",onValueChange:P=>C("anchor",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:M.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]}),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((m==null?void 0:m.align)||"center"),onValueChange:P=>C("align",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:y.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:s.titleCase(P)},P))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(m==null?void 0:m.format)||(u?"auto":"none"),onValueChange:P=>C("format",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(P=>e.jsx(s.SelectItem,{value:P,className:"text-xs",children:P==="auto"&&u?"Auto (Use Axis)":P==="none"?"None (Raw Value)":s.titleCase(P)},P))})]})]}),(m==null?void 0:m.format)&&!["auto","none"].includes(m.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(m.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(pe,{type:"number",placeholder:"0",value:String(((_=m==null?void 0:m.formatOptions)==null?void 0:_.decimalPlaces)??(m.format==="currency"?2:m.format==="percent"?1:0)),onSave:P=>B("decimalPlaces",Number(P)),className:""})})]}),m.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:((G=m==null?void 0:m.formatOptions)==null?void 0:G.currency)||"USD",onValueChange:P=>B("currency",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:I.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]}),["number","currency"].includes(m.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:((q=m==null?void 0:m.formatOptions)==null?void 0:q.useSuffix)??!1,onCheckedChange:P=>B("useSuffix",P)})]}),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:((V=m==null?void 0:m.formatOptions)==null?void 0:V.locale)||"en-US",onValueChange:P=>B("locale",P),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:F.map(P=>e.jsx(s.SelectItem,{value:P.value,className:"text-xs",children:P.label},P.value))})]})]})]}),N&&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(pe,{type:"number",placeholder:"12",value:String(((z=m==null?void 0:m.font)==null?void 0:z.size)||12),onSave:P=>A("size",Number(P)),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:((H=m==null?void 0:m.font)==null?void 0:H.weight)||"normal",onValueChange:P=>A("weight",P),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:(m==null?void 0:m.color)==="auto"||!(m!=null&&m.color)?"auto":"custom",onValueChange:P=>{P==="auto"&&C("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(pe,{type:"number",placeholder:"0",value:String((m==null?void 0:m.rotation)||0),onSave:P=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const us=["poor","satisfactory","good"];function ms(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function qs(){var I,F;const t=s.useEditorStore(T=>T.card.preferences),n=s.useEditorStore(T=>T.card),a=s.useEditorStore(T=>T.isDevMode),{setCardPreferences:r,setChartOrientation:o}=s.useEditorActions(),d=D.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),c=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,u]=D.useState(d.showRanges??!1),[x,h]=D.useState(d.rangesArePercentages??!1),g=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c,[k,m]=D.useState(g);D.useEffect(()=>{u(d.showRanges??!1)},[d.showRanges]),D.useEffect(()=>{h(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const f=d.targetValue===void 0?"":String(d.targetValue);D.useEffect(()=>{const T=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!c;m(T)},[d.disableAutoComparative,d.comparativeMetricKey,c]);const v=D.useMemo(()=>{var T,L;return((L=(T=n==null?void 0:n.config)==null?void 0:T.metricColumns)==null?void 0:L.map(w=>{const R=w.label||w.name||w.alias||"";return{value:R,label:R}}))||[]},[(I=n==null?void 0:n.config)==null?void 0:I.metricColumns]);D.useEffect(()=>{var q,V;if(!t||v.length===0)return;const T={};let L=!1;const w=(q=v[1])==null?void 0:q.value;!d.targetMetricKey&&w&&(T.targetMetricKey=w,L=!0);const R=(V=v[2])==null?void 0:V.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&R&&(T.comparativeMetricKey=R,L=!0);const K=v.slice(3),_={...d.rangeKeys||{}};let G=!1;if(us.forEach((z,H)=>{!_[z]&&K[H]&&(_[z]=K[H].value,G=!0)}),G&&(T.rangeKeys=_,L=!0,d.showRanges===void 0&&(T.showRanges=!0)),L){const z=ms({...d,...T});r({...t,bulletConfig:z})}},[v,d,t,r]);const C=T=>{const L=ms({...d,...T});r({...t,bulletConfig:L})},A=(T,L)=>{const w={...d.rangeKeys||{},[T]:L.trim()};L.trim()||delete w[T],C({rangeKeys:Object.keys(w).length>0?w:void 0})},B=(T,L)=>{const w=L===""?void 0:Number(L),R={...d.ranges||{}};w===void 0||Number.isNaN(w)?delete R[T]:R[T]=w,C({ranges:Object.keys(R).length?R:void 0})},O=T=>{if(T===""){C({targetValue:void 0});return}const L=Number(T);C({targetValue:Number.isNaN(L)?void 0:L})},E=(T,L)=>{const w=L.trim(),R={...d.rangeLabels||{}};w?R[T]=w:delete R[T],C({rangeLabels:Object.keys(R).length>0?R:void 0})},N=T=>{u(T),C({showRanges:T})},p=T=>{h(T),C({rangesArePercentages:T})},j=d.orientation||(((F=t==null?void 0:t.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),S=T=>{C({orientation:T}),o(T==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...v.map(T=>({value:T.value,label:T.label}))],y=M,b=T=>{if(m(T),!T){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){C({disableAutoComparative:!1});return}if(d.comparativeMetricKey)C({disableAutoComparative:!1});else{const L=v.find(w=>w.value!==d.targetMetricKey);C({comparativeMetricKey:L==null?void 0:L.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",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.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:j,onValueChange:T=>S(T),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:d.targetMetricKey||"__none",onValueChange:T=>C({targetMetricKey:T==="__none"?void 0:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),v.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(s.Select,{value:d.comparativeMetricKey||"__none",onValueChange:T=>C({comparativeMetricKey:T==="__none"?void 0:T,disableAutoComparative:T==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(T=>e.jsx(s.SelectItem,{value:T.value,className:"text-xs",children:T.label},T.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:k,onCheckedChange:T=>b(T)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(ce,{type:"number",className:"h-8 text-xs",value:f,onCommit:O,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:l,onCheckedChange:N})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!l,onChange:T=>p(T.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:us.map(T=>{var L,w,R,K,_;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," LABEL"]}),e.jsx(ce,{placeholder:`Display label (${T})`,value:((L=d.rangeLabels)==null?void 0:L[T])||"",onCommit:G=>E(T,G),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN"]}),e.jsxs(s.Select,{value:((w=d.rangeKeys)==null?void 0:w[T])||"__none",onValueChange:G=>{G==="__none"?A(T,""):A(T,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:y.map(G=>e.jsx(s.SelectItem,{value:G.value,className:"text-xs",children:G.label},G.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," COLUMN KEY"]}),e.jsx(ce,{placeholder:"Column key",value:((R=d.rangeKeys)==null?void 0:R[T])||"",onCommit:G=>A(T,G),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[T," VALUE"]}),e.jsx(ce,{type:"number",placeholder:x?"0.80":"Static value",value:((K=d.ranges)==null?void 0:K[T])===void 0?"":String((_=d.ranges)==null?void 0:_[T]),onCommit:G=>B(T,G),className:"h-8 text-xs"})]})]},T)})})]})]})]})}const xs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Ln=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Fe({value:t,onChange:n,label:a}){const[r,o]=D.useState(!1),[d,i]=D.useState(!1),c=()=>{const l=xs.find(u=>u.value===t);return l?l.color:t.startsWith("#")?t:xs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange: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:c()},"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:Ln.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),o(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{i(!0),o(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),d&&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:()=>i(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Vs,{color:c(),onColorChange:l=>{n(l),i(!1)},onClose:()=>i(!1)})})]})]})}const Fn=Object.keys(s.HEATMAP_PRESET_PALETTES);function Us(){const t=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>{var k;return(k=g.card)==null?void 0:k.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",o=(n==null?void 0:n.heatmapConfig)||{},d=o.colorPalette??"green",i=o.legendPosition??"bottom",c=D.useMemo(()=>o.colorRange&&o.colorRange[0]&&o.colorRange[1]?[o.colorRange[0],o.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[o.colorRange]),l=g=>{const k={...o,...g};k.colorPalette!=="custom"?delete k.colorRange:(!k.colorRange||!k.colorRange[0]||!k.colorRange[1])&&(k.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:k})},u=g=>{l({colorPalette:g,colorRange:g==="custom"?o.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(g,k)=>{const m=[...c];m[g]=k,l({colorPalette:"custom",colorRange:m})},h=g=>{l({legendPosition:g})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:d,onValueChange:g=>u(g??"blue"),className:"space-y-3",children:[Fn.map(g=>{const k=s.HEATMAP_PRESET_PALETTES[g];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${g}`,value:g}),e.jsxs(s.Label,{htmlFor:`heatmap-${g}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:k.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${k.start}, ${k.end})`}})]})]},g)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Fe,{value:c[0],onChange:g=>x(0,g),label:"Start color"}),e.jsx(Fe,{value:c[1],onChange:g=>x(1,g),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:i,onValueChange:g=>h(g??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(g=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:g[0].toUpperCase()+g.slice(1)},g))})]})]})]})]}):null}function hs(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function _s(){var E,N,p,j,S,M,y,b,I,F,T,L;const t=s.useEditorStore(w=>w.card.preferences),n=s.useEditorStore(w=>w.card),a=s.useEditorStore(w=>w.card.type),r=s.useEditorStore(w=>w.isDevMode),{setCardPreferences:o,updateCardInFrame:d}=s.useEditorActions(),i=a==="bubble",c=a==="scatter",l=D.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),x=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,h=D.useMemo(()=>{var w,R;return((R=(w=n==null?void 0:n.config)==null?void 0:w.metricColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(E=n==null?void 0:n.config)==null?void 0:E.metricColumns]),g=D.useMemo(()=>{var w,R;return((R=(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns)==null?void 0:R.map(K=>{const _=K.label||K.name||K.alias||"";return{value:_,label:_}}))||[]},[(N=n==null?void 0:n.config)==null?void 0:N.groupByColumns]),k=D.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&g.length>=2,[l.enableGrouping,r,g.length]),[m,f]=D.useState(k);D.useEffect(()=>{f(k)},[k]);const v=w=>{const R={...t||{},bubbleScatterConfig:w};o(R),n&&d({...n,preferences:R})},C=w=>{o(w),n&&d({...n,preferences:w})};D.useEffect(()=>{if(!t||h.length===0)return;const w={};let R=!1;if(!l.xMetricKey&&h[0]&&(w.xMetricKey=h[0].value,R=!0),!l.yMetricKey&&h[1]&&(w.yMetricKey=h[1].value,R=!0),i&&!l.radiusMetricKey&&h[2]&&(w.radiusMetricKey=h[2].value,R=!0),!l.labelKey&&g[0]&&(w.labelKey=g[0].value,R=!0),k&&!l.groupKey&&g[1]&&(w.groupKey=g[1].value,w.enableGrouping=!0,R=!0),R){const K=hs({...l,...w});v(K)}},[h,g,l,t,o,i,k]);const A=w=>{const R=hs({...l,...w});v(R)},B=w=>{f(w),A({enableGrouping:w,groupKey:w?l.groupKey:void 0})};if(!i&&!c)return null;const O=i?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),x?e.jsxs(s.Select,{value:l.labelKey||"",onValueChange:w=>A({labelKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:g.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:w=>A({labelKey:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:B})]}),m&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(s.Select,{value:l.groupKey||"",onValueChange:w=>A({groupKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:g.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:w=>A({groupKey:w})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),x?e.jsxs(s.Select,{value:l.xMetricKey||"",onValueChange:w=>A({xMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:w=>A({xMetricKey:w})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:w=>A({yMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:w=>A({yMetricKey:w})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:w=>A({radiusMetricKey:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:h.map(w=>e.jsx(s.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(ce,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:w=>A({radiusMetricKey:w})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:w=>A({radiusScale:w}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),l.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((p=l.minRadius)==null?void 0:p.toString())||"",onCommit:w=>A({minRadius:w?Number(w):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(ce,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((j=l.maxRadius)==null?void 0:j.toString())||"",onCommit:w=>A({maxRadius:w?Number(w):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([w])=>A({fixedRadius:w}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([w])=>A({fixedRadius:w}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((M=(S=t==null?void 0:t.xAxisConfig)==null?void 0:S.name)==null?void 0:M.enabled)??!1,onCheckedChange:w=>{var _,G,q,V;const R=l.xMetricKey||"X Axis",K=l.yMetricKey||"Y Axis";C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:w,text:((G=(_=t==null?void 0:t.xAxisConfig)==null?void 0:_.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:w,text:((V=(q=t==null?void 0:t.yAxisConfig)==null?void 0:q.name)==null?void 0:V.text)||K}}})}})]}),((b=(y=t==null?void 0:t.xAxisConfig)==null?void 0:y.name)==null?void 0:b.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((F=(I=t==null?void 0:t.xAxisConfig)==null?void 0:I.name)==null?void 0:F.text)||"",onCommit:w=>{var R;C({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:w||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(ce,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((L=(T=t==null?void 0:t.yAxisConfig)==null?void 0:T.name)==null?void 0:L.text)||"",onCommit:w=>{var R;C({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:w||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Bn=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Hs(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",o=(n==null?void 0:n.funnelConfig)||{},d=o.percentMode??"percentOfTotal",i=l=>{const u={...o,...l};a({...n||{},funnelConfig:u})},c=l=>{i({percentMode:l})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:d,onValueChange:l=>c(l),className:"space-y-2",children:Bn.map(l=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${l.value}`,value:l.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${l.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:l.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:l.description})]})]},l.value))})]})})]}):null}function On(){const t=s.useEditorStore(n=>n.card);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:[(t==null?void 0:t.type)==="funnel"&&e.jsx(Hs,{}),(t==null?void 0:t.type)==="heatmap"&&e.jsx(Us,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(qs,{}),((t==null?void 0:t.type)==="bubble"||(t==null?void 0:t.type)==="scatter")&&e.jsx(_s,{}),e.jsx(zs,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})]})}const Rn=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."]})]}),Pn=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."]})]}),Vn=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 zn(){const t=s.useEditorStore(a=>a.card.type);function n(a){const r=["kpi","table","text","map","custom"],o=d=>r.includes(a)?d:e.jsxs(e.Fragment,{children:[d,e.jsx(On,{})]});switch(a){case"stackedBar":case"stackedLine":return o(e.jsx(Sn,{}));case"tornado":case"pyramid":return o(e.jsx(Oe,{docContent:Rn,cardType:a}));case"kpi":return e.jsx(jn,{});case"line":case"bar":return o(e.jsx(dn,{cardType:a}));case"range":return o(e.jsx(Oe,{docContent:Pn,cardType:a}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return o(e.jsx(Oe,{cardType:a}));case"bubble":case"scatter":return o(e.jsx(un,{cardType:a}));case"table":return e.jsx(wn,{cardType:a});case"text":return e.jsx(Oe,{docContent:Vn,cardType:a,suffix:"Visual"});case"map":return e.jsx(Nn,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Fs,{})});default:return o(e.jsx(hn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function $n(){const t=D.useRef(null),n=D.useRef(null),a=s.useEditorStore(o=>o.isShowingVisual),r=s.useEditorStore(o=>o.showAIDialog);return D.useEffect(()=>{var o,d,i,c;r?((o=t.current)==null||o.resize(0),(d=n.current)==null||d.resize(0)):((i=t.current)==null||i.resize(25),(c=n.current)==null||c.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(zt,{})}),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(zn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(os,{})})]}):e.jsx(os,{})})]})}function Kn(t){var oe;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=D.useState(""),[r,o]=D.useState(null),{authToken:d,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.sql}),l=s.useEditorStore($=>$.isDevMode),u=s.useEditorStore($=>{var se;return(se=$==null?void 0:$.card)==null?void 0:se.python}),{setCardPython:x,setCardSql:h,setRunSql:g,switchCardType:k,setQueryConfig:m}=s.useEditorActions(),f=s.useEditorStore($=>$.currentAssitantScope)||[],v=s.useEditorStore($=>$.userInputForAI),C=s.useEditorStore($=>$.triggerAIRun),A=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),E=s.useEditorStore($=>$.selectedConnectionId),N=s.useEditorStore($=>$.selectedSchemaName),p=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:j,refetch:S,data:M}=s.useDashboardCardQuery(A),{setTriggerAIRun:y,setCurrentAssitantScope:b,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:F,connectionType:T,selectedDatamodelId:L}=s.useEditorAside(),w=(oe=s.useDashboardQuery().data)==null?void 0:oe.assistantProfileId,{messages:R,setMessages:K,regenerate:_,error:G,sendMessage:q,status:V,addToolResult:z,stop:H,clearError:P}=s.useChat({transport:new s.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:w,isDevMode:l,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:se})=>({body:{...se,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var se;if($.name==="AbortError"||(se=$.message)!=null&&se.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:W,onFinish({isAbort:$,isDisconnect:se,isError:de}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":se?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});D.useEffect(()=>{C&&v&&(q({role:"user",parts:[{type:"text",text:v}]}),y(!1))},[C,v,q,y]);async function W({toolCall:$}){var se,de,ue,we,me,je,xe,be,ke,fe,Te,Ee,Ae,Ie,ve,ye;if(["createChartFromSql","createForecast"].includes($.toolName)){const Q=((se=$.input)==null?void 0:se.sql)??((de=$.args)==null?void 0:de.sql),ae=((ue=$.input)==null?void 0:ue.python)??((we=$.args)==null?void 0:we.python),re=((me=$.input)==null?void 0:me.chartType)??((je=$.args)==null?void 0:je.chartType);k(re),h(Q),x(ae),g(!0),z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!c){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:c,python:u||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const Q=((xe=$.input)==null?void 0:xe.chartType)??((be=$.args)==null?void 0:be.chartType),ae=((ke=$.input)==null?void 0:ke.queryConfig)??((fe=$.args)==null?void 0:fe.queryConfig);((Te=$.input)==null?void 0:Te.cardConfig)??((Ee=$.args)==null||Ee.cardConfig),k(Q),I(ae),h(void 0),x(void 0);const re=await S();if((Ae=re==null?void 0:re.data)!=null&&Ae.error){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ae,message:(Ie=re==null?void 0:re.data)==null?void 0:Ie.error.message}});return}if((ve=re==null?void 0:re.data)!=null&&ve.records){z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized"}});return}z({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ae,message:"The data has been visualized",records:(ye=re==null?void 0:re.data)==null?void 0:ye.records}})}else a("Analyzing...")}function Y($){const se=s.removeFromScopeArray(f,$);ee(se)}function ee($){const se=s.sanitizeAIScope($);b(se),K(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(se)}`}]}])}function J(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelId:L||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||""},se=s.dedup([...f,$]);ee(se)}function ne(){const $={databaseName:B||"",schemaName:N||"",tableName:O||"",datamodelName:s.resolveDatamodelName(F),connectionId:E||"",connectionType:T||"",datamodelId:L||""};if(!s.isInAiScopeArray([...p||[],...f],$)||f.length===0){const de=s.dedup([...p||[],...f,$]).filter(ue=>ue.connectionId===$.connectionId);ee(de)}}const le=!["ready","error"].includes(V),Z=s.getErrorMessage(G);return{messages:R,setMessages:K,sendMessage:q,regenerate:_,isLoading:le,handleSetAIScope:ne,handleAddCurrentTableToScope:J,removeFromCurrentSelections:Y,currentAssitantScope:f,setCurrentAssitantScope:b,stop:H,status:V,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:Z,clearError:P}}const Gn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function ps({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=D.useRef(null),[o,d]=D.useState(!1),[i,c]=D.useState(s.isDevEnv),[l,u]=D.useState(!1),[x,h]=D.useState(!1),[g,k]=D.useState(!1),m=t??g,f=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:C}=s.useQueueActions(),{clearFileAttachments:A}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),N=s.useEditorStore(Q=>Q.actions.setCardSql),p=s.useEditorStore(Q=>Q.actions.setRunSql),j=s.useEditorStore(Q=>Q.showAIDialog),S=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:y}=s.useEditorActions(),{setDataSource:b}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:F,setMessages:T,sendMessage:L,isLoading:w,stop:R,status:K,llmUsage:_,errorMessage:G,clearError:q}=Kn(),[V,z]=D.useState(""),H=Q=>{z(Q.target.value)},P=Q=>{Q.preventDefault();const ae=V.trim();if(!ae&&B.length===0)return;const re=[];ae&&re.push({type:"text",text:ae}),B.forEach(Ne=>{Ne.data&&re.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),L({role:"user",parts:re}),z(""),A("editor"),se({force:!0})},{visibleMessages:W,hasMoreMessages:Y,totalMessageCount:ee,loadMoreMessages:J,resetMessageWindow:ne}=s.useMessageWindow(F,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:le,isAtBottom:Z,hasNewMessages:oe,newMessageCount:$,scrollToBottom:se,handleScroll:de,resetNewMessageCount:ue}=s.useAutoScroll(W,{threshold:50,behavior:"smooth",isStreaming:w});D.useEffect(()=>{var Q;j&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[j,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:K,isLoading:w,sendMessage:L});const{hasActiveTools:we}=s.useActiveToolStatus(F),me=D.useCallback(Q=>{n==null||n(Q),t===void 0&&k(Q)},[t,n]);D.useEffect(()=>{if(!m)return;function Q(ae){ae.key==="Escape"&&me(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[m,me]);const je=D.useCallback(Q=>{L({role:"user",parts:[{type:"text",text:Q}]}),se({force:!0})},[L,se]),xe=D.useCallback(async()=>{const Q=JSON.stringify(F??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ae){console.error("Failed to copy conversation",ae),s.ue.error("Unable to copy conversation")}},[F]),be=D.useCallback(()=>{me(!m)},[m,me]);function ke(Q,ae){ae==="sql"?(N(Q),p(!0)):ae==="python"&&(y(Q),p(!0))}function fe(){f.selectedEntities.length===0&&v({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function Te(Q){fe();const ae={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};L(ae)}function Ee(Q){fe(),L({role:"user",parts:[{type:"text",text:Q}]})}function Ae(){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 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:o,onCheckedChange:d,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"System Message"})]})]})}function Ie(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ve=(V==null?void 0:V.length)===0&&(F==null?void 0:F.filter(Q=>Q.role==="user").length)===0,ye=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",m&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ie(),S&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:S,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Ae(),i&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:xe,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:m?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:be,children:m?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{T([]),C("editor"),q(),ne()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:le,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:J,className:"text-xs",children:["Load ",Math.min(5,ee-W.length)," ","more messages (",ee-W.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:W,showTools:i,handleRun:ke,showSystemMessage:l,onQuickReply:je,disableQuickReplies:w}),!we&&e.jsx(s.AssistantStatus,{status:K,errorMessage:G})]})}),j&&!Z&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{se({force:!0}),ue()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),oe&&$>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:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ve&&!I&&e.jsx(s.Placeholders,{onClick:Te,placeholders:Gn}),e.jsx("div",{children:ve&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:Ee})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:z,stop:R,input:V,handleInputChange:H,handleSubmit:Q=>{fe(),P(Q),se({force:!0})},isLoading:w,status:K,assistantType:"editor",onFocus:()=>{}})]}),_&&o&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:x,onOpenChange:h,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return m&&a?nt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:ye})}),a):ye}const qn="chart-selector-standard-first";function Un(){const[t,n]=Ve(qn,!0);return{standardFirst:t,updatePreference:n}}const fs=({pluginVisual:t,index:n,onSelect:a})=>{const r=s.useDynamicIcon(t.icon||""),o=t.name.charAt(0).toUpperCase(),d=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"}):d||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}`)},gs=["default","standardPlugin","customPlugin"];function _n({selectedChart:t,onChartChange:n}){var E;const[a,r]=D.useState(!1),{data:o}=s.useCustomVisualsQuery();Un();const i=((E=s.useEditorStore(N=>N.card).customCardPreferences)==null?void 0:E.url)||"";at.useRemoteChartStore(i);const{setCardType:c,setCardPreferences:l,setIsDevMode:u}=s.useEditorStore(N=>N.actions),{setCardCustomCfg:x,setCustomCardPreferences:h,setQueryConfig:g}=s.useEditorActions(),[k,m]=Ve("chart-section-active",null),f=D.useMemo(()=>k?[k,...gs.filter(N=>N!==k)]:gs,[k]);function v(N){x(null),l({}),c(N),["custom","map"].includes(N)&&(u(!0),g(void 0)),n(N),r(!1)}function C(N){x(null),l({}),c("custom"),h({type:"component",visualType:"single",url:N.url,componentName:N.name,icon:N.icon,pluginChartType:N.chartType}),g(void 0),n("custom"),r(!1)}const A=D.useMemo(()=>{let N=s.chartTypes;return N=s.chartTypes.filter(j=>j.id!=="tableBuilder"),N.some(j=>j.id==="bullet")?N:[...N,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}]},[]),B=()=>{var p;if(t==="custom"){const j=s.useEditorStore.getState().card;return((p=j==null?void 0:j.customCardPreferences)==null?void 0:p.componentName)||"Custom Visual"}const N=A.find(j=>j.id===t);return(N==null?void 0:N.label)||"Select chart type"},O=()=>{var p,j;if(t==="custom"){const S=s.useEditorStore.getState().card,M=(p=S==null?void 0:S.customCardPreferences)==null?void 0:p.icon,y=(j=S==null?void 0:S.customCardPreferences)==null?void 0:j.componentName;if(M&&y)return e.jsx(Hn,{icon:M,componentName:y});if(y){const b=s.getAutoDetectedChartIcon(y);if(b)return b}return e.jsx(De,{className:"h-4 w-4"})}const N=A.find(S=>S.id===t);if(N){const S=N.icon;return e.jsx(S,{className:"h-4 w-4"})}return e.jsx(De,{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:[O(),e.jsx("span",{children:B()})]}),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."}),f.map(N=>{if(N==="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:k==="default",onCheckedChange:p=>m(p?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:A.map(p=>{const j=p.icon;return e.jsx(s.CommandItem,{value:`${p.label} ${p.id} chart graph visualization`,onSelect:()=>v(p.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j,{className:"h-4 w-4"}),e.jsx("span",{children:p.label})]})},p.id)})},"default");if(N==="standardPlugin"){const p=o.filter(j=>j.pluginType==="standard");return p.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:k==="standardPlugin",onCheckedChange:j=>m(j?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:p.filter(j=>j.componentType==="chart").map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"standardPlugin"):null}if(N==="customPlugin"){const p=o.filter(j=>j.pluginType==="custom");return p.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:k==="customPlugin",onCheckedChange:j=>m(j?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:p.map((j,S)=>e.jsx(fs,{pluginVisual:j,index:S,onSelect:()=>C(j)},`${j.url}-${j.name}-${S}`))},"customPlugin"):null}return null})]})]})})]})})}const Hn=({icon:t,componentName:n})=>{const a=s.useDynamicIcon(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(De,{className:"h-4 w-4"})},Jn=[{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:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function Qn({selectedChart:t,onChartChange:n,isDropdownExpanded:a,onToggleDropdown:r}){var c;const o=s.useEditorStore(l=>l.card),d=((c=o==null?void 0:o.config)==null?void 0:c.pivotByColumns)&&o.config.pivotByColumns.length>0,i=Jn.filter(l=>!(l.requiresPivot&&!d));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[i.map(l=>{const u=l.icon,x=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",x&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:l.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:l.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},l.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":a?"Hide all charts":"Show all charts",children:a?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:a?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}let Yn=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce((n,a)=>(a&=63,a<36?n+=a.toString(36):a<62?n+=(a-26).toString(36).toUpperCase():a>62?n+="-":n+="_",n),"");const Pe=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}];function Wn(t,n,a,r,o,d,i,c,l){const u=Pe.find(f=>f.id===n);if(!u)throw new Error(`Unknown operation: ${n}`);let x,h=[],g;if(n==="custom"){if(!(c!=null&&c.trim()))throw new Error("Custom expression is required");x=c.trim()}else if(n==="scale"){if(!a)throw new Error("Metric A is required for scale operation");if(l===void 0||l===0)throw new Error("Constant factor is required for scale operation");x=u.template().replace("{constant}",String(l)),h=[a],g=l}else{if(!a||!r)throw new Error("Metrics A and B are required for standard operations");x=u.template(),h=[a,r]}const k={operation:n,inputFields:h,...g!==void 0&&{constant:g}};return{id:i||`calc_${Yn(10)}`,name:t.toLowerCase().replace(/\s+/g,"_"),label:t,alias:t.toLowerCase().replace(/\s+/g,"_"),qualifiedFieldName:t.toLowerCase().replace(/\s+/g,"_"),dataType:"number",role:"metric",aggregate:"SUM",expression:x,calculatedFormula:k,entityId:d,entityName:s.CALCULATED_FIELD_ENTITY_MARKER,entityType:"table",description:`Calculated field: ${t}`}}function js(t){var r,o;const n=Pe.find(d=>d.id===t.operation);if(!n)return"Unknown operation";if(t.operation==="custom")return"Custom expression";if(t.operation==="scale"){const d=((r=t.inputFields[0])==null?void 0:r.label)||((o=t.inputFields[0])==null?void 0:o.name)||"A",i=t.constant??1;return`${d} × ${i}`}return t.inputFields.map(d=>d.label||d.name).join(` ${n.symbol} `)}const We=({dataType:t})=>s.getFieldIconComponent(t);function Xn({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=D.useState(t),[o,d]=D.useState(!1),i=(l=s.useEditorStore(u=>{var x;return(x=u.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:l[0],c=i?`e.g. Min Sales in {{${i.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,{placeholder:c,value:o?a:t,onChange:u=>{r(u.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&o&&a!==t?(n(a),d(!1)):u.key==="Escape"&&(r(t),d(!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),d(!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),d(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Zn({valueAliases:t,onValueAliasesChange:n}){const[a,r]=D.useState(null),[o,d]=D.useState(""),[i,c]=D.useState(""),l=()=>{n({...t,"":""})},u=h=>{const g={...t};delete g[h],n(g)},x=h=>{const g={...t};delete g[h],g[o]=i,n(g),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,g],k)=>e.jsx("div",{className:"flex items-center gap-2",children:a===h?e.jsxs(e.Fragment,{children:[e.jsx(s.Input,{placeholder:"Value key",value:o,onChange:m=>d(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:i,onChange:m=>c(m.target.value),className:"h-8 w-24 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.key==="Enter"?x(h):m.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:()=>x(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,{placeholder:"Value key",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(g)},"aria-label":"Edit value alias key"}),e.jsx(s.Input,{placeholder:"Alias label",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(h),d(h),c(g)},"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+k)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function ea({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var u,x;return(x=(u=l.card)==null?void 0:u.config)==null?void 0:x.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===t.label||l===t.name),d=o?r.indexOf(o):-1;function i(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(Rs,{idx:d,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){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(Ps,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&i(),["pie","doughnut"].includes(n)&&c()]})}function sa({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:o}=s.useSemaphorContext(),d=s.useEditorStore(u=>u.card),i=d==null?void 0:d.dataSource,c=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:c,queryFn:async()=>{if(!(i!=null&&i.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},x={connection_id:i.connectionId,cardConfig:u,cardDataSource:i,cache_config:s.getCacheConfig({card:d})};console.log("requestBody",x);const h=await s.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",x);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const g=t.name;return((h==null?void 0:h.records)||[]).map(m=>{const f=m[g]||m[t.alias||g]||m[t.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(i!=null&&i.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function Js({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:o,onSave:d}){var B,O;const i=!!o,[c,l]=D.useState(i?"values":"fields"),[u,x]=D.useState(""),[h,g]=D.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]:[]}),k=a.filter(E=>{var p;return i?!1:!((p=r==null?void 0:r.conditions)==null?void 0:p.some(j=>j.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),m=E=>{g({...h,field:E}),l("values")},f=()=>{if(h.field&&h.selectedValues.length>0){const E={id:h.id,field:h.field,operator:"in",value:h.selectedValues};let N;if(i){const p=((r==null?void 0:r.conditions)||[]).map(j=>j.id===o.id?E:j);N={...r,conditions:p}}else{const p=(r==null?void 0:r.conditions)||[];N={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...p,E],groups:[]}}d(N),n(!1)}},v=()=>{if(!i||!o)return;const E=((r==null?void 0:r.conditions)||[]).filter(N=>N.id!==o.id);if(E.length>0){const N={...r,conditions:E};d(N)}else d(void 0);n(!1)},C=E=>{g({...h,selectedValues:E})},A=()=>{i&&o?(g({id:o.id,field:o.field,selectedValues:Array.isArray(o.value)?o.value:[o.value]}),l("values")):(g({id:s.v4(),field:null,selectedValues:[]}),l("fields")),x("")};return D.useEffect(()=>{t&&A()},[t,i,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:i?`Edit Filter: ${(B=h.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(O=h.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="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(E=>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:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),c==="fields"&&!i?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,{placeholder:"Search fields...",value:u,onChange:E=>x(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:k.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>m(E),children:[e.jsx(We,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),k.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),k.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(ta,{field:h.field,selectedValues:h.selectedValues,onValuesChange:C,onBack:i?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:A,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:f,disabled:!h.field||h.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function ta({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[o,d]=D.useState(""),{values:i,isLoading:c,isFetching:l}=sa({field:t,searchQuery:o,limit:500}),u=o?i.filter(g=>String(g.value).toLowerCase().includes(o.toLowerCase())):i,x=g=>{const k=n.includes(g);a(k?n.filter(m=>m!==g):[...n,g])},h=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(g=>g.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,{placeholder:"Search values...",value:o,onChange:g=>d(g.target.value),className:"pl-10"})]}),c||l?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(g=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(g.value),children:[e.jsx(s.Checkbox,{checked:n.includes(g.value),onCheckedChange:()=>x(g.value)}),e.jsx(Qe,{className:"text-sm",children:g.label})]},g.id))})]})]})}function Qs({open:t,onOpenChange:n,availableMetrics:a,existingField:r,onSave:o,cardId:d}){const[i,c]=D.useState(""),[l,u]=D.useState("ratio"),[x,h]=D.useState(null),[g,k]=D.useState(null),[m,f]=D.useState(1),[v,C]=D.useState(""),[A,B]=D.useState({format:"number",decimalPlaces:2}),[O,E]=D.useState({}),N=Pe.find(b=>b.id===l),p=a.find(b=>b.id===x),j=a.find(b=>b.id===g);D.useEffect(()=>{if(r&&t)if(c(r.label),r.calculatedFormula)if(u(r.calculatedFormula.operation),r.calculatedFormula.operation==="custom")C(r.expression||"");else if(r.calculatedFormula.operation==="scale"){const b=r.calculatedFormula.inputFields;if(b.length>=1){const I=a.find(F=>F.qualifiedFieldName===b[0].qualifiedFieldName);h((I==null?void 0:I.id)||null)}r.calculatedFormula.constant!==void 0&&f(r.calculatedFormula.constant)}else{const b=r.calculatedFormula.inputFields;if(b.length>=2){const I=a.find(T=>T.qualifiedFieldName===b[0].qualifiedFieldName),F=a.find(T=>T.qualifiedFieldName===b[1].qualifiedFieldName);h((I==null?void 0:I.id)||null),k((F==null?void 0:F.id)||null)}}else u("custom"),C(r.expression||"")},[r,t,a]);const S=()=>{const b={};return i.trim()||(b.name="Name is required"),l==="custom"?v.trim()||(b.customExpression="Custom expression is required"):l==="scale"?(x||(b.inputA="Please select a metric for input A"),(isNaN(m)||m===0)&&(b.constantFactor="Please enter a valid non-zero number"),r&&x===r.id&&(b.circular="Cannot reference the field being edited")):(x||(b.inputA="Please select a metric for input A"),g||(b.inputB="Please select a metric for input B"),x===g&&(b.inputs="Inputs A and B must be different metrics"),r&&(x===r.id||g===r.id)&&(b.circular="Cannot reference the field being edited")),E(b),Object.keys(b).length===0},M=()=>{if(!S())return;const b=Wn(i,l,p||null,j||null,A,d,r==null?void 0:r.id,l==="custom"?v:void 0,l==="scale"?m:void 0);o(b),y()},y=()=>{c(""),u("ratio"),h(null),k(null),f(1),C(""),E({}),n(!1)};return e.jsxs(s.Dialog,{modal:!1,open:t,onOpenChange:n,children:[t&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-w-md max-h-[90vh] overflow-y-auto",onInteractOutside:b=>{b.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsxs(s.DialogTitle,{children:[r?"Edit":"Create"," Calculated Metric"]}),e.jsx(s.DialogDescription,{children:"Combine existing metrics to create a new calculated field"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"name",children:"Name"}),e.jsx(s.Input$1,{id:"name",value:i,onChange:b=>c(b.target.value),placeholder:"e.g., Profit Margin",className:O.name?"border-red-500":""}),O.name&&e.jsx("p",{className:"text-xs text-red-500",children:O.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"operation",children:"Outcome is"}),e.jsxs(s.Select,{value:l,onValueChange:b=>{u(b),b==="custom"?(h(null),k(null)):l==="custom"&&C("")},children:[e.jsx(s.SelectTrigger,{id:"operation",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"CALCULATED"}),Pe.map(b=>e.jsx(s.SelectItem,{value:b.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm",children:b.symbol}),e.jsx("span",{children:b.label})]})},b.id))]})})]}),N&&e.jsx("p",{className:"text-xs text-muted-foreground",children:N.description})]}),l==="custom"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"customExpression",children:"SQL Expression"}),e.jsx(s.Textarea,{id:"customExpression",value:v,onChange:b=>C(b.target.value),placeholder:"e.g., CASE WHEN revenue > 1000 THEN revenue - cost ELSE 0 END",className:s.cn("font-mono text-sm",O.customExpression&&"border-red-500"),rows:4}),O.customExpression&&e.jsx("p",{className:"text-xs text-red-500",children:O.customExpression}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Write a SQL expression using column names from your data source"})]}):e.jsxs("div",{className:"rounded-md bg-muted p-3 font-mono text-sm",children:["= ",x&&p?p.label:"A"," ",N==null?void 0:N.symbol," ",g&&j?j.label:"B"]}),l!=="custom"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"inputA",children:"Where"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"A"}),e.jsxs(s.Select,{value:x||"",onValueChange:h,children:[e.jsx(s.SelectTrigger,{id:"inputA",className:O.inputA?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputA&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputA})]}),l!=="custom"&&l!=="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded bg-muted font-mono text-sm font-medium",children:"B"}),e.jsxs(s.Select,{value:g||"",onValueChange:k,children:[e.jsx(s.SelectTrigger,{id:"inputB",className:O.inputB?"border-red-500":"",children:e.jsx(s.SelectValue,{placeholder:"+ Choose metric"})}),e.jsx(s.SelectContent,{children:a.filter(b=>!s.isCalculatedMetric(b)||b.id!==(r==null?void 0:r.id)).map(b=>e.jsxs(s.SelectItem,{value:b.id,children:[b.label||b.name,b.aggregate&&` (${b.aggregate})`]},b.id))})]})]}),O.inputB&&e.jsx("p",{className:"text-xs text-red-500",children:O.inputB})]}),l==="scale"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"constantFactor",children:"Multiplication Factor"}),e.jsx(s.Input$1,{id:"constantFactor",type:"number",step:"any",value:m,onChange:b=>f(parseFloat(b.target.value)||0),placeholder:"e.g., 0.15",className:O.constantFactor?"border-red-500":""}),O.constantFactor&&e.jsx("p",{className:"text-xs text-red-500",children:O.constantFactor}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enter the constant value to multiply the metric by (e.g., 0.15 for 15%)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"format",children:"Format"}),e.jsxs(s.Select,{value:A.format,onValueChange:b=>B({...A,format:b}),children:[e.jsx(s.SelectTrigger,{id:"format",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsxs(s.SelectItem,{value:"number",children:["Decimal (",A.decimalPlaces,")"]}),e.jsx(s.SelectItem,{value:"currency",children:"Currency"}),e.jsx(s.SelectItem,{value:"percent",children:"Percentage"})]})]})]}),(O.inputs||O.circular)&&e.jsxs(s.Alert,{variant:"destructive",children:[e.jsx(s.CircleAlert,{className:"h-4 w-4"}),e.jsx(s.AlertDescription,{children:O.inputs||O.circular})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:y,children:"Cancel"}),e.jsxs(s.Button,{onClick:M,children:[r?"Update":"Create"," Metric"]})]})]})]})}function na({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:d=!1,cardType:i}){var Ze,es,ss,ts,ns;const{attributes:c,listeners:l,setNodeRef:u,transform:x,transition:h,isDragging:g}=s.useSortable({id:t.id}),k=s.useEditorStore(U=>U.card),{updateLabel:m,handleAggregationChange:f,handleDateFormatChange:v,handleGranularityChange:C,handleAliasTemplateChange:A,handleValueAliasesChange:B,removeField:O,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:N,handleKpiTrendlineWindowChange:p,handleKpiTrendlineGranularityChange:j,handleKpiTargetValueChange:S}=s.useFieldManagement(k),[M,y]=D.useState(!1),[b,I]=D.useState(!1),[F,T]=D.useState(!1),[L,w]=D.useState(null),[R,K]=D.useState(t.dateFormat||"YYYY-MM-DD"),[_,G]=D.useState(t.customFormat||""),[q,V]=D.useState(!!t.customFormat),[z,H]=D.useState(t.granularity||"day"),[P,W]=D.useState(t.aliasTemplate||""),[Y,ee]=D.useState(t.valueAliases||{}),[J,ne]=D.useState((Ze=t.parameters)==null?void 0:Ze.filters),le=U=>{U==="custom"?V(!0):(V(!1),K(U),n==="groupBy"&&v(a,U,""))},Z=U=>{G(U),n==="groupBy"&&v(a,"custom",U)},oe=U=>{var ie;H(U);const X=(ie=s.getDateFormatOptionsForGranularity(U)[0])==null?void 0:ie.value;X&&!q&&(K(X),n==="groupBy"&&v(a,X,"")),n==="groupBy"&&C(a,U)},$=U=>{W(U),n==="metrics"&&A(a,U)},se=U=>{ee(U),n==="metrics"&&B(a,U)},de=U=>{m(n,a,U)},ue=U=>{var te;if(ne(U),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:U}},ie=[...((te=k.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ie})}I(!1)},we=()=>{O(n,a)},me={transform:s.CSS.Transform.toString(x),transition:h},je=s.getDataType(t.dataType),xe=je==="date",be=i==="kpi",ke=s.getDateFormatOptionsForGranularity(z),fe=n!=="pivotBy",Te=xe&&n==="groupBy"&&(!be||((es=k.config)==null?void 0:es.comparisonType)==="start_vs_end"),Ee=!be&&xe&&n==="groupBy",Ae=i&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(i)&&xe&&n==="groupBy",Ie=i==="kpi"&&xe&&n==="groupBy",ve=i&&i!=="pivotTable"&&n==="metrics"&&((ss=k.config)==null?void 0:ss.comparisonType)==="target",ye=n==="metrics",Q=()=>{const U=t,te=n==="metrics"&&s.isCalculatedMetric(U);return e.jsxs("div",{className:"space-y-1",children:[!te&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),te&&U.calculatedFormula&&e.jsxs("div",{title:js(U.calculatedFormula),onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",js(U.calculatedFormula)]})]})},ae=()=>fe?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(pe,{value:t.label??"",onSave:de,placeholder:"Display label...",type:"text"})]}):null,re=()=>Te?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:z,onValueChange:oe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U,children:s.toTitleCase(U)},U))})]})]}):null,Ne=()=>Ee?e.jsxs(e.Fragment,{children:[re(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:q?"custom":R,onValueChange:le,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:ke.map(U=>e.jsx(s.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.value))})]}),q&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:_,onChange:U=>{U.stopPropagation(),Z(U.target.value)},onClick:U=>U.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,Ws=()=>{var X,ie,Ce,Le,ge;const U=Ae,te=Ie;return!U&&!te?null:e.jsxs(e.Fragment,{children:[U&&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:((X=k.config)==null?void 0:X.comparisonType)||"none",onValueChange:E,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:"start_vs_end",children:"Start vs End"})]})]})]}),te&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ie=k.config)==null?void 0:ie.showTrendline)||!1,onCheckedChange:N})]})}),((Ce=k.config)==null?void 0:Ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input,{type:"number",min:"1",max:"365",value:((Le=k.config)==null?void 0:Le.trendlineWindow)||30,onChange:Be=>{const tt=parseInt(Be.target.value)||30;p(tt)},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:((ge=k.config)==null?void 0:ge.trendlineGranularity)||"day",onValueChange:j,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"})]})]})]})]})]})]})},Xs=()=>{var U,te;return ve?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(pe,{value:((U=k.config)==null?void 0:U.targetValue)!==void 0&&((te=k.config)==null?void 0:te.targetValue)!==null?String(k.config.targetValue):"",onSave:X=>{!isNaN(Number(X))&&X!==null?S(Number(X)):S(0)},placeholder:"Enter target value...",type:"text"})]}):null},Zs=()=>{if(!ye)return null;const U=t,te=s.isCalculatedMetric(U);return e.jsxs(e.Fragment,{children:[te&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>T(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),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:X=>{f(a,X)},disabled:te,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"}),(J==null?void 0:J.conditions)&&J.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:J.conditions.map(X=>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:()=>{w(X),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.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(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.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 (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((ie,Ce)=>e.jsx("div",{children:String(ie)},Ce))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ie=>{var Le;ie.stopPropagation();const Ce=J.conditions.filter(ge=>ge.id!==X.id);if(Ce.length>0){const ge={...J,conditions:Ce};ue(ge)}else if(ne(void 0),n==="metrics"){const ge={...t,parameters:{...t.parameters,filters:void 0}},Be=[...((Le=k.config)==null?void 0:Le.metricColumns)||[]];Be[a]=ge,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:Be})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{w(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(ea,{column:t}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Xn,{aliasTemplate:P,onAliasTemplateChange:$}),e.jsx(Zn,{valueAliases:Y,onValueAliasesChange:se})]})]})},{columns:et=[]}=s.useColumns(),st=(J==null?void 0:J.conditions)&&J.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:me,...c,...l,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 ${g?"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(We,{dataType:je}),e.jsx(Qe,{className:s.cn("w-[140px] flex-1 text-sm",st&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((ts=J==null?void 0:J.conditions)==null?void 0:ts.length)&&!M&&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:J.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:J.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),y(!M)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${M?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const te=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",te),o(te)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:U=>{U.stopPropagation(),we()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),M&&e.jsxs("div",{className:"space-y-3",children:[Q(),ae(),i==="kpi"&&re(),Ne(),Ws(),Xs(),Zs()]})]}),b&&e.jsx(Js,{open:b,onOpenChange:U=>{I(U),U||w(null)},availableFields:et,existingFilters:J,editingCondition:L,onSave:U=>{var te;if(U)ue(U);else if(ne(void 0),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:void 0}},ie=[...((te=k.config)==null?void 0:te.metricColumns)||[]];ie[a]=X,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:ie})}w(null)}}),F&&n==="metrics"&&e.jsx(Qs,{open:F,onOpenChange:T,availableMetrics:((ns=k.config)==null?void 0:ns.metricColumns)||[],existingField:t,onSave:U=>{var X;const te=[...((X=k.config)==null?void 0:X.metricColumns)||[]];te[a]=U,s.useEditorStore.getState().actions.updateCardConfig(k.id,{metricColumns:te})},cardId:k.id})]})}function aa({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:"Pivot 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:"Metric 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 Re({zone:t,fields:n,label:a,placeholder:r,shouldShow:o,hasPivotColumns:d=!1,activeField:i=null}){const{isOver:c,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),x=s.useEditorStore(v=>v.card),h=s.useEditorStore(v=>v.card.type),g=n.length>0,k=D.useMemo(()=>!i||!c?!0:s.validateFieldForChartType(i,t,h).isValid,[i,c,t,h]),m=(v,C)=>{var B;!((B=x.config)!=null&&B.sortByColumns)||x.config.sortByColumns.findIndex(O=>O.id===v)===-1||u(x.id,v,{direction:C})};if(t==="sortBy"&&o===!1)return null;const f=t!=="sortBy"&&h!=="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}),f&&e.jsx(aa,{concept:t})]}),e.jsx("div",{ref:l,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":c&&k,"border-red-500 bg-red-50 dark:bg-red-950":c&&!k,"border-muted-foreground/30 bg-muted/40":!c&&g,"min-h-[60px] border-muted-foreground/20 bg-background":!c&&!g}),children:n.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:n.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((v,C)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(na,{field:v,zone:t,index:C,sortDirection:B,onSortDirectionChange:O=>m(v.id,O),hasPivotColumns:d,cardType:h})})},v.id)})})})})]})}const bs={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%
200
200
  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 ra(){var g,k,m,f,v,C,A,B,O,E,N;const t=s.useEditorStore(p=>p.card),{setCardPreferences:n}=s.useEditorActions(),a=((g=t.config)==null?void 0:g.metricColumns)||[],r=((k=t.config)==null?void 0:k.groupByColumns)||[],o=a.length===2&&r.length===0,d=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(o||d)))return null;const c=((f=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:f.metricComparison)||{},l=p=>{var S;const j={...t.preferences,kpiVisualOptions:{...(S=t.preferences)==null?void 0:S.kpiVisualOptions,metricComparison:{...c,...p}}};n(j)},u=d||c.enabled,x=((v=t.config)==null?void 0:v.comparisonType)||"none",h=x==="previous_period"||x==="same_period_last_year"||x==="start_vs_end";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(pt,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[o&&a.length===2&&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:c.enabled||!1,onCheckedChange:p=>l({enabled:p,...p&&!c.calculationType?{calculationType:"difference"}:{}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const p=c.calculationType||"difference",j=bs[p];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:j==null?void 0:j.label}),e.jsx("p",{children:j==null?void 0:j.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:j==null?void 0:j.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",j==null?void 0:j.example]})]})})()})]})]}),e.jsxs(s.Select,{value:c.calculationType||"difference",onValueChange:p=>l({calculationType:p}),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(bs).map(([p,j])=>e.jsx(s.SelectItem,{value:p,className:"text-xs",children:j.label},p))})]})]}),e.jsx(Ye,{formatOptions:c.formatOptions||{},onFormatOptionsChange:p=>l({formatOptions:p}),showTitle:!0,title:"COMPARISON FORMAT"}),(h||o)&&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"}),o&&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:c.position||"right",onValueChange:p=>l({position:p}),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:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:c.showArrow!==!1,onCheckedChange:p=>l({showArrow:p})}),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:c.showColor!==!1,onCheckedChange:p=>l({showColor:p})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),c.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Fe,{value:((C=c.colorConfig)==null?void 0:C.increase)||"green",onChange:p=>l({colorConfig:{...c.colorConfig,increase:p}}),label:"Primary > Secondary"}),e.jsx(Fe,{value:((A=c.colorConfig)==null?void 0:A.decrease)||"red",onChange:p=>l({colorConfig:{...c.colorConfig,decrease:p}}),label:"Primary < Secondary"}),e.jsx(Fe,{value:((B=c.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:p=>l({colorConfig:{...c.colorConfig,noChange:p}}),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:c.conditionalLabel||!1,onCheckedChange:p=>l({conditionalLabel:p})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),c.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$1,{id:"label-increase",type:"text",value:((O=c.conditionalLabels)==null?void 0:O.increase)??"Increase",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,increase:p.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$1,{id:"label-decrease",type:"text",value:((E=c.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,decrease:p.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$1,{id:"label-no-change",type:"text",value:((N=c.conditionalLabels)==null?void 0:N.noChange)??"No change",onChange:p=>l({conditionalLabels:{...c.conditionalLabels,noChange:p.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:"Previous Label"}),e.jsx(s.Input$1,{id:"label-name",type:"text",value:c.labelName??"",onChange:p=>l({labelName:p.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function la(){var o,d;const t=s.useEditorStore(i=>i.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((d=(o=t.preferences)==null?void 0:o.kpiVisualOptions)==null?void 0:d.formatOptions)||{},r=i=>{var l;const c={...t.preferences,kpiVisualOptions:{...(l=t.preferences)==null?void 0:l.kpiVisualOptions,formatOptions:i}};n(c)};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(s.Hash,{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(Ye,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function oa(){var d;const t=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),n=s.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",o=i=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:i}};a(c)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:i=>o(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}function ia({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:o}){const[d,i]=D.useState(!1),c=s.useEditorStore(B=>{var O;return((O=B.card.customCardPreferences)==null?void 0:O.url)&&B.card.type==="custom"}),l=s.useEditorStore(B=>B.card),u=s.useEditorStore(B=>B.actions.updateCardConfig),x=l==null?void 0:l.type,h=t.length>0||a.length>0,g=x!=="kpi"||a.length<=2,k=x!=="kpi",m=x!=="kpi"&&h,f=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(x),v=k&&!f,C=()=>x==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},A=()=>x==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[g&&e.jsx(Re,{zone:"groupBy",fields:t,label:C().label,placeholder:C().placeholder,activeField:o}),v&&e.jsx(Re,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:o}),e.jsx(Re,{zone:"metrics",fields:a,label:A().label,placeholder:A().placeholder,hasPivotColumns:n.length>0,activeField:o}),a.length>=1&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>i(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),m&&e.jsx(Re,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:o})]})]}),!c&&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.Settings2,{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(la,{}),e.jsx(ra,{}),e.jsx(zs,{}),e.jsx(oa,{}),e.jsx(Us,{}),x==="bullet"&&e.jsx(qs,{}),x==="funnel"&&e.jsx(Hs,{}),(x==="bubble"||x==="scatter")&&e.jsx(_s,{}),e.jsx($s,{}),e.jsx(Ks,{}),e.jsx(Gs,{})]})})]}),c&&e.jsxs(s.AccordionItem,{value:"plugin",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(Ns,{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.jsx(Fs,{})})]})]}),e.jsx(Qs,{open:d,onOpenChange:i,availableMetrics:a,onSave:B=>{u(l.id,{metricColumns:[...a,B]})},cardId:l.id})]})}function ca({onEditJoins:t}){const n=s.useEditorStore(c=>c.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,o=(r==null?void 0:r.joins)||[];if(o.length===0)return null;const d=c=>!c||c.length===0?"No conditions":c.map(l=>{var g,k,m,f;const u=`${(g=l.source)==null?void 0:g.entityName}.${(k=l.source)==null?void 0:k.name}`,x=`${(m=l.target)==null?void 0:m.entityName}.${(f=l.target)==null?void 0:f.name}`,h=l.operator||"=";return`${u} ${h} ${x}`}).join(" AND "),i=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?d(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,u)=>({id:u,operator:l.operator,condition:d(l.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:o.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:o.map((c,l)=>{const u=i(c),x=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:c.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:x?u.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},c.id||l)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const vs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function da({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:d,activeField:i}){var p,j;const[c,l]=D.useState(()=>vs.getItem("chart-selector-expanded")==="true"),[u,x]=D.useState(!1),h=s.useEditorStore(S=>S.card),g=s.useEditorStore(S=>S.actions.updateCardConfig),k=a.length>0||r.length>0||o.length>0,{data:m,autoJoinMetadata:f}=s.useDashboardCardQuery(h),v=((p=h==null?void 0:h.config)==null?void 0:p.joinPlan)||(f!=null&&f.autoResolved?f.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],A=S=>{g(h.id,{...h==null?void 0:h.config,joinPlan:S}),x(!1)},B=()=>{g(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},O=()=>{x(!1)},E=()=>{x(!0)};D.useEffect(()=>{vs.setItem("chart-selector-expanded",String(c))},[c]);const N=()=>{l(S=>!S)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":c}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",c?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:c&&e.jsx(_n,{selectedChart:t,onChartChange:n})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(Qn,{selectedChart:t,onChartChange:n,isDropdownExpanded:c,onToggleDropdown:N})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:k||m}),children:e.jsx(_e.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(ca,{onEditJoins:E}),e.jsx(ia,{groupByFields:a,pivotByFields:r,metricsFields:o,sortByFields:d,activeField:i})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Ts,{open:u,onOpenChange:x,joinPlan:v,availableDataSources:C,onSave:A,onCancel:O,onRemove:B,children:e.jsx("div",{})})]})}function ua({initialFilters:t,availableFields:n}={}){const[a,r]=D.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:d}=s.useColumns(),c=n||o||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const N=p=>{if(p.id===E){const j=c[0]||l,S=s.getDataType(j.dataType)==="date";return{...p,conditions:[...p.conditions,{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}]}}return{...p,groups:p.groups.map(N)}};r(N(a))},x=E=>{const N=p=>{if(p.id===E){const j=c[0]||l,S=s.getDataType(j.dataType)==="date";return{...p,groups:[...p.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:j,operator:S?"between":"=",value:S?[]:""}],groups:[]}]}}return{...p,groups:p.groups.map(N)}};r(N(a))},h=(E,N)=>{const p=j=>j.id===E?{...j,conditions:j.conditions.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(p)};r(p(a))},g=(E,N)=>{const p=j=>j.id===E?{...j,groups:j.groups.filter(S=>S.id!==N)}:{...j,groups:j.groups.map(p)};r(p(a))},k=(E,N,p,j)=>{if(p==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const S=M=>M.id===E?{...M,conditions:M.conditions.map(y=>y.id===N?{...y,[p]:j}:y)}:{...M,groups:M.groups.map(S)};r(S(a))},m=(E,N,p)=>{const j=S=>S.id===E?{...S,conditions:S.conditions.map(M=>M.id===N?{...M,...p}:M)}:{...S,groups:S.groups.map(j)};r(j(a))},f=(E,N)=>{const p=j=>j.id===E?{...j,logicalOperator:N}:{...j,groups:j.groups.map(p)};r(p(a))},v=(E,N)=>{const p=j=>j.id===E?{...j,negate:N}:{...j,groups:j.groups.map(p)};r(p(a))},C=(E,N,p)=>{const j=S=>S.id===E?{...S,conditions:s.arrayMove(S.conditions,N,p)}:{...S,groups:S.groups.map(j)};r(j(a))},A=(E,N,p)=>{const j=S=>S.id===E?{...S,groups:s.arrayMove(S.groups,N,p)}:{...S,groups:S.groups.map(j)};r(j(a))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const N=j=>{let S="";typeof j.field=="object"?S=j.field.entityName?`${j.field.entityName}.${j.field.name}`:j.field.name:S=String(j.field);const M=j.operator;let y=j.value;if(j.field.dataType==="string"&&!["in","not in"].includes(j.operator))typeof y=="string"?y=`'${y}'`:Array.isArray(y)&&(y=`'${y.join(", ")}'`);else if(j.field.dataType==="date"||j.field.dataType==="datetime"||j.field.dataType==="timestamp")if(j.operator==="between"&&Array.isArray(y)&&y.length===2){const b=y[0]?`'${y[0]}'`:"NULL",I=y[1]?`'${y[1]}'`:"NULL";return`${S} BETWEEN ${b} AND ${I}`}else if((j.operator==="in"||j.operator==="not in")&&Array.isArray(y)){const b=y.map(I=>I?`'${I}'`:"NULL").join(", ");return`${S} ${M} (${b})`}else typeof y=="string"||y instanceof Date?y=`'${y}'`:Array.isArray(y)&&y.length>0&&(y=`'${y[0]}'`);else if(["in","not in"].includes(j.operator)){let b=[];Array.isArray(y)?b=y.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof y=="string"?b=y.split(",").map(I=>{const F=I.trim();return j.field.dataType==="string"?`'${F}'`:F}):typeof y=="number"&&(b=[String(y)]),y=`(${b.join(", ")})`}switch(M){case"contains":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"startsWith":return typeof y=="string"?`${S} LIKE '${y.replace(/'/g,"")}%'`:`${S} LIKE '${String(y)}%'`;case"endsWith":return typeof y=="string"?`${S} LIKE '%${y.replace(/'/g,"")}'`:`${S} LIKE '%${String(y)}'`;case"isNull":return`${S} IS NULL`;case"isNotNull":return`${S} IS NOT NULL`;default:return`${S} ${M} ${y}`}},p=j=>{const S=j.conditions.map(N),M=j.groups.map(F=>p(F)),y=[...S,...M].filter(Boolean);if(y.length===0)return"";const b=y.join(` ${j.logicalOperator} `),I=y.length>1?`(${b})`:b;return j.negate?`NOT ${I}`:I};return p(E)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:h,removeGroup:g,updateCondition:k,updateConditionFields:m,updateGroupOperator:f,updateGroupNegate:v,reorderConditions:C,reorderGroups:A,generateSQLPreview:B,hasAnyFilters:O}}function ma({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 xa=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function ha({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:o="w-64"}){const[d,i]=D.useState(!1),c=D.useMemo(()=>{const l={};return a.forEach(u=>{const x=xa(u);l[x]||(l[x]={}),l[x][u.entityId]||(l[x][u.entityId]=[]),l[x][u.entityId].push(u)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:d,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,className:s.cn("justify-between",!t&&"text-muted-foreground",o),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(ma,{children:[t.entityName,".",t.name]})}):r,e.jsx(dt,{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(c).map(([l,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"}),l]}),children:Object.entries(u).map(([x,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:[s.getEntityIcon(h[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:h[0].entityName})]}),h.map((g,k)=>e.jsxs(s.CommandItem,{value:g.id,onSelect:()=>{n(g),i(!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)===g.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:g.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:g.description&&e.jsx("span",{children:g.description})})]})]},g.id+k))]},`${l}-${x}`))},l))})]})})]})}function Xe(t){var f;const n=s.useEditorStore(v=>v.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),o=s.useEditorStore(v=>v.card.config),d=o==null?void 0:o.joinPlan,i={...t,alias:t.name,label:"value",role:"groupby"},c={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...i,role:"sortby",direction:"asc"},u={joinPlan:d,groupByColumns:[i],metricColumns:[c],sortByColumns:[l]},x=((f=n.dataSource)==null?void 0:f.connectionId)||n.connectionId,{data:h,isPending:g,error:k}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:x,cardConfig:u,cardDataSource:n.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:g,error:k}}function pa({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:o}){const[d,i]=qe.useState(!1),{filterValues:c}=Xe(t),l=x=>{a(n.filter(h=>h!==x))},u=x=>{n.includes(x)?a(n.filter(h=>h!==x)):a([...n,x])};return e.jsx("div",{className:s.cn("w-full",o),children:e.jsxs(s.Popover,{open:d,onOpenChange:i,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":d,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(x=>{const h=c.find(g=>g.value===x);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:g=>{g.key==="Enter"&&l(x)},onMouseDown:g=>{g.preventDefault(),g.stopPropagation()},onClick:g=>{g.stopPropagation(),l(x)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):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:c.map((x,h)=>e.jsxs(s.CommandItem,{onSelect:()=>u(x.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+h))})]})]})})]})})}function fa({field:t,value:n,onChange:a,placeholder:r="Select value...",className:o}){const{filterValues:d,isPending:i,error:c}=Xe(t);return i?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..."]}):c?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:d.map((l,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+u))})]})}function ga({value:t,operator:n,onChange:a,className:r}){var l;const{tokenProps:o}=s.useSemaphorContext(),d=(l=o==null?void 0:o.params)==null?void 0:l.timezone,i=D.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,x=t[1]?new Date(t[1]):void 0;if(u&&x)return{from:u,to:x}}}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]),x=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:x}}}},[t,n]),c=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const x=new Date(u.from);x.setHours(23,59,59,999),a([u.from.toISOString(),x.toISOString()])}else if(u.to){const x=new Date(u.to);x.setHours(0,0,0,0),a([x.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:i,onChange:c,timezone:d,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const ja=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],ba=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],va=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],ya=["=","!=","isNull","isNotNull"],Na=["between","isNull","isNotNull"],Ca={"=":"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","not between":"Not Between"};function ys(t){return Ca[t]||s.titleCase(t)}function Sa(t){switch(t){case"string":return ba;case"number":return va;case"boolean":return ya;case"date":return Na;default:return ja}}function Ys({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:d,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:l}){const{attributes:u,listeners:x,setNodeRef:h,transform:g,transition:k,isDragging:m}=s.useSortable({id:t.id}),{isPending:f,error:v}=Xe(t.field),C={transform:s.CSS.Transform.toString(g),transition:k};return e.jsxs("div",{ref:h,style:C,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${m?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...x,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:A=>i(a,A),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(ha,{value:t.field,onValueChange:A=>{const B=A,O=s.getDataType(B.dataType)==="date";l(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:A=>{A==="in"||A==="not in"?l(a,t.id,{operator:A,value:[]}):A==="isNull"||A==="isNotNull"?l(a,t.id,{operator:A,value:null}):l(a,t.id,{operator:A,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ys(t.operator):""})}),e.jsx(s.SelectContent,{children:Sa(s.getDataType(t.field.dataType)).map(A=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:A,children:ys(A)},A))})]}),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"?f?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..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(pa,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(A=>typeof A=="string")?t.value:[],onChange:A=>l(a,t.id,{value:A}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input,{value:typeof t.value=="string"?t.value:"",onChange:A=>l(a,t.id,{value:A.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(fa,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:A=>l(a,t.id,{value:A}),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:A=>l(a,t.id,{value:A==="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(ga,{value:t.value,operator:t.operator,onChange:A=>l(a,t.id,{value:A}),className:"flex-1"}):e.jsx(s.Input,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:A=>o(a,t.id,"value",A.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:()=>d(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function wa({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:d,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:l,onReorderConditions:u,onReorderGroups:x,onAddCondition:h,onAddGroup:g,availableFields:k,renderFilterGroup:m,updateConditionFields:f}){const{attributes:v,listeners:C,setNodeRef:A,transform:B,transition:O,isDragging:E}=s.useSortable({id:t.id}),N={transform:s.CSS.Transform.toString(B),transition:O},p=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id){const b=t.conditions.findIndex(F=>F.id===M.id),I=t.conditions.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&u(t.id,b,I)}},j=S=>{const{active:M,over:y}=S;if(y&&M.id!==y.id&&a){const b=t.groups.findIndex(F=>F.id===M.id),I=t.groups.findIndex(F=>F.id===y.id);b!==-1&&I!==-1&&x(a,b,I)}};return e.jsxs("div",{ref:A,style:N,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${E?"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",{...v,...C,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:S=>r(t.id,S),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&&d(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:p,children:e.jsx(s.SortableContext,{items:t.conditions.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((S,M)=>e.jsx(Ys,{condition:S,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:k,updateConditionFields:f},S.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:j,children:e.jsx(s.SortableContext,{items:t.groups.map(S=>S.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(S=>m(S,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:()=>g(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function ka({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:o}){const{currentFilters:d,availableFields:i,isLoading:c,addCondition:l,addGroup:u,removeCondition:x,removeGroup:h,updateCondition:g,updateConditionFields:k,updateGroupOperator:m,updateGroupNegate:f,reorderConditions:v,reorderGroups:C,generateSQLPreview:A,hasAnyFilters:B,setCurrentFilters:O}=ua({initialFilters:t,availableFields:n}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[N,p]=D.useState(!1),j=(y,b,I)=>{const F=T=>T.id===y?{...T,conditions:T.conditions.map(L=>L.id===b?{...L,field:I,dataType:I.dataType}:L)}:{...T,groups:T.groups.map(F)};O(F(d))},S=(y,b=0,I)=>b===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const w=y.conditions.findIndex(K=>K.id===T.id),R=y.conditions.findIndex(K=>K.id===L.id);w!==-1&&R!==-1&&v(y.id,w,R)}},children:e.jsx(s.SortableContext,{items:y.conditions.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.conditions.map((F,T)=>e.jsx(Ys,{condition:F,index:T,groupId:y.id,groupLogicalOperator:y.logicalOperator,onUpdateCondition:g,onUpdateField:j,onRemoveCondition:x,onUpdateGroupOperator:m,availableFields:i,updateConditionFields:k},F.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:F=>{const{active:T,over:L}=F;if(L&&T.id!==L.id){const w=y.groups.findIndex(K=>K.id===T.id),R=y.groups.findIndex(K=>K.id===L.id);w!==-1&&R!==-1&&C(y.id,w,R)}},children:e.jsx(s.SortableContext,{items:y.groups.map(F=>F.id),strategy:s.verticalListSortingStrategy,children:y.groups.map(F=>S(F,b+1,y.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:()=>l(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),N&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(y.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},y.id):e.jsx(wa,{group:y,depth:b,parentGroupId:I,onUpdateGroupOperator:m,onUpdateGroupNegate:f,onRemoveGroup:h,onUpdateCondition:g,onUpdateField:j,onRemoveCondition:x,onReorderConditions:v,onReorderGroups:C,onAddCondition:l,onAddGroup:u,availableFields:i,renderFilterGroup:S,updateConditionFields:k},y.id),M=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:[c?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..."})]}):S(d),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.SmallSwitch,{id:"advanced-mode",checked:N,onCheckedChange:y=>p(y)}),e.jsx(s.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)"})]})}),B&&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:A(d)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(B?d:null),children:"Apply Filters"})]})]})}function Ta({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:o,isOpen:d,onOpenChange:i}){const c=u=>{a(t,u),i(!1)},l=()=>{r(t),i(!1)};return e.jsxs(s.Dialog,{modal:!1,open:d,onOpenChange:i,children:[d&&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(ka,{filters:n,availableFields:o,onSave:c,onCancel:()=>i(!1),onClearAll:l})]})]})}function Ea({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var v,C;const[o,d]=D.useState(null),i=s.useEditorStore(A=>A.card),c=s.useEditorStore(A=>A.actions.updateCardConfig),l=(v=i==null?void 0:i.config)==null?void 0:v.joinPlan,u=(C=i==null?void 0:i.dataSource)==null?void 0:C.semanticDomainId,{data:x}=s.useJoinabilityMap(u),h=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],g=D.useCallback(A=>A.startsWith("card-")?null:A.startsWith("source-")||n.find(B=>B.id===A)?"source":a("groupBy").find(B=>B.id===A)?"groupBy":a("metrics").find(B=>B.id===A)?"metrics":a("pivotBy").find(B=>B.id===A)?"pivotBy":a("sortBy").find(B=>B.id===A)?"sortBy":null,[n,a]),k=D.useCallback(A=>{d(A.active.id)},[]),m=D.useCallback(A=>{var S;const{active:B,over:O}=A;if(!O||!t){d(null);return}const E=B.id,N=O.id,p=g(E),j=g(N)||N;if(j==="sortBy"){if(p==="source"){const M=n.find(b=>b.id===E);if(!M){d(null);return}if(!(a("groupBy").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName)||a("metrics").some(b=>b.name===M.name&&b.qualifiedEntityName===M.qualifiedEntityName))){d(null);return}}else if(p==="pivotBy"){d(null);return}else if(p!=="groupBy"&&p!=="metrics"&&p!=="sortBy"){d(null);return}}if(p==="source"&&j==="sortBy"){const M=[...n].find(F=>F.id===E);if(!M){d(null);return}const y=a("sortBy");if(s.fieldAlreadyExists(M,y)){d(null);return}const b=s.validateFieldForChartType(M,"sortBy",i.type);if(!b.isValid){s.ue.error("Invalid Field Type",{description:b.reason,position:"top-center",duration:3e3}),d(null);return}const I=s.getNewField(M,"sortBy",y);d(null),r("sortBy",[...y,I]);return}if(p==="source"&&j!=="source"&&j!=="sortBy"){const M=[...n].find(L=>L.id===E);if(!M){d(null);return}const y=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(y.length>0){const L=y[0].qualifiedEntityName;if(!L){d(null);return}if(L!==M.qualifiedEntityName&&M.qualifiedEntityName)if(u&&(x!=null&&x.joinabilityMap)){if(s.calculateFieldState(M,{joinabilityMap:x.joinabilityMap,selectedFields:y,baseEntityName:(S=l==null?void 0:l.baseEntity)==null?void 0:S.name}).state==="unreachable"){s.showJoinRequiredNotification(),d(null);return}}else{if(!l){s.showJoinRequiredNotification(),d(null);return}if(!s.areEntitiesJoined(L,M.qualifiedEntityName,l)){s.showJoinRequiredNotification(),d(null);return}}}const b=a(j);if(s.fieldAlreadyExists(M,b)){d(null);return}const I=s.validateFieldForChartType(M,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(M,j,b),T=[...b,F];d(null),r(j,T),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,T);return}if(p&&j&&p!=="source"&&j!=="source"&&p!==j){const M=a(p),y=a(j),b=M.find(w=>w.id===E);if(!b){d(null);return}const I=s.validateFieldForChartType(b,j,i.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),d(null);return}const F=s.getNewField(b,j,y);if(d(null),j==="sortBy"){s.fieldAlreadyExists(b,y)||r(j,[...y,F]);return}const T=M.filter(w=>w.id!==E),L=[...y,F];r(p,T),r(j,L),j==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(i.type,i.config,c,t,L);return}if(p&&j&&p===j&&p!=="source"){const M=a(p),y=M.findIndex(I=>I.id===E),b=M.findIndex(I=>I.id===N);if(y!==b){const I=s.arrayMove(M,y,b);r(p,I)}}d(null)},[t,n,a,r,g,l,u,x,i.type,c,i.config]),f=o?h.find(A=>A.id===o):null;return{activeId:o,activeField:f,handleDragStart:k,handleDragEnd:m}}function Aa({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(l=>l.card),{config:o}=D.useContext(s.SemaphorContext).tokenProps,d=(o==null?void 0:o.showInfoTab)!==!1,{errorMessage:i}=s.useDashboardCardQuery(r),c=()=>a?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:l=>n(l),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),c()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&d&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",i&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:i?"Error":"Info"})]})})}const Ia=[{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 Da(){var l,u;const t=s.useEditorStore(x=>x.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=D.useState(!1),[o,d]=D.useState(""),i=x=>{if(x==="custom"){r(!0);return}r(!1),n(t.id,parseInt(x))},c=x=>{const h=x.target.value;d(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$1,{type:"number",value:o,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:u.toString())||"100",onValueChange:i,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:Ia.map(x=>e.jsx(s.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Ma({card:t,queryData:n,isLoading:a,isFetching:r,pagination:o,onPaginationChange:d,onSortChange:i,sortState:c,splitViewEnabled:l}){const u=D.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ue,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(Ue,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:o,onPaginationChange:d,isLoading:a||r,onSortChange:i,sortState:c})})})]})}const La="semaphor-split-view-enabled";function Fa(){return Ve(La,!0)}function Ba({isOpen:t,onClose:n}){const a=rt.useClickOutside(n,{enabled:t}),r=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.url)||""}),o=s.useEditorStore(x=>x.card),d=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.pluginChartType)||""}),i=s.useEditorStore(x=>{var h;return((h=x.card.customCardPreferences)==null?void 0:h.settings)||{}}),{data:c}=s.useDashboardCardQuery(o),{getCard:l}=s.useCustomVisual(r),u=D.useMemo(()=>!r||r.trim()===""?null:l("Chart Settings"),[l,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(D.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(c==null?void 0:c.records)||[],chartType:d,settings:i})})})]})})}function Oa({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:o,activeCard:d,columns:i,columnsLoading:c,columnsError:l}){var J,ne,le;const u=s.useEditorStore(Z=>Z.card),x=s.useDashboardStore(Z=>Z.filterValues),h=s.useDashboardStore(Z=>Z.selectedSheetId),g=s.useDashboardStore(Z=>Z.inlineFilterValuesMap[(d==null?void 0:d.id)||""]),{updateCardConfig:k,setCard:m,updateCardInFrame:f,setShowAIDialog:v}=s.useEditorActions(),C=s.useEditorStore(Z=>Z.showAIDialog),A=s.useDashboardStore(Z=>Z.isVisualEditing),[B,O]=D.useState(!1),[E,N]=D.useState(!1),[p,j]=D.useState(null),{config:S}=D.useContext(s.SemaphorContext).tokenProps,M=(S==null?void 0:S.showInfoTab)!==!1,[y,b]=Fa(),I=s.useEditorStore(Z=>{var oe;return((oe=Z.card.customCardPreferences)==null?void 0:oe.url)&&Z.card.type==="custom"}),{data:F,errorMessage:T,isLoading:L,isFetching:w,errorSql:R,pagination:K,refetch:_,comparisonMetadata:G}=s.useDashboardCardQuery(d),q=D.useMemo(()=>(F==null?void 0:F.records)||[],[F==null?void 0:F.records]),[V,z]=D.useState(!1);D.useEffect(()=>{w||z(!1)},[w]);const H=()=>{const Z=!y;Z&&t==="table"&&n("chart"),b(Z)},P=(Z,oe)=>{const $={...d,paginationConfig:{page:Z+1,pageSize:oe}};m($),f($)};function W(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",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(u.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(x||{},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(d.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",i.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:c?"Loading...":l?"Error loading columns":JSON.stringify(i.slice(0,5),null,2)})]})]})]})}const Y=Z=>{if(!u.config)return;const oe=s.sortStateToSortByColumns(Z,u.config.metricColumns,u.config.groupByColumns);k(u.id,{...u.config,sortByColumns:oe})},ee=D.useMemo(()=>{var Z;return s.sortByColumnsToSortState((Z=u.config)==null?void 0:Z.sortByColumns)},[(J=u.config)==null?void 0:J.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":C&&A}),children:[a&&W(),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"&&C&&e.jsx(Ms,{variant:"outline"}),e.jsx(Aa,{activeView:t,onViewChange:n,splitViewEnabled:y}),e.jsx(s.FilterInfo,{cardId:d.id,cardFilters:(ne=d.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((le=d.config)==null?void 0:le.filters)||null),onFiltersClick:o,inlineFilters:d.inlineFilters,inlineFilterValues:g,sheetId:h||""}),G&&e.jsx(s.ComparisonMetadataBadge,{metadata:G,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Da,{})}),C&&e.jsx(_e.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:L||w,onClick:()=>{z(!0),_()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:y?"Hide Results Table":"Show Results Table",onClick:H,children:y?e.jsx(ht,{className:"size-4"}):e.jsx(Et,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(Ls,{})}),!C&&e.jsx(s.IconButton,{onClick:()=>v(!C),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!B&&I&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>O(!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 min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":y&&!["table","pivotTable","aggregateTable"].includes(d.type)}),children:e.jsx(Ma,{card:d,queryData:F,isLoading:L,isFetching:w,pagination:K,onPaginationChange:P,onSortChange:Y,sortState:ee,splitViewEnabled:y})}),t==="table"&&(F==null?void 0:F.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:d,data:q,paginationMetadata:K,onPaginationChange:P,isLoading:L||w,onSortChange:Y,sortState:ee})}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:T?e.jsx(Je,{error:T,errorSql:R,onSendFeedback:()=>{const Z=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:d.dataSource,dashboardFilters:x,errorMessage:T,errorSql:R,generatedSql:F==null?void 0:F.sql});j(Z),N(!0)},onOpenInEditor:()=>{v(!0),setTimeout(()=>{const Z=s.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(R||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):e.jsx(As,{sql:F==null?void 0:F.sql,error:T,errorSql:R})})})]}),e.jsx(Ba,{isOpen:B,onClose:()=>O(!1)}),p&&e.jsx(s.FeedbackDialog,{open:E,onOpenChange:N,feedbackData:p})]})]})}function Ra({activeField:t}){const[n,a]=D.useState(!0);return D.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(We,{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 Pa=()=>{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 Va({column:t,isSelected:n,onSelect:a,availableFields:r,width:o,onWidthChange:d}){var K,_,G;const i=s.useEditorStore(q=>q.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:u,updateFilters:x}=s.useEditorActions(),[h,g]=D.useState(!1),[k,m]=D.useState(!1),f=D.useRef(null),v=D.useCallback(q=>{q.preventDefault(),q.stopPropagation(),m(!0),f.current={startX:q.clientX,startWidth:o||150};const V=H=>{if(!f.current)return;const P=H.clientX-f.current.startX,W=Math.max(80,f.current.startWidth+P);d==null||d(t.id,W)},z=()=>{m(!1),f.current=null,document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",z)};document.addEventListener("mousemove",V),document.addEventListener("mouseup",z)},[o,t.id,d]),C=(K=i==null?void 0:i.config)==null?void 0:K.filters,A=(_=C==null?void 0:C.conditions)==null?void 0:_.some(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName),B=q=>{q?x(i.id,q):c(i.id,{filters:void 0})},{attributes:O,listeners:E,setNodeRef:N,transform:p,transition:j,isDragging:S}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(p),transition:j},y=s.getDataType(t.dataType),b=za(y),I=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"asc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.sortByColumns)||[],V=q.findIndex(H=>H.name===t.name);if(V!==-1){const H=[...q];H[V]={...H[V],direction:"desc"},c(i.id,{sortByColumns:H})}else c(i.id,{sortByColumns:[...q,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},T=()=>{var z;const q=((z=i==null?void 0:i.config)==null?void 0:z.groupByColumns)||[];if(!q.some(H=>H.name===t.name)){const H={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...q,H]})}},L=q=>{var H;const V=((H=i==null?void 0:i.config)==null?void 0:H.metricColumns)||[];if(!V.some(P=>P.name===t.name&&P.aggregate===q)){const P={...t,id:`metric-${t.id}-${q}-${Date.now()}`,label:`${q} of ${t.label||t.name}`,role:"metric",aggregate:q};c(i.id,{metricColumns:[...V,P]})}},w=()=>{t.role==="groupby"?l(i.id,t.id):t.role==="metric"&&u(i.id,t.id)},R={...M,width:o?`${o}px`:void 0,minWidth:o?`${o}px`:"120px"};return e.jsxs("th",{ref:N,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",S&&"opacity-50",n&&"bg-primary/10",k&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...E,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(b,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),A&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>g(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",A&&"text-primary")}),A?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:I,children:[e.jsx(it,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:F,children:[e.jsx(ot,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>L("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>L("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:T,children:[e.jsx(He,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ss,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:w,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:v,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",k&&"bg-primary")}),e.jsx(Js,{open:h,onOpenChange:g,availableFields:r.length>0?r:[t],existingFilters:C,editingCondition:A?(G=C==null?void 0:C.conditions)==null?void 0:G.find(q=>q.field.name===t.name&&q.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function za(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function $a({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var j,S,M,y;const o=s.useEditorStore(b=>b.card),{updateCardConfig:d}=s.useEditorActions(),[i,c]=D.useState(null),[l,u]=D.useState({}),[x,h]=D.useState(!1),g=D.useMemo(()=>{var F,T;const b=((F=o==null?void 0:o.config)==null?void 0:F.groupByColumns)||[],I=((T=o==null?void 0:o.config)==null?void 0:T.metricColumns)||[];return[...b,...I]},[(j=o==null?void 0:o.config)==null?void 0:j.groupByColumns,(S=o==null?void 0:o.config)==null?void 0:S.metricColumns]),k=D.useMemo(()=>{const b=new Set(g.map(I=>`${I.qualifiedEntityName}.${I.name}`));return r.filter(I=>!b.has(`${I.qualifiedEntityName}.${I.name}`))},[r,g]),{data:m,isLoading:f}=s.useDashboardCardQuery(o),v=(m==null?void 0:m.records)||[],C=D.useCallback((b,I)=>{u(F=>({...F,[b]:I}))},[]),A=D.useCallback(b=>{var L,w;const I=s.getDataType(b.dataType),F=((L=o==null?void 0:o.config)==null?void 0:L.groupByColumns)||[],T=((w=o==null?void 0:o.config)==null?void 0:w.metricColumns)||[];if(I==="number"){const R={...b,id:`metric-${b.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};d(o.id,{metricColumns:[...T,R]})}else{const R={...b,id:`groupby-${b.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...F,R]})}h(!1)},[(M=o==null?void 0:o.config)==null?void 0:M.groupByColumns,(y=o==null?void 0:o.config)==null?void 0:y.metricColumns,o.id,d]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=b=>{c(b.active.id)},E=b=>{const{active:I,over:F}=b;if(c(null),!F||I.id===F.id)return;const T=g.findIndex(w=>w.id===I.id),L=g.findIndex(w=>w.id===F.id);if(T!==-1&&L!==-1){const w=s.arrayMove(g,T,L),R=w.filter(_=>_.role==="groupby"),K=w.filter(_=>_.role==="metric");d(o.id,{groupByColumns:R,metricColumns:K})}},N=i?g.find(b=>b.id===i):null,p=b=>{let I="";for(;b>=0;)I=String.fromCharCode(b%26+65)+I,b=Math.floor(b/26)-1;return I};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):g.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:B,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:E,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:g.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:g.map((b,I)=>e.jsx("th",{style:{width:l[b.id]?`${l[b.id]}px`:void 0,minWidth:l[b.id]?`${l[b.id]}px`:"120px"},className:"border-r border-border bg-muted/30 px-2 py-1 text-center text-xs font-medium text-muted-foreground",children:p(I)},`letter-${b.id}`))}),e.jsx("th",{className:"w-10 border-r border-border bg-muted/30 px-2 py-1"})]}),e.jsxs("tr",{className:"border-b-2 border-border bg-background",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:"#"}),e.jsx(s.SortableContext,{items:g.map(b=>b.id),strategy:s.horizontalListSortingStrategy,children:g.map(b=>e.jsx(Va,{column:b,isSelected:(t==null?void 0:t.id)===b.id,onSelect:()=>n(b),availableFields:r,width:l[b.id],onWidthChange:C},b.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:x,onOpenChange:h,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:k.map(b=>{const I=s.getDataType(b.dataType),F=I==="number"?s.Hash:I==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:b.label||b.name,onSelect:()=>A(b),children:[e.jsx(F,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm",children:b.label||b.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:b.entityName})]})]},b.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:g.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):v.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:g.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):v.slice(0,100).map((b,I)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",I%2===0?"bg-background":"bg-muted/20"),children:[e.jsx("td",{className:"sticky left-0 z-10 w-12 border-r border-border bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground",children:I+1}),g.map(F=>{const T=b[F.name]??b[F.label??""];return e.jsx("td",{style:{width:l[F.id]?`${l[F.id]}px`:void 0,minWidth:l[F.id]?`${l[F.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===F.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Ka(T,F)})},`${I}-${F.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},I))})]}),e.jsx(s.DragOverlay,{children:N&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:N.label||N.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(v.length,100)," of ",v.length," rows"]}),e.jsxs("span",{children:[g.length," columns"]})]})]})}function Ka(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function Ga({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(E=>E.card),{updateCardConfig:r,removeGroupByColumn:o,removeMetricColumn:d}=s.useEditorActions(),[i,c]=D.useState(!0),[l,u]=D.useState(""),[x,h]=D.useState(new Set),g=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],k=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],m=E=>{const N=new Set(x);N.has(E)?N.delete(E):N.add(E),h(N)},f=E=>g.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName)||k.some(N=>N.name===E.name&&N.qualifiedEntityName===E.qualifiedEntityName),v=(E,N)=>{if(N)if(s.getDataType(E.dataType)==="number"){const j={...E,id:`metric-${E.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...k,j]})}else{const j={...E,id:`groupby-${E.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...g,j]})}else{const p=g.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName),j=k.findIndex(S=>S.name===E.name&&S.qualifiedEntityName===E.qualifiedEntityName);p!==-1&&o(a.id,g[p].id),j!==-1&&d(a.id,k[j].id)}},C=E=>{if(!l)return E;const N=l.toLowerCase();return E.filter(p=>p.name.toLowerCase().includes(N)||p.label&&p.label.toLowerCase().includes(N))},A=E=>{switch(s.getDataType(E)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(wt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search columns...",value:l,onChange:E=>u(E.target.value),className:"h-8 pl-8 text-sm"})]})}),(g.length>0||k.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[g.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(He,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsx("span",{children:"Groupings"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:g.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:g.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>o(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]}),k.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:k.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:k.map(E=>{const N=A(E.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(N,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:E.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,E.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},E.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(E=>{const N=C(E.columns);if(N.length===0)return null;const p=x.has(E.entityId)||l.length>0;return e.jsxs(s.Collapsible,{open:p,onOpenChange:()=>m(E.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",p&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:E.label||E.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:N.map(j=>{const S=A(j.dataType),M=f(j);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:y=>v(j,y),className:"h-3.5 w-3.5"}),e.jsx(S,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:j.label||j.name})]},j.id)})})})]},E.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(kt,{className:"h-4 w-4"})})})}const qa=[{name:"SUM",description:"Sum of values",syntax:"SUM([column])"},{name:"AVG",description:"Average of values",syntax:"AVG([column])"},{name:"COUNT",description:"Count of rows",syntax:"COUNT([column])"},{name:"COUNTD",description:"Count distinct values",syntax:"COUNTD([column])"},{name:"MIN",description:"Minimum value",syntax:"MIN([column])"},{name:"MAX",description:"Maximum value",syntax:"MAX([column])"},{name:"IF",description:"Conditional logic",syntax:"IF(condition, then, else)"},{name:"CASE",description:"Multiple conditions",syntax:"CASE WHEN ... THEN ... END"},{name:"CONCAT",description:"Concatenate text",syntax:"CONCAT([col1], [col2])"},{name:"ROUND",description:"Round number",syntax:"ROUND([column], decimals)"},{name:"FLOOR",description:"Round down",syntax:"FLOOR([column])"},{name:"CEIL",description:"Round up",syntax:"CEIL([column])"},{name:"ABS",description:"Absolute value",syntax:"ABS([column])"},{name:"DATEPART",description:"Extract date part",syntax:"DATEPART(year, [date])"},{name:"DATEDIFF",description:"Difference between dates",syntax:"DATEDIFF(day, [date1], [date2])"}];function Ua({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:o,availableColumns:d}){const[i,c]=D.useState(!1),[l,u]=D.useState("column"),x=D.useRef(null);D.useEffect(()=>{const m=f=>{f.key==="Escape"&&t?r():f.key==="Enter"&&t&&!i&&a(t)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,r,a,i]);const h=m=>{const f=`[${m.label||m.name}]`,v=x.current;if(v){const C=v.selectionStart||0,A=v.selectionEnd||0,B=t.slice(0,C)+f+t.slice(A);n(B),setTimeout(()=>{v.setSelectionRange(C+f.length,C+f.length),v.focus()},0)}else n(t+f);c(!1)},g=m=>{const f=x.current;if(f){const v=f.selectionStart||0,C=f.selectionEnd||0,A=t.slice(0,v)+m.syntax+t.slice(C);n(A),setTimeout(()=>{f.setSelectionRange(v+m.name.length+1,v+m.syntax.length-1),f.focus()},0)}else n(t+m.syntax);c(!1)},k=m=>{switch(s.getDataType(m)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:o?e.jsx("span",{className:"truncate",children:o.label||o.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:i&&l==="function",onOpenChange:m=>{c(m),m&&u("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Tt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:qa.map(m=>e.jsx(s.CommandItem,{value:m.name,onSelect:()=>g(m),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-medium",children:m.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:m.syntax})]})},m.name))})]})]})})]}),e.jsxs(s.Popover,{open:i&&l==="column",onOpenChange:m=>{c(m),m&&u("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:d.map(m=>{const f=k(m.dataType);return e.jsxs(s.CommandItem,{value:m.label||m.name,onSelect:()=>h(m),children:[e.jsx(f,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:m.label||m.name})]},m.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input$1,{ref:x,value:t,onChange:m=>n(m.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function _a({className:t}){var g,k,m,f;const n=s.useEditorStore(v=>v.card),[a,r]=D.useState(null),[o,d]=D.useState(""),{columns:i=[],columnGroups:c=[],isLoading:l}=s.useColumns();(g=n==null?void 0:n.config)!=null&&g.groupByColumns,(k=n==null?void 0:n.config)!=null&&k.metricColumns,(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(f=n==null?void 0:n.config)!=null&&f.pivotByColumns;const u=v=>{r(v),d(v?`[${v.label||v.name}]`:"")},x=v=>{console.log("Formula submitted:",v),d(""),r(null)},h=()=>{d(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(Ua,{value:o,onChange:d,onSubmit:x,onCancel:h,selectedColumn:a,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx($a,{selectedColumn:a,onColumnSelect:u,isLoading:l,sourceFields:i})}),e.jsx(Ga,{entityGroups:c,isLoading:l})]})]})}function Ha(){var K,_;const[t,n]=D.useState("chart"),[a,r]=D.useState(!1),[o,d]=D.useState(!1),[i,c]=D.useState(!0),l=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:x}=s.useEditorActions(),h=s.useEditorStore(G=>G.card.type);D.useEffect(()=>Pa(),[]);const g=G=>{x(G)},k=s.useEditorStore(G=>G.frame),m=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:f,removeCard:v,updateCard:C,setActiveCard:A,updateFilters:B}=s.useEditorActions(),{columns:O=[],isLoading:E,error:N}=s.useColumns(),p=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),j=m,{getFieldsForContainer:S,setFieldsForContainer:M}=s.useFieldManagement(j),{activeField:y,handleDragStart:b,handleDragEnd:I}=Ea({activeCardId:k.activeCardId,sourceFields:O,getFieldsForContainer:S,setFieldsForContainer:M}),F=(G,q)=>{q&&B(G,q)},T=G=>{var q;C(G,{config:{...(q=k.cards.find(V=>V.id===G))==null?void 0:q.config,filters:void 0}})},L=O,w=G=>{if(!G)return 0;let q=G.conditions.length;return G.groups.forEach(V=>{q+=w(V)}),q},R=w(((K=j==null?void 0:j.config)==null?void 0:K.filters)||null);return e.jsxs(s.DndContext,{sensors:p,collisionDetection:s.closestCenter,onDragStart:b,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Es,{isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:h==="tableBuilder"?e.jsx(_a,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(da,{selectedChart:h,onChartChange:g,groupByFields:S("groupBy"),pivotByFields:S("pivotBy"),metricsFields:S("metrics"),sortByFields:S("sortBy"),activeField:y}),e.jsx(Oa,{selectedChart:h,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>d(!0),filterCount:R,activeCard:j,dataSourceState:m.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:E,columnsError:N,getFieldsForContainer:S,cards:k.cards,activeCardId:k.activeCardId,addCard:f,setActiveCard:A})]})}),!i&&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:()=>c(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),j&&e.jsx(Ta,{cardId:j.id,filters:((_=j.config)==null?void 0:_.filters)||null,onFiltersChange:F,onClearFilters:T,availableFields:L,isOpen:o,onOpenChange:d}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Ra,{activeField:y||null})})]})}function Ja({authToken:t,onSave:n,onClose:a}){const r=D.useRef(null),o=s.useEditorStore(N=>N.showAIDialog),d=s.useEditorStore(N=>N.isDevMode),i=s.useAssistantLayoutStore(N=>N.setFullscreen),c=s.useAssistantLayoutStore(N=>N.setPanelOpen),l=s.useAssistantLayoutStore(N=>N.setContainer),u=s.useAssistantPanel("editor"),x=s.useFullscreenAssistant(),h=s.useAssistantContainer("editor"),g=x==="editor",k=D.useCallback(N=>{l("editor",N)},[l]),{setAuthToken:m}=s.useDashboardActions(),{setShowAIDialog:f,setOnSave:v,setOnClose:C}=s.useEditorActions(),{setActiveAssistantType:A}=s.useAIActions();D.useEffect(()=>{n&&v(n),a&&C(a)},[n,v,a,C]),D.useEffect(()=>{t&&t.accessToken&&m(t)},[t,m]),D.useEffect(()=>{var N,p;o?((N=r.current)==null||N.resize(40),c("editor",!0),A("editor")):((p=r.current)==null||p.resize(0),c("editor",!1),x==="editor"&&i(null),A(null))},[o,c,A,i,x]);function B(N){N<1?(f(!1),c("editor",!1),x==="editor"&&i(null),A(null)):(o||(f(!0),A("editor")),u.isOpen||c("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(Es,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx($n,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:g,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!g&&"pointer-events-none")})]})]})}function E(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",g&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Ha,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(ps,{isFullscreen:g,onFullscreenChange:N=>i(N?"editor":null),fullscreenContainer:h})})})]}),e.jsx("div",{ref:k,className:s.cn("absolute inset-0",!g&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):E()})}function Qa(){s.useDashboardStore(i=>i.selectedCardId);const t=s.useDashboardStore(i=>i.selectedSheetId),{setIsVisualEditing:n}=s.useDashboardStore(i=>i.actions),a=s.useDashboardStore(i=>i.isVisualEditing),r=s.useDashboardStore(i=>i.actions.updateFrame);function o(i){t&&(r(t,i),n(!1))}function d(){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(Ja,{onSave:o,onClose:d})})}exports.default=Qa;