react-semaphor 0.1.285 → 0.1.287

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 (31) hide show
  1. package/dist/chunks/{dashboard-controls-DSwmmI8w.js → dashboard-controls-B8xnCPTZ.js} +318 -341
  2. package/dist/chunks/{dashboard-controls-B8f_BKTb.js → dashboard-controls-C25JMBLV.js} +4 -4
  3. package/dist/chunks/dashboard-filter-controls-button-BOJUiKGk.js +11 -0
  4. package/dist/chunks/{dashboard-filter-controls-button-BqmNXVoa.js → dashboard-filter-controls-button-D-o6ofi2.js} +476 -442
  5. package/dist/chunks/{dashboard-json-D0H5w5WI.js → dashboard-json-BYCWtm_z.js} +1 -1
  6. package/dist/chunks/{dashboard-json-qT21EDMm.js → dashboard-json-DFuRB4cG.js} +1 -1
  7. package/dist/chunks/{dashboard-summary-settings-dialog-BRI5dAfz.js → dashboard-summary-settings-dialog-CFTJNcmp.js} +1 -1
  8. package/dist/chunks/{dashboard-summary-settings-dialog-Mq8T35Qv.js → dashboard-summary-settings-dialog-CsnHeIhi.js} +1 -1
  9. package/dist/chunks/{edit-dashboard-visual-DLpQykTX.js → edit-dashboard-visual-DU3NzdD5.js} +2 -2
  10. package/dist/chunks/{edit-dashboard-visual-gSIS7RGI.js → edit-dashboard-visual-YmESbDUP.js} +4 -4
  11. package/dist/chunks/{index-Celt_oJr.js → index-BDE8cMG8.js} +170 -170
  12. package/dist/chunks/{index-r_DA-pny.js → index-Bz0-3JKw.js} +10194 -10218
  13. package/dist/chunks/resource-management-panel-C6qnO0ID.js +6 -0
  14. package/dist/chunks/resource-management-panel-Lxjcn4i0.js +933 -0
  15. package/dist/chunks/use-create-flow-overlay-state-AXNDXDqV.js +21 -0
  16. package/dist/chunks/{use-create-flow-overlay-state-C1xhazfY.js → use-create-flow-overlay-state-CJiyn4FY.js} +142 -145
  17. package/dist/chunks/{use-visual-utils-CWcTBBvd.js → use-visual-utils-BygqTxyR.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-CqL5PNOR.js → use-visual-utils-CWVz-eYg.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/style.css +1 -1
  24. package/dist/surfboard/index.cjs +1 -1
  25. package/dist/surfboard/index.js +2 -2
  26. package/dist/types/main.d.ts +18 -2
  27. package/package.json +1 -1
  28. package/dist/chunks/dashboard-filter-controls-button-DXKJ-0iV.js +0 -11
  29. package/dist/chunks/resource-management-panel-Brj3iNyX.js +0 -6
  30. package/dist/chunks/resource-management-panel-DXLca9OX.js +0 -920
  31. package/dist/chunks/use-create-flow-overlay-state-DVyd9L7O.js +0 -21
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-Celt_oJr.js"),N=require("react"),it=require("./use-visual-utils-CWcTBBvd.js"),De=require("./use-create-flow-overlay-state-DVyd9L7O.js"),cn=require("react-dom");function dn(s){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const a in s)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(s,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}return n.default=s,Object.freeze(n)}const Pt=dn(N);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-BDE8cMG8.js"),N=require("react"),it=require("./use-visual-utils-BygqTxyR.js"),De=require("./use-create-flow-overlay-state-AXNDXDqV.js"),cn=require("react-dom");function dn(s){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const a in s)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(s,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>s[a]})}}return n.default=s,Object.freeze(n)}const Pt=dn(N);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -190,4 +190,4 @@ ${r}`].filter(Boolean).join(`
190
190
 
191
191
  `;o(u)}:void 0}}function Ra({className:s,...n}){var pe,X,Z,ue,Fe;const a=t.useEditorStore(te=>te.card);t.useEditorStore(te=>te.isDevMode);const r=((pe=a.customCardPreferences)==null?void 0:pe.showCardHeader)??!0,d=((Z=(X=a.preferences)==null?void 0:X.displayOptions)==null?void 0:Z.showInlineFilterBar)??!0,i=t.useEditorStore(te=>te.frame),o=t.useEditorStore(te=>te.inlineFilterValuesMap[a.id]),c=t.useDashboardStore(te=>te.dashboard.filters),l=t.useDashboardStore(te=>te.selectedSheetId),[u,p]=N.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:h}=N.useContext(t.SemaphorContext),m=t.useEditorStore(te=>te.actions.setRunSql),g=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),v=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),{updateFilter:b}=t.useDashboardActions(),S=c==null?void 0:c.find(te=>te.id===i.filterId),E=N.useMemo(()=>t.findCustomVisualConfigCard(i,a),[i,a]),{manifest:B}=t.useCustomVisual(((ue=E==null?void 0:E.customCardPreferences)==null?void 0:ue.url)||""),C=N.useMemo(()=>{var te;return(te=B==null?void 0:B.visuals)==null?void 0:te.find(ge=>{var ye;return ge.name===((ye=E==null?void 0:E.customCardPreferences)==null?void 0:ye.componentName)})},[B,(Fe=E==null?void 0:E.customCardPreferences)==null?void 0:Fe.componentName]),A=t.resolveMultiInputType(E,C),T=N.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:E,isMultiInputVisual:A==="multiple"}),[i,E,A]),D=N.useMemo(()=>{const te=T.findIndex(ge=>(ge==null?void 0:ge.id)===(a==null?void 0:a.id));return te<0?-1:t.getSlotIndexForCard(a,te)},[T,a]),I=N.useMemo(()=>!E||A!=="multiple"||D<0?a.type:t.getEffectiveCardTypeForSlot(a,D,C==null?void 0:C.slots)??a.type,[E,A,D,a,C==null?void 0:C.slots]),M=I??a.type,j=N.useMemo(()=>M===a.type?a:{...a,type:M},[a,M]),R=N.useMemo(()=>I!==a.type?{...a,type:I}:a,[a,I]),{data:y,isLoading:L,isFetching:F,errorMessage:f,errorSql:k,pagination:w}=t.useDashboardCardQuery(R),{handleOpenInEditor:V,handleDebugWithAssistant:O}=Fa(f,k||a.sql||a.python),P=N.useMemo(()=>(y==null?void 0:y.records)||[],[y==null?void 0:y.records]),{setCard:_,updateCardInFrame:z}=t.useEditorActions(),{data:U}=t.useTopoJson(j),Y=N.useMemo(()=>{var te;return M!=="pivotTable"||!((te=y==null?void 0:y.records)!=null&&te.length)?null:{records:y.records,columnSubtotalMeta:y.columnSubtotalMeta,subtotalColumns:y.subtotalColumns||[],pivotSchema:y.pivotSchema||[],groupByColumns:y.groupByColumns}},[M,y==null?void 0:y.records,y==null?void 0:y.columnSubtotalMeta,y==null?void 0:y.subtotalColumns,y==null?void 0:y.pivotSchema,y==null?void 0:y.groupByColumns]),$=t.usePivotTableConfig(j,Y),ee=()=>{p(!0)},ne=N.useMemo(()=>{const te=typeof window<"u"?window.location.href:"",ge=typeof navigator<"u"?navigator.userAgent:"",ye=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:c,errorMessage:f||void 0,errorSql:k||a.sql||a.python,generatedSql:k||a.sql},metadata:{url:te,userAgent:ge,timestamp:new Date().toISOString(),viewport:ye}}},[x,h,a,c,f,k]),me=(te,ge)=>{var je,we;const ye={...a,paginationConfig:{page:te+1,pageSize:ge}};_(ye),z(ye),a.sql&&((we=(je=a.preferences)==null?void 0:je.tablePrefs)!=null&&we.enableDevModePagination)&&m(!0)},ve=te=>{var je,we,Ee,K,le;const ge=t.sortStateToSortByColumns(te,(je=a.config)==null?void 0:je.metricColumns,(we=a.config)==null?void 0:we.groupByColumns,(Ee=a.config)==null?void 0:Ee.detailColumns),ye={...a,config:{...a.config||{},sortByColumns:ge}};_(ye),z(ye),a.sql&&((le=(K=a.preferences)==null?void 0:K.tablePrefs)!=null&&le.enableDevModePagination)&&m(!0)},se=N.useMemo(()=>!j.id||!(y!=null&&y.records)?null:t.createChartConfig({card:j,data:y==null?void 0:y.records,cardType:M,queryConfig:j.queryConfig,customCfg:j.customCfg,preferences:j.preferences,topoJson:U}),[j,y==null?void 0:y.records,M,U]);function re(te){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:te})})}function de(){var te;if(y!=null&&y.records&&(y==null?void 0:y.records.length)===0&&!L&&!F)return f?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:f,errorSql:k||a.sql||a.python,onOpenInEditor:V,onDebugWithAssistant:O,onSendFeedback:ee,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((L||F)&&(!(y!=null&&y.records)||y.records.length===0))return M==="table"||M==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!j.id)return null;if(M==="custom")return re(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(M)&&se)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:L||F?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:se})});if(M==="table"||M==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:j,data:P,comparisonMetadata:(te=y==null?void 0:y.metadata)==null?void 0:te.comparisonMetadata,paginationMetadata:w,onPaginationChange:me,onSortChange:ve,isLoading:L||F})});if(M==="pivotTable"&&$)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.PivotTableTanstack,{card:j,data:$.data,options:$.options,onAggregationChange:ge=>{const ye=t.handleAggregationChange(ge,a.config),je={...a,config:ye};_(je),z(je)},onAggregationLabelChange:ge=>{const ye=t.handleAggregationLabelChange(ge,a.config),je={...a,config:ye};_(je),z(je)}})});if(M==="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(t.AggregateTable,{card:j,data:(y==null?void 0:y.records)||[],groupByColumns:y==null?void 0:y.groupByColumns,pivotSchema:y==null?void 0:y.pivotSchema,paginationMetadata:w,onPaginationChange:me,onAggregationChange:ge=>{const ye=t.handleAggregationChange(ge,a.config),je={...a,config:ye};_(je),z(je)},isLoading:L||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...n,children:[(L||F)&&(y==null?void 0:y.records)&&y.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(t.CardHeader,{className:t.cn("flex flex-row items-start justify-between py-4 pr-6","pl-2"),children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.CardTitle,{className:"text-base",children:e.jsx(t.EditableText,{value:a.title,onSave:te=>_({...a,title:te}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:a}),e.jsx(De.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(nr,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(a.description||"").trim(),onSave:te=>_({...a,description:te.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),S&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:S.title||S.column,onSave:te=>b({...S,title:te}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:S})]})]}),d&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-2 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:a,sheetId:l||"",inlineFilterValues:o,setInlineFilterValue:te=>g(a.id,te),removeInlineFilterValue:te=>v(a.id,te)})}),e.jsxs(t.CardContent,{className:t.cn("flex min-h-0 grow flex-col pr-6","pl-2"),children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:de()}),t.isCardSummaryVisibleOnCard(j)&&e.jsx("div",{className:"pt-3",children:e.jsx(t.CardSummary,{card:j,mode:"editor"})})]}),e.jsx(t.FeedbackDialog,{open:u,onOpenChange:p,feedbackData:ne,showDebugInfo:!0})]})}const es=({language:s,value:n,onChange:a,readonly:r})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:n,onValueChange:a,readOnly:r,embedded:!0}),rr=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.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."})]})]}),lr=({customCode:s,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:d})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{language:"json",value:a,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(es,{language:"javascript",value:s,onChange:d})})]}),or=({error:s,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:d})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:d,variant:"outline",children:"Close"})]});function ir({triggerVariant:s="icon",className:n,label:a="Customize Visual"}={}){const[r,d]=N.useState(!1),[i,o]=N.useState(""),[c,l]=N.useState(""),[u,p]=N.useState(""),[x,h]=N.useState(""),m=t.useEditorStore(j=>j.card),g=De.useEffectiveEditorCardType(),v=t.useEditorStore(j=>j.card.customCfg),b=v?JSON.stringify(v,null,2):"",S=N.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:E}=t.useDashboardCardQuery(S),{data:B}=t.useTopoJson(m),{setCardCustomCfg:C,setCustomVisualCode:A}=t.useEditorActions(),T=j=>{var R,y;return JSON.stringify({...j,data:{...j.data,datasets:(y=(R=j.data)==null?void 0:R.datasets)==null?void 0:y.map(L=>({...L,data:[]}))}},null,2)},D=()=>{var R,y;if(!((R=E==null?void 0:E.records)!=null&&R.length))return;const j=t.createChartConfig({card:m,data:E.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:B});if(j){o(T(j)),p(((y=m.preferences)==null?void 0:y.customVisualCode)||"");const L=t.merge(j,v);l(T(L))}},I=()=>{try{if(u&&A(u),c){const j=JSON.parse(c),R=t.getObjectDiff(JSON.parse(i),j);C(R),h("")}}catch{h("Invalid JSON configuration")}},M=Object.keys(v||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:d,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:D,className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",M?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:D,className:t.cn(M?"":"text-green-600 hover:text-green-700",n),children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(rr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Ra,{className:"w-1/2 rounded shadow-none"})}),e.jsx(lr,{customCode:u,cardCustomCfgString:b,mergedConfig:c,onConfigChange:j=>l(j??""),onCodeChange:j=>p(j??"")})]}),e.jsx(or,{error:x,hasCardCustomConfig:!!v,onReset:()=>{l(i),C(null)},onApply:I,onClose:()=>d(!1)})]})]})}function cr({isStarred:s,onClick:n,className:a}){const r=d=>{d.stopPropagation(),d.preventDefault(),n(d)};return e.jsx("button",{type:"button",onClick:r,className:t.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(t.Star,{className:t.cn("h-3.5 w-3.5 transition-colors",s?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function da({chartType:s,chartName:n,isCustom:a=!1,pluginName:r,isStarred:d,showStar:i=!0,onSelect:o,onToggleStar:c}){return e.jsxs("div",{className:"group relative",children:[i&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",d?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(cr,{isStarred:d,onClick:()=>c()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1 z-10",children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(t.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(t.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsxs("button",{type:"button",onClick:o,className:t.cn("flex w-full 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(t.ChartIcon,{chartType:s,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})]})}const ua=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function dr({onChartSelect:s,onClose:n}){const[a,r]=N.useState(""),{starredCharts:d,isStarred:i,toggleStar:o}=t.useStarredChartsStore(),{data:c=[],isLoading:l}=t.useCustomVisualsQuery(),{setCardType:u,setCardPreferences:p,setIsDevMode:x}=t.useEditorStore(j=>j.actions),h=t.useEditorStore(j=>j.card),{setCardCustomCfg:m,setCustomCardPreferences:g,setVisualizationMode:v,setQueryConfig:b,replaceFrameCards:S,clearModeDrafts:E,initializeModeDrafts:B}=t.useEditorActions(),C=N.useMemo(()=>{if(!a)return ua;const j=a.toLowerCase();return ua.filter(R=>R.name.toLowerCase().includes(j))},[a]),A=N.useMemo(()=>{const j=c.filter(y=>y.componentType==="chart"&&y.pluginType!=="standard");if(!a)return j;const R=a.toLowerCase();return j.filter(y=>y.name.toLowerCase().includes(R))},[c,a]),T=j=>{m(null),p({}),v("builtin"),u(j),["custom","text","map"].includes(j)&&(x(!0),b(void 0)),s==null||s(j),n==null||n()},D=j=>{m(null),p({}),v("builtin"),b(void 0);const R=t.resolveMultiInputTypeFromVisual(j);if(R==="multiple"&&j.slots&&j.slots.length>0){E();const L=t.createCardsFromSlots(j.slots,j,h);S(L),L[0]&&B(L[0]),n==null||n();return}else u("custom"),g({type:"component",visualType:R,url:j.url,componentName:j.name,icon:j.icon,pluginChartType:j.chartType,minInputs:j.minInputs,maxInputs:j.maxInputs});s==null||s("custom",j),n==null||n()},I=j=>{const R={type:"default",id:j.id,name:j.name};o(R)},M=j=>{const R={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};o(R)};return e.jsxs("div",{className:"flex flex-col",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(t.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search charts...",value:a,onChange:j=>r(j.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-[350px] overflow-y-auto",children:[C.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:C.map(j=>e.jsx(da,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:i("default",j.id),onSelect:()=>T(j.id),onToggleStar:()=>I(j)},j.id))})}),A.length>0&&e.jsxs(e.Fragment,{children:[C.length>0?e.jsx(t.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:A.map((j,R)=>e.jsx(da,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:i("custom",j.name),onSelect:()=>D(j),onToggleStar:()=>M(j)},`${j.url}-${j.name}-${R}`))})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),C.length===0&&A.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function ur({selectedChart:s,onChartChange:n}){var T,D,I,M;const a=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.frame),d=t.useEditorStore(j=>j.isDevMode),{replaceFrameCards:i,clearModeDrafts:o,initializeModeDrafts:c,setIsDevMode:l}=t.useEditorActions(),u=N.useMemo(()=>t.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=t.useCustomVisual(((T=u==null?void 0:u.customCardPreferences)==null?void 0:T.url)||""),x=N.useMemo(()=>{var j;return(j=p==null?void 0:p.visuals)==null?void 0:j.find(R=>{var y;return R.name===((y=u==null?void 0:u.customCardPreferences)==null?void 0:y.componentName)})},[p,(D=u==null?void 0:u.customCardPreferences)==null?void 0:D.componentName]),h=t.resolveMultiInputType(u,x)==="multiple",m=De.useEffectiveEditorCardType(),g=h?m:s??a.type,v=(I=a==null?void 0:a.customCardPreferences)==null?void 0:I.componentName,b=(M=u==null?void 0:u.customCardPreferences)==null?void 0:M.componentName,S=h&&!!b,E=N.useMemo(()=>{const j=t.chartTypes.find(R=>R.id===g);return j?j.label:g==="custom"?v||"Custom Visual":"Select chart type"},[g,v]),B=N.useMemo(()=>{const j=t.chartTypes.find(R=>R.id===g);if(j){const R=j.icon;return e.jsx(R,{className:"h-4 w-4"})}if(g==="custom"&&v){const R=t.getAutoDetectedChartIcon(v);return R||e.jsx(t.ChartIcon,{chartName:v,isCustom:!0,className:"h-4 w-4"})}return e.jsx(En,{className:"h-4 w-4"})},[g,v]);return{displayChartType:g,displayLabel:E,displayIcon:B,showBadge:S,badgeLabel:b,isMultiInputContext:h,handleChartSelect:j=>{n==null||n(j)},handleClearCustomVisual:j=>{j.stopPropagation();const R={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};i([R]),o(),c(R),d&&l(!0),n==null||n("bar")}}}function us({selectedChart:s,onChartChange:n,variant:a="ghost",className:r}){const[d,i]=N.useState(!1),{displayLabel:o,displayIcon:c,showBadge:l,badgeLabel:u,handleChartSelect:p,handleClearCustomVisual:x}=ur({selectedChart:s,onChartChange:n});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:d,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":d,className:t.cn("w-full justify-between gap-2",a==="ghost"&&"border border-border/70 bg-background text-foreground/90",a==="outline"&&"border-border/70 bg-background text-foreground/90",a==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c,e.jsx("span",{className:"truncate",children:o})]}),e.jsx(t.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:h=>h.preventDefault(),children:e.jsx(dr,{onChartSelect:h=>p(h),onClose:()=>i(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:u,children:[e.jsx(t.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:u}),e.jsx("button",{onClick:x,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]})]})}function mr(){const s=t.useEditorStore(l=>{var u,p;return(p=(u=l.card.preferences)==null?void 0:u.chartOptions)==null?void 0:p.indexAxis}),n=t.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=t.useEditorStore(l=>l.actions),d=l=>{if(a(l),n!=="bullet")return;const u=l==="y"?"horizontal":"vertical",p=t.useEditorStore.getState().card.preferences,x={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:u}};r(x)};function i(){const l=s??"x",u=()=>{d(l==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Xt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})})}function o(){const l=()=>{d(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:l,tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(Xt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})})}function c(){const l=s??"y",u=()=>{d(l==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Wt,{className:"size-4"}):e.jsx(Xt,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?c():i()})}function ms({className:s,triggerVariant:n="icon",label:a="Display Options"}){var v,b,S,E,B,C,A,T,D,I;const r=t.useEditorStore(M=>M.card),{setCardPreferences:d,updateCardInFrame:i,setCard:o}=t.useEditorActions(),[c,l]=N.useState(!1),u=((b=(v=r.preferences)==null?void 0:v.displayOptions)==null?void 0:b.showFilterInfo)??!0,p=((E=(S=r.preferences)==null?void 0:S.displayOptions)==null?void 0:E.showCardToolbar)??!0,x=((C=(B=r.preferences)==null?void 0:B.displayOptions)==null?void 0:C.showChrome)??!0,h=((T=(A=r.preferences)==null?void 0:A.displayOptions)==null?void 0:T.allowScroll)??!0,m=((I=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:I.showInlineFilterBar)??!0,g=(M,j)=>{var L;const R={...r.preferences,displayOptions:{...(L=r.preferences)==null?void 0:L.displayOptions,[M]:j}};d(R);const y={...r,preferences:R};o(y),i(y)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:c,onOpenChange:l,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a})]}):e.jsx(t.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"Display Options"}),e.jsx(t.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(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:M=>{g("showFilterInfo",M)},onSelect:M=>M.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(t.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:M=>{g("showCardToolbar",M)},onSelect:M=>M.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(t.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:M=>{g("showChrome",M)},onSelect:M=>M.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(t.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:M=>{g("allowScroll",M)},onSelect:M=>M.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(t.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:M=>{g("showInlineFilterBar",M)},onSelect:M=>M.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 xs({className:s,triggerVariant:n="icon",label:a="Inline Filters"}){var A,T,D;const[r,d]=N.useState(!1),i=t.useEditorStore(I=>I.card),o=t.useEditorStore(I=>I.selectedConnectionId),{tokenProps:c}=t.useSemaphorContext(),{setCard:l}=t.useEditorActions(),u=t.useDashboardStore(I=>I.actions.removeCardInlineFilterValue),p=t.useDashboardStore(I=>I.actions.setCardInlineFilterValue),x=t.useEditorStore(I=>I.actions.removeCardInlineFilterValue),h=t.useEditorStore(I=>I.actions.setCardInlineFilterValue),m=t.useDashboardStore(I=>I.isVisualEditing),g=(i==null?void 0:i.inlineFilters)||[],v=((T=(A=c==null?void 0:c.params)==null?void 0:A.calendarContext)==null?void 0:T.tz)||((D=c==null?void 0:c.params)==null?void 0:D.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(I){var O,P,_,z,U;const M=((_=(P=(O=i==null?void 0:i.dataSource)==null?void 0:O.selectedEntities)==null?void 0:P[0])==null?void 0:_.database)||"",j=I.qualifiedFieldName||I.name;if(g.find(Y=>t.doesStoredFilterMatchField(Y,I)))return;const y=I.qualifiedFieldName?I.qualifiedFieldName.split(".").slice(0,-1).join("."):I.qualifiedEntityName||I.entityName,F=t.fmt(I.name),f=t.buildFilterFieldMeta(I),k=t.buildFilterSemanticContext(i==null?void 0:i.dataSource,{connectionId:o||((z=i==null?void 0:i.dataSource)==null?void 0:z.connectionId),connectionType:(U=i==null?void 0:i.dataSource)==null?void 0:U.connectionType}),w=t.isCalculatedFilterField(f),V={id:t.v4(),column:j,title:I.label||I.name,dataType:I.dataType,table:I.entityName||"",database:M,connectionId:o||"",operation:"in",sql:w?"":t.getDefaultFilterSql(I.dataType,y,F),fieldMeta:f,semanticContext:k,width:250};l({...i,inlineFilters:[...g,V]})}function S(I){const M=g.filter(j=>j.id!==I);l({...i,inlineFilters:M}),m?x(i.id,I):u(i.id,I)}function E(I,M){const j=g.map(F=>F.id===I?{...F,...M}:F);if(l({...i,inlineFilters:j}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const y=j.find(F=>F.id===I);if(!y)return;const L=t.buildFilterValueFromDefaults(y,v);L?m?h(i.id,L):p(i.id,L):m?x(i.id,I):u(i.id,I)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(i==null?void 0:i.type))return null;const C=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",C&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:C?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",g.length>0&&"text-primary"),children:[e.jsx(sa,{className:"h-4 w-4"}),e.jsx("span",{children:a}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:g.length})]}):e.jsxs(t.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative",{"text-primary":g.length>0}),children:[e.jsx(sa,{className:"h-4 w-4"}),g.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:g.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",C&&"z-[60]"),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 h-[320px] min-h-0 flex-col overflow-hidden",children:e.jsx(t.DndContext,{collisionDetection:t.closestCenter,children:e.jsx(t.SortableContext,{items:[],strategy:t.verticalListSortingStrategy,children:e.jsx(t.FieldsList,{context:"inline-filter",onFieldSelect:b,inlineFilters:g})})})}),g.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:g.map(I=>e.jsx(xr,{filter:I,onUpdate:M=>E(I.id,M),onRemove:()=>S(I.id)},I.id))})]})]})})]})})}function xr({filter:s,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:s.column,children:s.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(t.CustomFilterPopover,{filter:s,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(t.Settings2,{className:"h-3 w-3"})})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const hr={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function pr(s,n){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:n||null}const fr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Vt(s,n){return`${s}:${n}`}function gr(s,n,a){const r=new Set(a.filter(i=>i.target!=="sql_param").map(i=>Vt(i.controlId,i.target))),d=n.map(i=>{const o=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(p=>p.value),c=fr[i.type],u=[...c?[c]:[],...o.filter(p=>p!==c)].find(p=>!r.has(Vt(i.id,p)));return u?{controlId:i.id,target:u}:null}).find(Boolean);return d?{controlId:d.controlId,target:d.target,mapping:{}}:null}function jr({card:s,dashboardControls:n,bindings:a,onChange:r,availableFieldChoices:d,availableMetricChoices:i,suppressTransientStaleState:o=!1}){const c=[...n,...s.controls||[]],[l,u]=N.useState({}),p=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),x=t.getBindingTargetSuggestions(s),h=new Set(a.map(B=>Vt(B.controlId,B.target))),m=c.some(B=>t.getCompatibleBindingTargetOptions({card:s,control:B}).some(C=>!h.has(Vt(B.id,C.value)))),g=o?0:a.reduce((B,C)=>{const A=v(C.target),T=Object.values(C.mapping).filter(D=>{const I=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof D=="string"?D:D==null?void 0:D.id:typeof D=="string"?D:void 0;return typeof I=="string"&&!A.some(M=>M.value===I)}).length;return B+T},0);function v(B){var C,A,T,D;switch(B){case"config_metric_selector":return i?i.filter(I=>!!I.target).map(I=>({value:I.target.id,label:I.target.label||I.option.label,target:I.target})):((A=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:A.map(I=>({value:I.id,label:I.label||I.id,target:I})))||[];case"config_field_selector":return d?d.filter(I=>!!I.target).map(I=>({value:I.target.id,label:I.target.label||I.option.label,target:I.target})):((D=(T=s.config)==null?void 0:T.groupByColumns)==null?void 0:D.map(I=>({value:I.id,label:I.label||I.id,target:I})))||[];case"config_aggregation":return(x.config_aggregation||[]).map(I=>({value:I,label:I}));case"config_grain":return(x.config_grain||[]).map(I=>({value:I,label:I.charAt(0).toUpperCase()+I.slice(1)}));default:return[]}}const b=(B,C)=>{r(a.map((A,T)=>T!==B?A:C(A)))},S=B=>{r(a.filter((C,A)=>A!==B))},E=()=>{const B=gr(s,c,a);B&&r([...a,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=p.map(({controlId:C,paramId:A})=>{const T=c.find(D=>D.id===C);return T?{id:C,paramId:A,label:T.label,reference:`[[param.${A}]]`}:{id:C,paramId:A,label:C,reference:`[[param.${A}]]`}});return e.jsx("div",{className:"space-y-2",children:B.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is currently using raw SQL. Reference a control directly in the SQL editor with syntax like `[[param.metric]]`."}):B.map(C=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:C.reference}),e.jsx(t.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[g>0?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-950",children:[e.jsx(t.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[g," ",g===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"This card is not using any controls yet."}):a.map((B,C)=>{const A=x[B.target]||[],T=c.find(f=>f.id===B.controlId),D=T?t.ensureManualSource(T):null,I=(D==null?void 0:D.source.kind)==="manual"?D.source.options:[],M=v(B.target),j=Array.from(new Set([...I.map(f=>f.value),...Object.keys(B.mapping)])).map(f=>{const k=I.find(w=>w.value===f);return{value:f,label:(k==null?void 0:k.label)||f}}),R=`${B.controlId}-${B.target}-${C}`,y=l[R]??C===0,L=Object.keys(B.mapping).length,F=T!=null&&T.type?hr[T.type]||T.type:null;return e.jsxs(t.Collapsible,{open:y,onOpenChange:f=>u(k=>({...k,[R]:f})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[y?e.jsx(t.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(t.ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:(T==null?void 0:T.label)||"Control"}),F?e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:F}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:L>0?`${L} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>S(C),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]}),e.jsx(t.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:j.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"Add choices to this control first so you can decide what each choice changes in the card."}):M.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No matching targets are available for this binding yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs",children:"Map each choice"}),e.jsx("div",{className:"space-y-2",children:j.map(f=>{const k=B.mapping[f.value],w=B.target==="config_metric_selector"||B.target==="config_field_selector"?typeof k=="string"?k:k==null?void 0:k.id:typeof k=="string"?k:void 0,V=!o&&typeof w=="string"&&!M.some(_=>_.value===w),O=pr(k,w),P=w&&V?[...M,{value:w,label:"Needs remap",target:k}]:M;return e.jsxs("div",{className:"grid gap-2 rounded-md border p-2 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Viewer picks"}),e.jsx("div",{className:"rounded-md bg-muted/50 px-3 py-2 text-sm",children:f.label})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-[11px] text-muted-foreground",children:"Switch to"}),e.jsxs(t.Select,{value:w||"__none__",onValueChange:_=>b(C,z=>{if(z.target==="config_metric_selector"){const Y={...z.mapping};if(_==="__none__")delete Y[f.value];else{const $=P.find(ee=>ee.value===_);$!=null&&$.target?Y[f.value]=$.target:delete Y[f.value]}return{...z,mapping:Y}}if(z.target==="config_field_selector"){const Y={...z.mapping};if(_==="__none__")delete Y[f.value];else{const $=P.find(ee=>ee.value===_);$!=null&&$.target?Y[f.value]=$.target:delete Y[f.value]}return{...z,mapping:Y}}const U={...z.mapping};return _==="__none__"?delete U[f.value]:U[f.value]=_,{...z,mapping:U}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),P.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),V?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(t.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",O?` · Previously: ${O}`:""]})]}):null]})]},`${B.controlId}-${B.target}-${f.value}`)})}),A.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",A.join(", ")]})]})})]},R)}),m?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:E,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}const br=[];function vr({className:s,triggerVariant:n="icon",label:a="Controls"}){var y,L;const{handleOpenChange:r,preventPassiveDismissDuringCreate:d,resolvedOpen:i,setIsCreateFlowActive:o}=De.useCreateFlowOverlayState({}),c=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.frame),u=t.useDashboardStore(F=>F.dashboard),x=t.useDashboardStore(F=>F.dashboard.controls)||br,{setCard:h,updateCardInFrame:m}=t.useEditorActions(),[g,v]=N.useState(null);N.useEffect(()=>{i&&!g&&(c!=null&&c.id)&&v(c.id)},[c==null?void 0:c.id,i,g]),N.useEffect(()=>{!i&&g!==null&&v(null)},[i,g]);const b=N.useMemo(()=>g?(l==null?void 0:l.cards.find(F=>F.id===g))||((c==null?void 0:c.id)===g?c:void 0):c,[c,l==null?void 0:l.cards,g]),S=(b==null?void 0:b.controls)||[],E=b?t.collectDashboardControlIds(u,{excludeCardId:b.id}):x.map(F=>F.id),B=((b==null?void 0:b.controlBindings)||[]).filter(F=>F.target!=="sql_param"),C=t.buildCardControlUsageById({card:b,controls:S}),A={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((y=b==null?void 0:b.config)==null?void 0:y.groupByColumns)||[]).map(F=>[F.id,F]))},T={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((L=b==null?void 0:b.config)==null?void 0:L.metricColumns)||[]).map(F=>[F.id,F]))},D=A.choices.map(F=>({option:F,target:A.targetMap[F.value]})),I=T.choices.map(F=>({option:F,target:T.targetMap[F.value]})),M=(F,f)=>{if(!b)return;const k=(f==null?void 0:f.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:f.oldId,newId:f.newId}):(f==null?void 0:f.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:f.controlId}):b,w={...k,controls:F,controlBindings:t.syncStructuralBindingsWithControls(k.controlBindings,F)};m(w),(c==null?void 0:c.id)===w.id&&h(w)},j=F=>{if(!b)return;const f={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,b.controlBindings)};m(f),(c==null?void 0:c.id)===f.id&&h(f)},R=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",R&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:R?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-8 w-full justify-start gap-2 px-2 text-sm",(S.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),e.jsx("span",{children:a}),S.length+B.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:S.length+B.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative",{"text-primary":S.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-4 w-4"}),S.length+B.length>0&&e.jsx("span",{className:"absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-medium text-primary-foreground",children:S.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:d,onPointerDownOutside:d,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),b!=null&&b.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(De.ControlDefinitionListEditor,{scope:"card",card:b,controls:S,reservedControlIds:E,usageByControlId:C,availableFieldChoices:D,availableMetricChoices:I,onCreateFlowActiveChange:o,onChange:(F,f,k)=>M(F,k),emptyMessage:"No card-scoped controls yet."}),e.jsxs("div",{className:"space-y-1 border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"How this card uses controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose what each control changes in this card."})]}),b?e.jsx(jr,{card:b,dashboardControls:x,bindings:B,onChange:j,availableFieldChoices:D,availableMetricChoices:I}):null]})})]})]})})}function Oa({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:a=!0,showControls:r=!0,showDisplayOptions:d=!0}={}){const i=t.useEditorStore(m=>m.card),o=t.useEditorStore(m=>{var g,v;return(v=(g=m.card)==null?void 0:g.preferences)==null?void 0:v.chartOptions}),c=t.getChartGridStyle(o),{setChartGrid:l}=t.useEditorActions();function u(){const m=["xy","none","x","y"],v=(m.indexOf(c)+1)%m.length;l(m[v])}const p=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),x=n&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return p||x||a||r||d?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[p&&e.jsx(e.Fragment,{children:e.jsx(mr,{})}),x&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:u,children:[(c==="xy"||!c)&&e.jsx(t.Grid3x3,{className:"size-4"}),c==="x"&&e.jsx(cs,{className:"size-4"}),c==="y"&&e.jsx(zt,{className:"size-4"}),c==="none"&&e.jsx(t.Square,{className:"size-4"})]}),a&&e.jsx(xs,{}),r&&e.jsx(vr,{}),d&&e.jsx(ms,{})]}):null}function yr({visible:s}){const n=t.useDashboardStore(o=>o.selectedFrameId),a=t.useManagementStore(o=>o.selectedVisual),r=t.useEditorStore(o=>o.frame),i=!!!(r!=null&&r.visualId||a!=null&&a.id)&&!!n;return!s||i?null:e.jsx("div",{className:"mb-2 flex",children:e.jsx(De.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Nr({isPreviewMode:s,onPreviewToggle:n,configCard:a}){var F,f,k,w,V;const r=t.useEditorStore(O=>O.frame),d=t.useEditorStore(O=>O.card),{setFrame:i,setActiveTabCardId:o,setCard:c,updateCardInFrame:l,clearModeDrafts:u,initializeModeDrafts:p}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((F=a==null?void 0:a.customCardPreferences)==null?void 0:F.url)||""),h=(f=x==null?void 0:x.visuals)==null?void 0:f.find(O=>{var P;return O.name===((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.componentName)}),g=t.resolveMultiInputType(a,h)==="multiple",v=(h==null?void 0:h.minInputs)??((k=a==null?void 0:a.customCardPreferences)==null?void 0:k.minInputs)??1,b=(h==null?void 0:h.maxInputs)??((w=a==null?void 0:a.customCardPreferences)==null?void 0:w.maxInputs),S=N.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:g}),[r,a,g]),E=g?S.filter(Boolean).length:r.cards.length,B=b?E<b:!0,C=E>Math.max(v||1,1),A=!!((V=a==null?void 0:a.customCardPreferences)!=null&&V.dataInputCardIds),T=(O,P)=>{O.dataTransfer.setData("tabIndex",P.toString())},D=O=>{O.preventDefault()},I=(O,P)=>{const _=O.dataTransfer.getData("tabIndex");if(_===P.toString())return;const z=Array.from(r.cards),[U]=z.splice(parseInt(_),1);z.splice(P,0,U),i({...r,cards:z})};function M(O){const P=(a==null?void 0:a.id)===O;if(!(A&&P?r.cards.length>1:C))return;let z=r.cards.filter(ee=>ee.id!==O);g&&!A&&(z=t.reindexSlotCards(z));const U=z[0],Y={...r,cards:z,activeCardId:U.id},$=O===d.id;$&&u(),i(Y),o(U.id),c(U),$&&p(U)}function j(O,P){if(!B)return;const _={...r,cards:[...r.cards,P],activeCardId:O.id};i(_),o(P.id)}function R(){if(g&&(a==null?void 0:a.id)===d.id){y(d);return}const O={...d,id:t.v4(),title:`${d.title} Copy`,tabTitle:`${d.tabTitle||d.title} Copy`,customCardPreferences:d.customCardPreferences?{...d.customCardPreferences,slotIndex:g?Math.max(-1,...S.map((P,_)=>t.getSlotIndexForCard(P,_)))+1:d.customCardPreferences.slotIndex}:void 0};j(d,O)}function y(O){var $;if(!B)return;let P=g?"table":"bar",_="Title",z="";const U=g?Math.max(-1,...S.map((ee,ne)=>t.getSlotIndexForCard(ee,ne)))+1:E;if(g&&(($=h==null?void 0:h.slots)!=null&&$.length)){const ee=t.getSlotDefinitionForIndex(h.slots,U);ee&&(P=t.getSlotExpectedChartType(ee),_=ee.label||`Tab ${U+1}`,z=ee.description||"")}const Y={dataSource:O.dataSource,connectionId:O.connectionId,lastSelectedDatabase:O.lastSelectedDatabase,lastSelectedSchema:O.lastSelectedSchema,lastSelectedTable:O.lastSelectedTable,lastSelectedDatamodelId:O.lastSelectedDatamodelId,id:t.v4(),title:_,tabTitle:_,description:z,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:P,sql:"",data:[],mode:"explorer",...g&&{customCardPreferences:{slotIndex:U}}};j(O,Y)}function L(O,P){return O.cards.length===1&&(P.displayTab===!0||P.displayTab===void 0)||O.activeCardId!==P.id&&(P.displayTab===!0||P.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const _=P.displayTab===void 0?!1:!P.displayTab;c({...P,displayTab:_}),l({...P,displayTab:_})},children:P.displayTab===!0||P.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(t.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group ml-2 mr-6 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((O,P)=>{var $,ee;const _=g?t.getSlotIndexForCard(O,P):-1,z=g&&(($=h==null?void 0:h.slots)!=null&&$.length)&&_>=0?t.getSlotDefinitionForIndex(h.slots,_):null,U=z?(Array.isArray(z.expectedType)?z.expectedType[0]:z.expectedType)||"table":O.type,Y=g&&((ee=h==null?void 0:h.slots)==null?void 0:ee.length)&&h.slots.every(ne=>typeof ne.position=="number"||typeof ne.position=="string"&&!ne.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:ne=>T(ne,P),onDragOver:g?void 0:D,onDrop:g?void 0:ne=>I(ne,P),className:"",value:O.id,children:[g&&z?e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:t.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:z.label||`Tab ${_+1}`})]})}),e.jsx(t.TooltipContent,{side:"bottom",className:"w-64 p-3 text-left",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:z.label}),z.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:z.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[z.expectedType&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:Array.isArray(z.expectedType)?z.expectedType.join(" / "):z.expectedType}),z.required&&e.jsx("span",{className:"inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground",children:"Required"})]})]})})]})}):e.jsxs(e.Fragment,{children:[L(r,O),e.jsx(t.Editable,{enabled:r.activeCardId===O.id,text:O.tabTitle||O.title,onSave:ne=>{c({...d,tabTitle:ne}),l({...d,tabTitle:ne})},children:O.tabTitle||O.title},O.id)]}),r.activeCardId===O.id&&!Y&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:ne=>{ne.stopPropagation(),R()}}),r.activeCardId===O.id&&(A&&(a==null?void 0:a.id)===O.id?r.cards.length>1:C)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>M(O.id)})]},O.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>y(d),disabled:!B,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),g&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(t.EyeOff,{className:"h-4 w-4"}):e.jsx(t.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ot({renderCardOverride:s,alwaysRenderOverride:n=!1}={}){var Ee,K,le,Ne,Pe;const a=t.useEditorStore(W=>W.frame),r=t.useEditorStore(W=>W.card),[d,i]=N.useState(!1),o=N.useMemo(()=>t.findCustomVisualConfigCard(a,r),[a,r]),c=t.useEditorStore(W=>W.isSqlRunning);t.useEditorStore(W=>W.isDevMode);const{setFrame:l,setActiveTabCardId:u,setCard:p,setRunSql:x,mergeDraftsIntoCard:h,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[v,b]=N.useState({}),[S,E]=N.useState(()=>new Set),{theme:B}=t.useTheme(),C=t.useDashboardStore(W=>W.themeStyle),{authToken:A}=t.useSemaphorContext(),T=t.getTokenParams(A==null?void 0:A.accessToken),D={mode:B||"system",colors:((K=(Ee=C==null?void 0:C.chart)==null?void 0:Ee.dataset)==null?void 0:K.backgroundColor)||[]},{getCard:I,manifest:M,isLoading:j}=t.useCustomVisual(((le=o==null?void 0:o.customCardPreferences)==null?void 0:le.url)||""),R=(Ne=o==null?void 0:o.customCardPreferences)==null?void 0:Ne.componentName,y=R?I(R):null,L=(Pe=M==null?void 0:M.visuals)==null?void 0:Pe.find(W=>W.name===R),F=t.resolveMultiInputType(o,L),f=d&&F==="multiple"&&!!o,k=N.useMemo(()=>t.getCustomVisualInputCards({frame:a,configCard:o,isMultiInputVisual:!0}).map(fe=>(fe==null?void 0:fe.id)===r.id?r:fe),[a,o,r]),w=N.useMemo(()=>t.buildSlotOrderedCards(k),[k]),V=N.useMemo(()=>{const W=k.findIndex(fe=>(fe==null?void 0:fe.id)===r.id);return W<0?-1:t.getSlotIndexForCard(r,W)},[k,r]),O=N.useMemo(()=>!o||F!=="multiple"||V<0?r.type:t.getEffectiveCardTypeForSlot(r,V,L==null?void 0:L.slots)??r.type,[o,F,V,r,L==null?void 0:L.slots]),P=N.useMemo(()=>f?{...r,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:O!==r.type?{...r,type:O}:r,[r,O,f]),{data:_,isLoading:z,isFetching:U,isError:Y}=t.useDashboardCardQuery(P),$=N.useCallback((W,fe)=>{const Ce=t.normalizeMultiInputPayload(fe);b(ke=>({...ke,[W]:Ce}))},[]),ee=N.useCallback((W,fe)=>{E(Ce=>{const ke=new Set(Ce);return fe?ke.add(W):ke.delete(W),ke})},[]),ne=S.size>0,me=t.useInteractionStore(W=>W.interactionStates),ve=t.useDashboardStore(W=>{var fe;return(fe=W.dashboard)==null?void 0:fe.id}),se=t.useDashboardStore(W=>W.dashboard.filters),re=t.useDashboardStore(W=>W.filterValues),de=t.useDashboardStore(W=>W.selectedSheetId),pe=t.useEditorStore(W=>W.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),X=t.useEditorStore(W=>W.actions.setCardInlineFilterValue),Z=t.useEditorStore(W=>W.actions.removeCardInlineFilterValue),ue=N.useMemo(()=>o?t.buildInlineFilterNodes({card:o,sheetId:de||"",inlineFilterValues:pe,setInlineFilterValue:W=>X(o.id,W),removeInlineFilterValue:W=>Z(o.id,W)}):[],[o,de,pe,X,Z]),{cardFilters:Fe,cardFilterValues:te}=N.useMemo(()=>o?t.calculateContextAwareFilters({card:o,interactionStates:me,currentDashboardId:ve,filters:se,filterValues:re,selectedSheetId:de}):{cardFilters:[],cardFilterValues:[]},[o,me,ve,se,re,de]);function ge(W){const fe=a.cards.find(Ce=>Ce.id===W);fe&&(it.flushPendingEditorDrafts(),h(),ye(W),u(W),m(),g(fe))}function ye(W){const fe=t.useEditorStore.getState().card,Ce=t.useEditorStore.getState().frame,ke={...Ce,cards:Ce.cards.map(Be=>Be.id===fe.id?fe:Be),activeCardId:W};l(ke);const Se=ke.cards.find(Be=>Be.id===W);Se.sql&&x(!0),p(Se)}function je(){if(j)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!y)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const fe=w.map((Ce,ke)=>t.getEffectiveCardTypeForSlot(Ce,ke,L==null?void 0:L.slots));return e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[k.map((Ce,ke)=>{if(!Ce)return null;const Se=t.getSlotIndexForCard(Ce,ke),Be=t.getEffectiveCardTypeForSlot(Ce,Se,L==null?void 0:L.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:ee,onDataChange:$,card:Ce,effectiveCardType:Be},`${Ce.id}-${Se}`)}),ne&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:t.cn("flex h-full min-h-0 flex-1 flex-col gap-2",ne&&"opacity-50"),children:e.jsx(N.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(y,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:o,slotOrderedCards:w,slotTypes:fe,multiInputData:v,params:T,theme:D,filters:Fe,filterValues:[...te||[],...pe||[]],inlineFilters:ue})})})})]})}function we(){var W;return f?je():s&&(n||!z&&!U&&!Y)?s({card:r,data:_,isLoading:z,isFetching:U,isError:Y}):r.type==="kpi"?z||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx(yr,{visible:!0}),e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(t.KPICard,{card:r,data:_==null?void 0:_.records,isPending:z||U,isError:Y,comparisonMetadata:(W=_==null?void 0:_.metadata)==null?void 0:W.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(r)&&e.jsx(t.CardSummary,{card:r,mode:"editor"})]})}):r.type==="text"?z||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(t.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(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:c,card:r,data:_==null?void 0:_.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Ra,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:ge,value:a.activeCardId,className:"flex grow flex-col gap-2",children:[f?e.jsx("div",{className:"mt-0 grow",children:we()}):a.cards.map(W=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:W.id,children:we()},W.id)),e.jsx(Nr,{isPreviewMode:f,onPreviewToggle:i,configCard:o})]})}function Cr({onClick:s,className:n}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",n),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Pa({fallbackPreview:s,records:n,title:a,isInspectorOpen:r,onInspectorOpenChange:d}){var L;const i=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.actions.setCard),c=t.useEditorStore(F=>F.actions.updateCardInFrame),l=t.normalizeDynamicRendererSource((L=i.dynamicCardPreferences)==null?void 0:L.rendererCode),[u,p]=N.useState(l),[x,h]=N.useState(l);N.useEffect(()=>{p(l),h(l)},[l,i.id]);const m=N.useMemo(()=>t.normalizeDynamicRendererSource(u),[u]),g=N.useMemo(()=>t.validateDynamicRendererSource(m),[m]),v=!!l,b=N.useMemo(()=>{var F;return t.buildCardWithVisualizationMode(i,x?"dynamic":"builtin",{rendererCode:x||void 0,artifactId:((F=i.dynamicCardPreferences)==null?void 0:F.artifactId)||i.id,title:a||i.title})},[i,x,a]),S=!!x,E=m!==x,B=x!==l,C=!m||!g.valid||E||B,A=m?g.valid?E?"Unapplied changes":"Pending save":"Needs attention":"Draft",T=!m||E||B?"outline":"destructive",D=m?g.valid?E?"The preview still reflects the last applied code until you apply this draft.":B?"Preview reflects pending changes. Accept changes to save them.":"":g.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function I(){if(!g.valid){t.ue.error(g.error||"Visual code is invalid.");return}h(m),t.ue.success("Dynamic preview updated.")}function M(){p(x)}function j(){var f;const F=t.buildCardWithVisualizationMode(i,x?"dynamic":"builtin",{rendererCode:x||void 0,artifactId:((f=i.dynamicCardPreferences)==null?void 0:f.artifactId)||t.v4(),title:a||i.title});o(F),c(F),d(!1),t.ue.success(x?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){p(l),h(l),d(!1)}function y(){p(""),h("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:v?e.jsx(t.PersistedDynamicVisual,{card:i,records:n,title:a,layoutMode:"fill",fallback:s},l||"applied-empty"):e.jsxs("div",{className:"flex h-full min-h-[280px] flex-col items-center justify-center gap-3 rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center",children:[e.jsx("div",{className:"flex size-10 items-center justify-center rounded-full border bg-background",children:e.jsx(t.CodeXml,{className:"text-muted-foreground"})}),e.jsxs("div",{className:"flex max-w-md flex-col gap-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"No applied dynamic visual yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open Customize, paste visual code, and apply it to preview the renderer here."})]}),e.jsx(Cr,{onClick:()=>d(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:F=>{if(!F){R();return}d(!0)},children:e.jsxs(t.DialogContent,{className:"flex h-[min(88vh,860px)] max-w-[min(1280px,calc(100vw-2rem))] flex-col gap-0 overflow-hidden p-0",children:[e.jsx(t.DialogHeader,{className:"border-b px-6 py-4 pr-20 text-left",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 pr-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[e.jsx(t.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(t.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),C&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:T,children:A})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(t.ResizablePanel,{defaultSize:54,minSize:38,children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx("div",{className:"min-h-0 flex-1 bg-background p-4",children:S?e.jsx(t.PersistedDynamicVisual,{card:b,records:n,title:a,layoutMode:"fill",fallback:s},x||"preview-empty"):e.jsx("div",{className:"flex h-full min-h-[280px] items-center justify-center rounded-md border border-dashed border-border/70 bg-muted/20 px-6 text-center text-sm text-muted-foreground",children:"Apply valid visual code to preview the dynamic visual here."})})})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:46,minSize:30,children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(t.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.AlertDialog,{children:[e.jsx(t.AlertDialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{type:"button",size:"sm",variant:"ghost",className:"h-8 gap-1.5 px-2.5 text-xs",disabled:!v&&!m,children:[e.jsx(t.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(t.AlertDialogContent,{children:[e.jsxs(t.AlertDialogHeader,{children:[e.jsx(t.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(t.AlertDialogDescription,{children:"This removes the saved dynamic renderer and switches the card back to built-in mode. The underlying query and built-in chart type will remain."})]}),e.jsxs(t.AlertDialogFooter,{children:[e.jsx(t.AlertDialogCancel,{children:"Cancel"}),e.jsx(t.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:y,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:M,disabled:!E,children:[e.jsx(os,{className:"h-3.5 w-3.5 shrink-0"}),"Reset"]}),e.jsxs(t.Button,{type:"button",size:"sm",className:"h-8 gap-1.5 px-3 text-xs",onClick:I,disabled:!E||!g.valid,children:[e.jsx(t.Play,{className:"h-3.5 w-3.5 shrink-0"}),"Apply to Preview"]})]})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[D&&e.jsx("p",{className:t.cn("text-xs",g.valid?"text-muted-foreground":"text-destructive"),children:D}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!g.valid&&m&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:u,onValueChange:F=>p(F||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(t.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:D||"Preview changes here before saving them."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:R,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:j,disabled:!B,children:"Accept changes"})]})]})]})})]})}function Ba({onCustomize:s}){const n=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.actions.setIsShowingVisual),{setVisualizationMode:d,setDynamicCardPreferences:i}=t.useEditorActions(),c=t.getVisualizationMode(n)==="dynamic";if(a.cards.length!==1||t.isCustomVisualizationCard(n))return null;const l=u=>{var p;u==="dynamic"&&!n.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(n.type,(p=n.preferences)==null?void 0:p.displayOptions)),d(u),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),l(c?"builtin":"dynamic")},className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(t.CodeXml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{checked:c,onCheckedChange:u=>l(u?"dynamic":"builtin"),onClick:u=>u.stopPropagation()})]}),c&&s?e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),s()},children:[e.jsx(t.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Customize Visual"]}):null]})}function ma({children:s,visualAsideControl:n}){var ve;const a=t.useQueryClient(),r=t.useEditorStore(se=>se.frame),d=t.useEditorStore(se=>se.card),i=d.type==="table"||d.type==="detailTable",o=t.useEditorStore(se=>se.isDevMode),c=t.useEditorStore(se=>se.isShowingVisual),l=t.useEditorStore(se=>se.actions.setIsShowingVisual),u=t.useDashboardStore(se=>se.isVisualEditing),{isConsoleMode:p}=t.useDashboardPreferences(),x=t.useEditorStore(se=>se.pythonStdOut),h=t.useEditorStore(se=>se.actions.setRunSql),m=De.useEffectiveEditorCardType(),v=t.getVisualizationMode(d)==="dynamic",[b,S]=N.useState(!1),{setFrame:E,setCard:B,setActiveTabCardId:C,setCardPreferences:A,mergeDraftsIntoCard:T,clearModeDrafts:D,initializeModeDrafts:I,updatePageSize:M}=t.useEditorActions(),j=N.useMemo(()=>m!==d.type?{...d,type:m}:d,[d,m]),{data:R,isLoading:y,isFetching:L,errorMessage:F,errorSql:f,refetch:k,queryKey:w,pagination:V}=t.useDashboardCardQuery(j),O=N.useRef(w);O.current=w;const{handleDebugWithAssistant:P}=Fa(F,f),_=N.useMemo(()=>(R==null?void 0:R.records)||[],[R==null?void 0:R.records]),[z,U]=N.useState(!1);N.useEffect(()=>{L||U(!1)},[L]),N.useEffect(()=>{i&&!c&&!o&&!p&&l(!0)},[p,o,i,c,l]);function Y(se,re){var X,Z;const de={...d,paginationConfig:{page:se+1,pageSize:re}};B(de);const pe={...r,cards:r.cards.map(ue=>ue.id===d.id?de:ue)};E(pe),d.sql&&((Z=(X=d.preferences)==null?void 0:X.tablePrefs)!=null&&Z.enableDevModePagination)&&h(!0)}function $(se){var X,Z,ue,Fe,te;const re=t.sortStateToSortByColumns(se,(X=d.config)==null?void 0:X.metricColumns,(Z=d.config)==null?void 0:Z.groupByColumns,(ue=d.config)==null?void 0:ue.detailColumns),de={...d,config:{...d.config||{},sortByColumns:re}};B(de);const pe={...r,cards:r.cards.map(ge=>ge.id===d.id?de:ge)};E(pe),d.sql&&((te=(Fe=d.preferences)==null?void 0:Fe.tablePrefs)!=null&&te.enableDevModePagination)&&h(!0)}function ee(){var re;const se=JSON.stringify(R==null?void 0:R.records,null,2);typeof navigator>"u"||!((re=navigator.clipboard)!=null&&re.writeText)||navigator.clipboard.writeText(se).catch(de=>{console.error("Failed to copy JSON",de)})}function ne(){const se=JSON.stringify(R==null?void 0:R.records,null,2),re=new Blob([se],{type:"application/json"}),de=URL.createObjectURL(re),pe=document.createElement("a");pe.href=de,pe.download=`${d.title}.json`,pe.click()}function me(){const re=[Object.keys(R==null?void 0:R.records.reduce((Z,ue)=>({...Z,...ue}),{})).join(","),...((R==null?void 0:R.records)||[]).map(Z=>Object.values(Z).join(","))].join(`
192
192
  `),de=new Blob([re],{type:"text/csv"}),pe=URL.createObjectURL(de),X=document.createElement("a");X.href=pe,X.download=`${d.title}.csv`,X.click()}return d?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 pl-2 pr-6",children:[c&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(n==null?void 0:n.show)&&e.jsx(t.IconButton,{tooltip:n.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-9 w-9 px-0",buttonProps:{variant:"outline"},onClick:n.onToggle,children:n.isOpen?e.jsx(t.ChevronLeft,{className:"size-4"}):e.jsx(t.ChevronRight,{className:"size-4"})}),!v&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:o?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:y||L,onClick:()=>{if(U(!0),o){it.flushPendingEditorDrafts(),setTimeout(()=>{a.removeQueries({queryKey:O.current,exact:!0}),h(!0)},0);return}k()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":z})})}),!v&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),(o||p)&&e.jsxs(e.Fragment,{children:[e.jsx(Tr,{}),i&&e.jsx(wr,{})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8 w-8 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[!v&&!["table","detailTable","custom"].includes(d.type)&&u&&e.jsx(ir,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ba,{onCustomize:()=>S(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:me,children:[e.jsx(t.Download,{className:"h-4 w-4"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:ne,children:[e.jsx(fn,{className:"h-4 w-4"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-8 w-full justify-start gap-2 px-2 text-sm",onClick:ee,children:[e.jsx(t.Copy,{className:"h-4 w-4"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),c?v?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Pa,{fallbackPreview:e.jsx(ot,{}),records:_,title:d.title,isInspectorOpen:b,onInspectorOpenChange:S})}):e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{className:"py-2 pl-2 pr-6",direction:"horizontal",children:[x&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:x&&e.jsx(Sr,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:t.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"py-2 pl-2 pr-6":x}),children:[Array.isArray(R==null?void 0:R.records)&&!F&&(o?e.jsx(sr,{data:R.records,card:j,paginationMetadata:V,onPaginationChange:Y,onPageSizePreferenceChange:M,onSortChange:$,isLoading:y||L}):R.records.length>0?e.jsx(t.TableVisual,{card:d,data:_,comparisonMetadata:(ve=R==null?void 0:R.metadata)==null?void 0:ve.comparisonMetadata,paginationMetadata:V,onPaginationChange:Y,onSortChange:$,isLoading:y||L}):null),F&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ds,{error:F,errorSql:f||d.sql||d.python,onDebugWithAssistant:P,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Sr(){const s=t.useEditorStore(a=>a.pythonStdOut);if(!s)return null;const n=s.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(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function wr(){var c,l,u,p,x,h,m,g;const s=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>v.actions.setCard),a=t.useEditorStore(v=>v.actions.setRunSql),r=t.useEditorStore(v=>v.actions.setCardPreferences),d=t.useEditorStore(v=>v.actions.updateCardInFrame),i=N.useMemo(()=>{var v,b;return t.getTablePageSizeOptions((b=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:b.pageSize)},[(l=(c=s.preferences)==null?void 0:c.tablePrefs)==null?void 0:l.pageSize]),o=t.resolveTablePageSize((p=(u=s.preferences)==null?void 0:u.tablePrefs)==null?void 0:p.pageSize);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"dev-pagination",checked:((h=(x=s.preferences)==null?void 0:x.tablePrefs)==null?void 0:h.enableDevModePagination)??!1,onCheckedChange:v=>{var b;r({...s.preferences,tablePrefs:{...(b=s.preferences)==null?void 0:b.tablePrefs,enableDevModePagination:v}})}}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:"cursor-pointer text-sm",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(o),onValueChange:v=>{var E,B,C;const b=Number(v),S={...s,preferences:{...s.preferences,tablePrefs:{...(E=s.preferences)==null?void 0:E.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};n(S),d(S),s.sql&&((C=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&C.enableDevModePagination)&&a(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(v=>e.jsx(t.SelectItem,{value:String(v),children:v},v))})]})]})}function Tr(){const s=t.useEditorStore(a=>a.isShowingVisual),n=t.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:a=>{n(!a)},variant:"default",size:"sm",className:"h-8 gap-2 border border-transparent text-foreground/80 hover:bg-accent hover:text-accent-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",children:[e.jsx(t.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Query Output"})]})}function qe({value:s,onCommit:n,type:a="text",placeholder:r,className:d}){const[i,o]=N.useState(s),c=N.useRef(!1);N.useEffect(()=>{o(s)},[s]);const l=()=>{if(c.current){c.current=!1;return}i!==s&&n(i)},u=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(c.current=!0,o(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:a,placeholder:r,value:i,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:u,className:d})}function at({defaultValue:s,label:n,options:a,value:r,onValueChange:d,className:i,icon:o,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[o&&e.jsx("span",{children:o}),c&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),a.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function Er(s,n){return t.getSlotDefinitionForIndex(s,n)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,r,d]=n;return`Tabs ${Number(r)+1}-${Number(d)+1}`}const a=s.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${s}`}function Ir(s){return s?Array.isArray(s)?s:[s]:[]}function ts(s){var r,d;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const n=!!((d=s.sql)!=null&&d.trim()),a=t.hasValidCardConfig(s.config);return n||a}function Dr({slots:s,cards:n,minInputs:a}){const r=[],d=n.filter(Boolean).length;return a&&d<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const l=n[i.position];ts(l)||r.push({type:"missing-required",message:`${St(i.position)} ("${i.label}") is required but has no data configured.`});return}const o=i.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,u]=o.map(Number);for(let p=l;p<=u;p+=1){const x=n[p];if(!ts(x)){r.push({type:"missing-required",message:`${St(p)} ("${i.label}") is required but has no data configured.`});break}}return}const c=i.position.match(/^(\d+)\+$/);if(c){const l=Number(c[1]);if(n.length<=l){r.push({type:"missing-required",message:`${St(l)} ("${i.label}") is required but has no data configured.`});return}for(let u=l;u<n.length;u+=1){const p=n[u];if(!ts(p)){r.push({type:"missing-required",message:`${St(u)} ("${i.label}") is required but has no data configured.`});break}}}}),n.forEach((i,o)=>{if(!i)return;const c=Er(s,o);if(!c||!c.expectedType)return;const l=Ir(c.expectedType);l.length!==0&&(l.includes(i.type)||r.push({type:"wrong-type",message:`${St(o)} ("${c.label}") expects ${l.join(", ")}, but is configured as ${i.type}.`}))})),r}const kr={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Va(){var y,L,F;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:n}=t.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=t.useEditorStore(f=>f.card),d=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),o=N.useMemo(()=>t.findCustomVisualConfigCard(d,r),[d,r]),c=o==null?void 0:o.customCardPreferences,{components:l,manifest:u}=t.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),p=(y=u==null?void 0:u.visuals)==null?void 0:y.find(f=>f.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),h=t.resolveMultiInputType(o||r,p)==="multiple",m=!!o&&o.id===r.id,g=(p==null?void 0:p.minInputs)??((L=o==null?void 0:o.customCardPreferences)==null?void 0:L.minInputs),v=(p==null?void 0:p.maxInputs)??((F=o==null?void 0:o.customCardPreferences)==null?void 0:F.maxInputs),b=N.useMemo(()=>t.getCustomVisualInputCards({frame:d,configCard:o||r,isMultiInputVisual:h}),[d,o,r,h]),S=N.useMemo(()=>t.buildSlotOrderedCards(b),[b]),E=N.useMemo(()=>S.map((f,k)=>{if(!f)return null;const w=t.getSlotIndexForCard(f,k),V=t.getEffectiveCardTypeForSlot(f,w,p==null?void 0:p.slots);return{...f,type:V??f.type}}),[S,p==null?void 0:p.slots]),B=N.useMemo(()=>Dr({slots:p==null?void 0:p.slots,cards:E,minInputs:g}),[p==null?void 0:p.slots,E,g]),C=N.useMemo(()=>{const f=b.findIndex(k=>(k==null?void 0:k.id)===r.id);return f<0?-1:t.getSlotIndexForCard(r,f)},[b,r]);function A(f){if(typeof f=="number")return`Tab ${f+1}`;const k=f.match(/^(\d+)-(\d+)$/);if(k){const[,V,O]=k;return`Tabs ${Number(V)+1}-${Number(O)+1}`}const w=f.match(/^(\d+)\+$/);return w?`Tabs ${Number(w[1])+1}+`:`Tab ${f}`}function T(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function D(f,k,w=[],V="",O,P,_){const z=I({key:k,defaultValue:V,settingsValue:P,sourceCard:_});return f==="input"?e.jsx(qe,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:U=>{M({key:k,value:U,settingsField:O,settingsValue:P,sourceCard:_})}},k):f==="select"?e.jsx(at,{className:"h-8 w-full",label:"",options:w,value:String(z!==void 0?z:V??""),onValueChange:U=>{M({key:k,value:U,settingsField:O,settingsValue:P,sourceCard:_})}}):null}function I({key:f,defaultValue:k,settingsValue:w,sourceCard:V}){const O=w==null?void 0:w[f];return O!==void 0?O:f==="title"&&(V==null?void 0:V.title)!==void 0?V.title:f==="description"&&(V==null?void 0:V.description)!==void 0?V.description:k}function M({key:f,value:k,settingsField:w,settingsValue:V,sourceCard:O}){const P={...V||{}},_=f==="title"&&(O==null?void 0:O.title)!==void 0,z=f==="description"&&(O==null?void 0:O.description)!==void 0;_&&k===String((O==null?void 0:O.title)??"")||z&&k===String((O==null?void 0:O.description)??"")?delete P[f]:P[f]=k,i({...s||{},[w]:P})}function j({settingsSchema:f,settingsField:k,settingsValue:w,sourceCard:V,headerLabel:O}){const P=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[O&&e.jsx(t.Label,{children:O}),P.map(([_,z])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:z.title}),((U=z.docs)==null?void 0:U.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:z.docs.description})})]})})]}),D(z.ui,_,z.options,z.defaultValue,k,w,V)]},_)})]})}function R(){return e.jsxs(e.Fragment,{children:[h&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((f,k)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:A(f.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:f.label})]}),f.description&&e.jsx("p",{className:"text-muted-foreground",children:f.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[T(f.expectedType)&&e.jsxs("span",{children:["Expected: ",T(f.expectedType)]}),f.required&&e.jsx("span",{children:"Required"})]})]},`${f.label}-${k}`))}):e.jsxs("div",{className:"space-y-1 text-muted-foreground",children:[e.jsx("p",{children:"This visual renders all tabs in a flexible layout. Add as many tabs as needed."}),(g||v)&&e.jsxs("p",{children:[g?`Min ${g} tabs`:"",g&&v?" • ":"",v?`Max ${v} tabs`:""]})]})})]}),h&&B.length>0&&e.jsx(t.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(t.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((f,k)=>e.jsx("li",{children:f.message},`${f.type}-${k}`))})})}),p&&!h&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:j({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:r})})}),p&&h&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[m&&p.settings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:p.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:j({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:r,headerLabel:(()=>{const f=r.tabTitle||r.title,k=C>=0?C:0,w=m?"Slot 0":`Slot ${k}`;return f?`${w}: ${f} Settings`:`${w} Settings`})()})})]})]})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.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:[(!h||m)&&e.jsx(at,{icon:e.jsx(Ta,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(c==null?void 0:c.url)||"",onValueChange:f=>i({...s||{url:"",componentName:""},url:f})}),h&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!h||m)&&e.jsx(e.Fragment,{children:l&&e.jsx(at,{icon:e.jsx(pn,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(f=>({value:f.name,label:f.name})))||[],value:s.componentName||"",onValueChange:f=>{var V;const k=(V=u==null?void 0:u.visuals)==null?void 0:V.find(O=>O.name===f),w=l==null?void 0:l.find(O=>O.name===f);i({...s,componentName:f,visualType:(k==null?void 0:k.visualType)||(w==null?void 0:w.type)||"single",minInputs:k==null?void 0:k.minInputs,maxInputs:k==null?void 0:k.maxInputs,pluginChartType:k==null?void 0:k.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(t.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(t.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(t.Markdown,{remarkPlugins:[t.remarkGfm],components:kr,children:p.docs.dataSchema})})]}),(()=>{var k;const f=(k=p.docs)==null?void 0:k.useCases;return!f||f.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Use Cases"}),e.jsx("ul",{className:"space-y-1 text-sm",children:f.map((w,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:w})]},V))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Ar({colorRanges:s,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,c,l){const u=[...s];u[o]={...u[o],[c]:l},n(u)}function d(o){const c=[...s];c.splice(o,1),n(c)}function i(){n([...s,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:"Color Range"}),e.jsx(t.Button,{onClick:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.Plus,{className:"size-3"})})]}),s.map((o,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:l=>r(c,"start",l.target.value),value:o.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:o.end,onChange:l=>r(c,"end",l.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:l=>r(c,"color",l.target.value),value:o.color,className:t.cn(`h-7 min-w-14 p-0 ${t.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:t.colors.green[600]}),e.jsx("option",{children:t.colors.red[500]}),e.jsx("option",{children:t.colors.yellow[400]}),e.jsx("option",{children:t.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>d(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},c))]})}function Mr(){var p,x,h,m,g;const s=t.useEditorStore(v=>v.card.preferences),n=t.useEditorStore(v=>v.actions.setCardPreferences),a=t.useEditorStore(v=>v.card),r=t.hasValidCardConfig(a.config),d=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.decimalPlaces});const i=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.locale}),o=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const c=t.useEditorStore(v=>{var b,S;return(S=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.colorRanges})||[],l=t.useEditorStore(v=>v.actions.setColorRanges),u=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(v=>v.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(t.Checkbox,{checked:!!((p=s==null?void 0:s.formatNumber)!=null&&p.enabled),onCheckedChange:v=>{n({...s,formatNumber:{...s==null?void 0:s.formatNumber,enabled:v}})}}),e.jsx(t.Label,{children:"Format Number"})]}),(((x=s==null?void 0:s.formatNumber)==null?void 0:x.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(t.Label,{children:"Locale"}),e.jsxs(t.Select,{value:i||"none",onValueChange:v=>{var b,S,E;return d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=s==null?void 0:s.formatNumber)==null?void 0:S.currency)||"",v,((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Format"}),e.jsx(t.SelectItem,{value:"none",children:"Auto"},"none"),t.LOCALE_CURRENCY_PAIRS.map(v=>e.jsx(t.SelectItem,{value:v.locale,children:v.locale},v.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Currency"}),e.jsxs(t.Select,{value:o||"none",onValueChange:v=>{var b,S,E;console.log("currency",v),d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,v==="none"?"":v,((S=s==null?void 0:s.formatNumber)==null?void 0:S.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),u.map(v=>e.jsx(t.SelectItem,{value:v,children:v},v))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Decimals"}),e.jsxs(t.Select,{value:((m=(h=s==null?void 0:s.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:m.toString())||"0",onValueChange:v=>{var b,S,E;return d(Number(v),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((S=s==null?void 0:s.formatNumber)==null?void 0:S.locale)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.suffix)||"")},children:[e.jsx(t.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["0","1","2","3","4"].map(v=>e.jsx(t.SelectItem,{value:v,children:v},v))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(t.Label,{children:"Suffix"}),e.jsx(t.Input,{value:((g=s==null?void 0:s.formatNumber)==null?void 0:g.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:v=>{var b,S,E;return d(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=s==null?void 0:s.formatNumber)==null?void 0:S.currency)||"",((E=s==null?void 0:s.formatNumber)==null?void 0:E.locale)||"",v.target.value)}})]})]})]})}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Ar,{colorRanges:c,setColorRanges:l})]})]})}const Lr={combo:{label:"Combo Chart",query:"SELECT x-axis, metric-1, metric-2, ... FROM table",fields:[{name:"x-axis",type:"category",description:"dimension"},{name:"metric-1, metric-2",type:"number",description:"can be bar, line, or area"}],description:"Combo charts allow mixing bar and line series with optional dual Y-axis for metrics with different scales.",docsUrl:"https://docs.semaphor.cloud/docs/charts/combo"},area:{label:"Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Area charts display quantitative data with filled areas under the line.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedArea:{label:"Stacked Area Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, city"},{name:"Y-axis",type:"number",description:"e.g., sales, population"}],description:"Stacked area charts show how multiple series contribute to a total over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},bar:{label:"Bar Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., city, product"},{name:"Y-axis",type:"number",description:"e.g., sales, count"}],description:"Bar charts compare values across categories using horizontal or vertical bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},line:{label:"Line Chart",query:"SELECT x-axis, y-axis-1, y-axis-2, ... FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date, month"},{name:"Y-axis",type:"number",description:"e.g., revenue, count"}],description:"Line charts show trends over time or continuous data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bar-line-area"},stackedBar:{label:"Stacked Bar Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., month"},{name:"Stack-by",type:"category",description:"e.g., product type"},{name:"Y-axis",type:"number",description:"e.g., sales"}],description:"Stacked bar charts show how parts contribute to a whole across categories.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},stackedLine:{label:"Stacked Line Chart",query:"SELECT x-axis, stack-by, y-axis FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., date"},{name:"Stack-by",type:"category",description:"e.g., region"},{name:"Y-axis",type:"number",description:"e.g., revenue"}],description:"Stacked line charts show cumulative trends over time.",docsUrl:"https://docs.semaphor.cloud/docs/charts/stacked"},pie:{label:"Pie Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Pie charts show proportions of a whole.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},doughnut:{label:"Doughnut Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., product, region"},{name:"Measure",type:"number",description:"e.g., sales, count"}],description:"Doughnut charts show proportions with a hollow center.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},polarArea:{label:"Polar Area Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., skill, metric"},{name:"Measure",type:"number",description:"e.g., score, value"}],description:"Polar area charts compare values using sectors of equal angle but varying radius.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},radar:{label:"Radar Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., attribute, skill"},{name:"Measure",type:"number",description:"e.g., score, rating"}],description:"Radar charts display multivariate data on axes starting from the same point.",docsUrl:"https://docs.semaphor.cloud/docs/charts/pie-donut-polar"},funnel:{label:"Funnel Chart",query:"SELECT label, measure FROM table",fields:[{name:"Label",type:"category",description:"e.g., stage name"},{name:"Measure",type:"number",description:"e.g., count, value"}],description:"Funnel charts visualize progressive reduction of data through stages.",docsUrl:"https://docs.semaphor.cloud/docs/charts/funnel"},bubble:{label:"Bubble Chart",query:"SELECT label, [group], x-axis, y-axis, radius FROM table",fields:[{name:"Label",type:"category",description:"e.g., city"},{name:"Group",type:"category",description:"e.g., region",optional:!0},{name:"X-axis",type:"number",description:"e.g., population"},{name:"Y-axis",type:"number",description:"e.g., income"},{name:"Radius",type:"number",description:"e.g., area"}],description:"Bubble charts display three dimensions of data using position and size.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},scatter:{label:"Scatter Chart",query:"SELECT label, [group], x-axis, y-axis FROM table",fields:[{name:"Label",type:"category",description:"e.g., item name"},{name:"Group",type:"category",description:"e.g., type",optional:!0},{name:"X-axis",type:"number",description:"e.g., price"},{name:"Y-axis",type:"number",description:"e.g., quantity"}],description:"Scatter charts show relationships between two numeric variables.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bubble"},tornado:{label:"Tornado Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Tornado charts compare two groups across categories using back-to-back bars.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},pyramid:{label:"Pyramid Chart",query:"SELECT dimension, cohort, metric FROM table",fields:[{name:"Dimension",type:"category",description:"e.g., age group"},{name:"Cohort",type:"category",description:"e.g., gender"},{name:"Metric",type:"number",description:"e.g., population"}],description:"Population pyramids show age and gender distribution.",docsUrl:"https://docs.semaphor.cloud/docs/charts/tornado"},range:{label:"Range Chart",query:"SELECT y-axis, label, range-from, range-to, range-value FROM table",fields:[{name:"Y-axis",type:"category",description:"e.g., category"},{name:"Label",type:"category",description:"e.g., range name"},{name:"Range-from",type:"number",description:"start value"},{name:"Range-to",type:"number",description:"end value"},{name:"Range-value",type:"number",description:"e.g., midpoint"}],description:"Range charts display data ranges with start and end values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/range"},heatmap:{label:"Heatmap",query:"SELECT x-axis, y-axis, value FROM table",fields:[{name:"X-axis",type:"category",description:"e.g., day"},{name:"Y-axis",type:"category",description:"e.g., hour"},{name:"Value",type:"number",description:"e.g., count, intensity"}],description:"Heatmaps visualize data density using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/heatmap"},bullet:{label:"Bullet Chart",query:"SELECT label, actual, target, [ranges] FROM table",fields:[{name:"Label",type:"category",description:"e.g., metric name"},{name:"Actual",type:"number",description:"current value"},{name:"Target",type:"number",description:"goal value"},{name:"Ranges",type:"number",description:"threshold values",optional:!0}],description:"Bullet charts compare actual performance against targets.",docsUrl:"https://docs.semaphor.cloud/docs/charts/bullet"},text:{label:"Text Visual",query:"SELECT text FROM table LIMIT 1",fields:[{name:"Text",type:"string",description:"content to display"}],description:"Text visuals display dynamic text content from your data.",docsUrl:"https://docs.semaphor.cloud/docs/charts/text"},kpi:{label:"KPI",query:"SELECT current, previous FROM table",fields:[{name:"Current",type:"number",description:"current value"},{name:"Previous",type:"number",description:"comparison value"}],description:"KPI visuals display key performance indicators with comparison values.",docsUrl:"https://docs.semaphor.cloud/docs/charts/kpi"},map:{label:"Map Chart",query:"SELECT country, value FROM table",fields:[{name:"Country/Region",type:"category",description:"geographic identifier"},{name:"Value",type:"number",description:"e.g., population, sales"}],description:"Map charts visualize geographic data using color intensity.",docsUrl:"https://docs.semaphor.cloud/docs/charts/map"},table:{label:"Table",query:"SELECT column1, column2, ... FROM table",fields:[{name:"Columns",type:"category",description:"any data columns"}],description:"Tables display data in rows and columns.",docsUrl:"https://docs.semaphor.cloud/docs/charts/table"},detailTable:{label:"Detail Table",query:"SELECT column1, column2, ... FROM table ORDER BY column1 DESC",fields:[{name:"Columns",type:"category",description:"columns to display (no aggregation)"}],description:"Detail tables display raw records without aggregation. Ideal for event logs, transaction history, and audit trails.",docsUrl:"https://docs.semaphor.cloud/docs/charts/detail-table"}};function za(s){return Lr[s]}function Fr({chartType:s,showDocsLink:n=!0}){const a=za(s);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,d)=>e.jsxs("tr",{className:d<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(t.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Rr({chartType:s}){return za(s)?e.jsxs(t.HoverCard,{openDelay:200,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"rounded bg-muted px-2 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:bg-muted/80 hover:text-foreground",children:"SQL"})}),e.jsx(t.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Fr,{chartType:s})})]}):null}function _t({chartType:s,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(Rr,{chartType:s})]})}function Or(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Mr,{})})]})}function xa({children:s,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:t.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(t.Label,{children:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function _a(){const[s,n]=N.useState([]),a=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:d}=t.useEditorStore(u=>u.actions),i=t.useEditorStore(u=>u.queryResultColumns);t.useEditorStore(u=>{var p;return(p=u.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),N.useEffect(()=>{i&&n(new Array(i.length).fill(!1))},[i]);function o(u,p){var x,h;p?a!=null&&a.onClickFilter&&((x=a==null?void 0:a.onClickFilter)==null?void 0:x.length)>0?d({...a,onClickFilter:[...a.onClickFilter,{columnIndex:u,expression:""}]}):d({...a,onClickFilter:[{columnIndex:u,expression:""}]}):(d({...a,onClickFilter:(h=a==null?void 0:a.onClickFilter)==null?void 0:h.filter(m=>m.columnIndex!==u)}),n(m=>{const g=[...m];return g[u]=!1,g}))}function c(u,p){var h;const x=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.map(m=>m.columnIndex===u?{...m,expression:p.target.value}:m);d({...a,onClickFilter:x})}function l(u){var p,x,h,m;if(s!=null&&s[u]||(x=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))!=null&&x.expression)return e.jsx(t.Input,{value:(m=(h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>c(u,g),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:i==null?void 0:i.map((u,p)=>{var x,h;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(t.Checkbox,{checked:!!((x=a==null?void 0:a.onClickFilter)!=null&&x.find(m=>m.columnIndex===p)),onCheckedChange:m=>o(p,m)}),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:((h=a==null?void 0:a.onClickFilter)==null?void 0:h.find(m=>m.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{n(m=>{const g=[...m];return g[p]=!m[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},u)})})}const Pr=[{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"}],Br=["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"],Vr=Br.map(s=>({label:s,value:s}));function zr(){var l,u,p,x,h,m,g,v,b,S,E,B,C,A,T,D,I,M;const s=t.useEditorStore(j=>j.card),n=(u=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:u.topoJsonUrl,[a,r]=N.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:i}=t.useTopoJson(s),o=Object.keys((i==null?void 0:i.objects)||{}).map(j=>({label:j,value:j}))||[],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:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:"map"}),e.jsx(xa,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(at,{className:"h-9",options:c,onValueChange:j=>{console.log("value",j),d({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:j=>{r(j.target.value)},onBlur:()=>{var j;console.log("onBlur",a),d({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(at,{className:"h-9",options:o,value:((m=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,objectKey:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(at,{className:"h-9",options:Pr,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:j=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projection:j}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(at,{className:"h-9",options:Vr,value:((S=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:S.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(xa,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((B=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:j=>{var R;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionScale:Number(j.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((T=(A=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[0])||0,onChange:j=>{var R,y,L,F;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(j.target.value),((F=(L=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:F[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:M[1])||0,onChange:j=>{var R,y,L,F;d({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(L=(y=s.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:F[0])||0,Number(j.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(_a,{})]})}function qa({color:s,onColorChange:n,onClose:a}){const[r,d]=N.useState(0),[i,o]=N.useState(100),[c,l]=N.useState(50),[u,p]=N.useState(s);N.useEffect(()=>{const b=ha(s);if(b){const S=pa(b.r,b.g,b.b);d(S.h),o(S.s),l(S.l),p(s)}},[s]);const x=b=>{d(b),m(b,i,c)},h=b=>{const S=b.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(b.clientX-S.left)/S.width)),B=Math.max(0,Math.min(1,(b.clientY-S.top)/S.height)),C=E*100,A=(1-B)*100;o(C),l(A),m(r,C,A)},m=(b,S,E)=>{const B=qr(b,S,E),C=_r(B.r,B.g,B.b);p(C)},g=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const S=ha(b);if(S){const E=pa(S.r,S.g,S.b);d(E.h),o(E.s),l(E.l)}}},v=()=>{/^#[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:h,onMouseMove:b=>{b.buttons===1&&h(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,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:b=>x(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"HEX"}),e.jsx(t.Input,{value:u,onChange:b=>g(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:s}}),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(t.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(t.Button,{onClick:v,children:"OK"})]})]})}function ha(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function _r(s,n,a){return"#"+((1<<24)+(s<<16)+(n<<8)+a).toString(16).slice(1)}function pa(s,n,a){s/=255,n/=255,a/=255;const r=Math.max(s,n,a),d=Math.min(s,n,a);let i=0,o=0;const c=(r+d)/2;if(r!==d){const l=r-d;switch(o=c>.5?l/(2-r-d):l/(r+d),r){case s:i=((n-a)/l+(n<a?6:0))/6;break;case n:i=((a-s)/l+2)/6;break;case a:i=((s-n)/l+4)/6;break}}return{h:Math.round(i*360),s:Math.round(o*100),l:Math.round(c*100)}}function qr(s,n,a){s/=360,n/=100,a/=100;let r,d,i;if(n===0)r=d=i=a;else{const o=(u,p,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(p-u)*6*x:x<.5?p:x<.6666666666666666?u+(p-u)*(.6666666666666666-x)*6:u),c=a<.5?a*(1+n):a+n-a*n,l=2*a-c;r=o(l,c,s+1/3),d=o(l,c,s),i=o(l,c,s-1/3)}return{r:Math.round(r*255),g:Math.round(d*255),b:Math.round(i*255)}}const fa=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$r=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function nt({value:s,onChange:n,label:a}){const[r,d]=N.useState(!1),[i,o]=N.useState(!1),c=()=>{const l=fa.find(u=>u.value===s);return l?l.color:s.startsWith("#")?s:fa[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:r,onOpenChange:d,children:[e.jsx(t.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(t.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:$r.map(l=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",c()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),d(!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:()=>{o(!0),d(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),i&&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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(qa,{color:c(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function ga(s,n){if(!n||n==="auto")return{type:"auto"};const a={...s,type:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?is(a,Bt(n)):a}function is(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Kr=["auto","number","currency","percent","scientific","date"],Gr=[{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"}],Ur=[{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"}],Hr=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const d=s.type||"auto",i=d==="auto"?s:ga(s,d),o=m=>{m.stopPropagation()},c=(m,g)=>{n({...i,[m]:g})},[l,u]=N.useState(()=>String(i.decimalPlaces??Bt(d))),[p,x]=N.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),h=m=>{n(ga(s,m))};return N.useEffect(()=>{u(String(i.decimalPlaces??Bt(d)))},[i.decimalPlaces,d]),N.useEffect(()=>{x(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:d,onValueChange:m=>h(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Hr(m)},m))})]})]}),d!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(d)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:"10",placeholder:"0",value:l,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");u(g),g!==""&&n(is(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(l!=="")return;const m=Bt(d);u(String(m)),n(is(i,m))},className:"h-8 text-xs"})})]}),d==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(t.Select,{value:s.currency||"USD",onValueChange:m=>c("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:s.useSuffix??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>c("useSuffix",m)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(t.Select,{value:s.locale||"en-US",onValueChange:m=>c("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:o,onPointerDown:o,onKeyDown:o,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ur.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., $",value:s.prefix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>c("prefix",m.target.value),className:"h-8 text-xs"})})]}),d==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{placeholder:"e.g., units",value:s.suffix||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>c("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(d)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(t.Switch,{size:"sm",checked:s.negativeInParentheses??!1,onClick:m=>m.stopPropagation(),onCheckedChange:m=>c("negativeInParentheses",m)})]}),d==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",inputMode:"decimal",placeholder:"100",value:p,onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");x(g),c("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),d==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(t.Input,{type:"text",placeholder:"MM/DD/YYYY",value:s.dateFormat||"",onClick:o,onPointerDown:o,onKeyDown:o,onChange:m=>c("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function hs({value:s,onChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const d=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=o=>{n(t.fromTFormatOptions(o))};return e.jsx(jt,{formatOptions:d,onFormatOptionsChange:i,showTitle:a,title:r})}function Qr(){const s=t.useDashboardStore(c=>c.dashboard.filters),n=t.useEditorStore(c=>c.frame),{setFrame:a}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:d}=t.useAssignFilter();function i(c){const l=d(c,"frame");a({...n,filterId:l})}const o=s==null?void 0:s.find(c=>c.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(Jr,{onSelect:i,columns:r}),o&&e.jsx(t.FilterHeader,{filter:o})]})}function Jr({columns:s,onSelect:n}){var c;const[a,r]=Pt.useState(!1),[d,i]=Pt.useState(""),o=Pt.useCallback(l=>[l.label,l.name,l.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:a,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[d?((c=s.find(l=>l.id===d))==null?void 0:c.label)||d:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No column found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(l=>e.jsxs(t.CommandItem,{value:o(l),onSelect:()=>{const u=l.id===d?"":l.id;i(u),r(!1),u&&n(l)},children:[l.label||l.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",d===l.id?"opacity-100":"opacity-0")})]},l.id))})]})]})})]})}const Yr=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Wr=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Xr({cardType:s="table"}){var p,x,h,m,g;const n=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),d=((p=n.config)==null?void 0:p.metricColumns)||[],i=d.some(v=>v.comparisonType&&v.comparisonType!=="none"),o=((x=a==null?void 0:a.tableVisualOptions)==null?void 0:x.metricComparison)||{},c=v=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...v}}})},l={increase:((h=o.colors)==null?void 0:h.increase)||"green",decrease:((m=o.colors)==null?void 0:m.decrease)||"red",neutral:((g=o.colors)==null?void 0:g.neutral)||"neutral"},u=v=>{r({...a,allowDownload:v})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:[i&&e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.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(Ia,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(t.Select,{value:o.calculatedAs||"change_difference",onValueChange:v=>c({calculatedAs:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yr.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:v=>c({formatOptions:v}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(t.Select,{value:o.indicatorStyle||"arrow_badge",onValueChange:v=>c({indicatorStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wr.map(v=>e.jsx(t.SelectItem,{value:v.value,className:"text-xs",children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(nt,{value:l.increase,onChange:v=>c({colors:{...l,increase:v}}),label:"Increase"}),e.jsx(nt,{value:l.decrease,onChange:v=>c({colors:{...l,decrease:v}}),label:"Decrease"}),e.jsx(nt,{value:l.neutral,onChange:v=>c({colors:{...l,neutral:v}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(t.Checkbox,{checked:o.lowerIsBetter||!1,onCheckedChange:v=>c({lowerIsBetter:!!v})})]})]})]}),d.length>0&&e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsx("span",{children:"Metric Formats"})}),e.jsx(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:d.map(v=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:v.label||v.name}),e.jsx(hs,{value:v.format,onChange:b=>{var E;const S=(((E=n.config)==null?void 0:E.metricColumns)||[]).map(B=>B.id===v.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(n.id,{metricColumns:S})},showTitle:!1})]},v.id))})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Click Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(_a,{}),e.jsx(Qr,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:u,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 Zr(){var r;const s=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:n}=t.useEditorStore(d=>d.actions);function a(d){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:d==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.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(t.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(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function el(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Text Type"}),e.jsx(Zr,{})]})]})}const tl=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function sl(){var A,T,D,I,M,j,R,y,L,F;const s=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>{var k;return(k=f.card)==null?void 0:k.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions(),i=N.useMemo(()=>a!==s.type?{...s,type:a}:s,[s,a]),{data:o}=t.useDashboardCardQuery(i),[c,l]=N.useState({}),[u,p]=N.useState(null),[x,h]=N.useState(null),m=N.useMemo(()=>{var V,O,P,_,z,U,Y;if(!(o!=null&&o.records)||o.records.length===0)return[];const f=a==="stackedBar"||a==="stackedLine",k=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",w=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||k)&&w){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const $=new Set;return o.pivotSchema.forEach(ee=>{ee.alias&&$.add(ee.alias)}),Array.from($)}if(o.records.length>0){const $=o.records[0],ee=Object.keys($),ne=new Set;(O=s==null?void 0:s.config)!=null&&O.groupByColumns&&s.config.groupByColumns.forEach(se=>{ne.add(se.label||se.name),ne.add(se.alias||se.name)});const me=new Set;return(P=s==null?void 0:s.config)!=null&&P.metricColumns&&s.config.metricColumns.forEach(se=>{const re=se.alias||se.name;me.add(re),me.add(`${re}_count`),me.add(`${re}_sum`),me.add(`${re}_avg`),me.add(`${re}_min`),me.add(`${re}_max`);const de=se.entityName||se.qualifiedEntityName;de&&(me.add(`${de}_${re}`),me.add(`${de}_${re}_count`))}),ee.filter(se=>!ne.has(se)&&!me.has(se))}}if((k||f)&&!w&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map($=>$.alias||$.label||$.name);if((Y=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&Y.length){const $=s.config.groupByColumns[0],ee=$.label||$.name,ne=new Set;return o.records.forEach(me=>{const ve=me[ee];ve!=null&&ne.add(String(ve))}),Array.from(ne)}return[]},[o,(A=s==null?void 0:s.config)==null?void 0:A.groupByColumns,(T=s==null?void 0:s.config)==null?void 0:T.pivotByColumns,(D=s==null?void 0:s.config)==null?void 0:D.metricColumns,s==null?void 0:s.type]),g=N.useMemo(()=>t.getDefaultChartColors(),[]);N.useEffect(()=>{const f={};m.forEach((k,w)=>{f[k]=t.getColorForValue(k,w,n==null?void 0:n.colorConfig)}),l(f)},[m,n==null?void 0:n.colorConfig,g]);const v=(f,k)=>{const w={...c,[f]:k};l(w);const V={...n||{},colorConfig:{segments:w}};r(V);const O={...s,preferences:V};d(O)},b=(f,k)=>{var z;const w=g[k%g.length],{[f]:V,...O}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},P={...n||{},colorConfig:{segments:O}};r(P);const _={...s,preferences:P};d(_),l(U=>({...U,[f]:w}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((M=(I=s==null?void 0:s.config)==null?void 0:I.groupByColumns)==null?void 0:M.length)||((R=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:R.length):(L=(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const f={...n||{},colorConfig:{segments:{}}};r(f);const k={...s,preferences:f};d(k);const w={};m.forEach((V,O)=>{w[V]=t.getColorForValue(V,O,void 0)}),l(w)},C=Object.keys(((F=n==null?void 0:n.colorConfig)==null?void 0:F.segments)||{}).length>0;return e.jsxs(t.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(t.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(Cn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(t.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:C&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(os,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:m.map((f,k)=>{const w=t.isDefaultColor(c[f],k),V=!w;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:u===f,onOpenChange:O=>p(O?f:null),children:[e.jsx(t.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:c[f]}})}),e.jsx(t.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((O,P)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[f]===O?"border-gray-900":"border-transparent"),style:{backgroundColor:O},onClick:()=>{v(f,O),p(null)},children:[P===k%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:O})]},`default-${P}`))})]}),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:tl.map((O,P)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[f]===O?"border-2 border-gray-900":O==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:O},onClick:()=>{v(f,O),p(null)},children:e.jsx("span",{className:"sr-only",children:O})},`preset-${P}`))})]}),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:()=>{h({value:f,color:c[f]}),p(null)},children:"Custom color"}),!w&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(f,k),p(null)},children:[e.jsx(os,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),V&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},f)})}),x&&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:()=>h(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(qa,{color:x.color,onColorChange:f=>{v(x.value,f),h(null)},onClose:()=>h(null)})})]})]})})]})}function He({value:s,onSave:n,placeholder:a="",type:r="text",className:d=""}){const[i,o]=N.useState(s??""),[c,l]=N.useState(!1);N.useEffect(()=>{o(s??"")},[s]);const u=()=>{n(i),l(!1)},p=()=>{o(s??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input,{placeholder:a,type:r,value:c?i:s??"",onChange:x=>{o(x.target.value),l(!0)},onFocus:()=>l(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&c&&i!==s?u():x.key==="Escape"&&p()},"aria-label":a||"Edit field"}),c&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:u,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function ss({axis:s,label:n,type:a,config:r,onChange:d,defaultTitle:i,hidePosition:o}){var g,v,b,S,E,B,C,A,T,D,I,M,j,R;const c=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),l=(y,L)=>{d({...r??{},[y]:L})},u=(y,L)=>{var w,V,O,P;const F=y==="enabled"&&L===!0,f=(w=r==null?void 0:r.name)==null?void 0:w.text,k=F&&!f&&i;d({...r??{},name:{...r==null?void 0:r.name,enabled:y==="enabled"?L:((V=r==null?void 0:r.name)==null?void 0:V.enabled)??!1,text:y==="text"?L:k?i:f,fontSize:y==="fontSize"?L:(O=r==null?void 0:r.name)==null?void 0:O.fontSize,fontWeight:y==="fontWeight"?L:(P=r==null?void 0:r.name)==null?void 0:P.fontWeight}})},p=(y,L)=>{var F,f;d({...r??{},labels:{enabled:y==="enabled"?L:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:y==="rotation"?L:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},x=(y,L)=>{d({...r??{},scale:{...r==null?void 0:r.scale,[y]:L===""?"auto":Number(L)}})},h=s==="x"?["auto","top","bottom"]:["auto","left","right"],m=["auto","0","45","90","-45","-90"];return e.jsxs(t.AccordionItem,{value:`${s}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(t.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(t.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:y=>l("enabled",y),onClick:y=>y.stopPropagation()})]}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:`${s}-title-enabled`,checked:((g=r==null?void 0:r.name)==null?void 0:g.enabled)??!1,onCheckedChange:y=>u("enabled",y===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((v=r==null?void 0:r.name)==null?void 0:v.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(He,{placeholder:`${n} title`,value:((b=r==null?void 0:r.name)==null?void 0:b.text)||"",onSave:y=>u("text",y),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((S=r==null?void 0:r.name)==null?void 0:S.fontSize)||12),onSave:y=>u("fontSize",Number(y)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(t.Select,{value:((E=r==null?void 0:r.name)==null?void 0:E.fontWeight)||"normal",onValueChange:y=>u("fontWeight",y),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!o&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:y=>l("position",y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(y=>e.jsx(t.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":t.titleCase(y)},y))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(t.Switch,{size:"sm",checked:((B=r==null?void 0:r.labels)==null?void 0:B.enabled)!==!1,onCheckedChange:y=>p("enabled",y)})]}),((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(t.Select,{value:String(((A=r==null?void 0:r.labels)==null?void 0:A.rotation)||"auto"),onValueChange:y=>p("rotation",y==="auto"?"auto":Number(y)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(y=>e.jsx(t.SelectItem,{value:y,className:"text-xs",children:y==="auto"?"Auto (Default)":`${y}°`},y))})]})]})]}),a==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:c==="override",onCheckedChange:y=>d({...r,formatMode:y?"override":"inherit"})})]}),c==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:y=>d({...r,formatMode:"override",formatOptions:y}),showTitle:!1})]}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((T=r==null?void 0:r.scale)==null?void 0:T.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:y=>x("min",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((I=r==null?void 0:r.scale)==null?void 0:I.max)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.max)===void 0?"":String(r.scale.max),onSave:y=>x("max",y),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"auto",value:((j=r==null?void 0:r.scale)==null?void 0:j.stepSize)==="auto"||((R=r==null?void 0:r.scale)==null?void 0:R.stepSize)===void 0?"":String(r.scale.stepSize),onSave:y=>x("stepSize",y),className:""})})]})]})]})]})]})}function as(s,n,a){var i,o,c;if(s==="x"){const l=(o=(i=n==null?void 0:n.config)==null?void 0:i.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.name)||""}const r=((c=n==null?void 0:n.config)==null?void 0:c.metricColumns)||[],d=(a==null?void 0:a.datasetOptions)||[];if(s==="y"){const l=r.filter((u,p)=>{const x=d.find(h=>h.idx===p);return!x||x.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(s==="y2"){const l=r.filter((u,p)=>{const x=d.find(h=>h.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function al(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),{setCardPreferences:a,updateCardInFrame:r}=t.useEditorActions(),d=De.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const i=t.AxisConfigurator.getAxisInfo(d,n);if(!i.hasXAxis&&!i.hasYAxis)return null;const o=(l,u)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...n||{},[p]:u};a(x);const h={...s,preferences:x};r(h)},c=i.hasY2Axis&&d==="combo";return e.jsxs(t.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(t.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(t.SlidersHorizontal,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[i.hasXAxis&&e.jsx(ss,{axis:"x",label:"X-Axis",type:i.xAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"x"),n==null?void 0:n.xAxisConfig),onChange:l=>o("x",l),defaultTitle:as("x",s,n)}),i.hasYAxis&&e.jsx(ss,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(d,"y"),n==null?void 0:n.yAxisConfig),onChange:l=>o("y",l),defaultTitle:as("y",s,n)}),c&&e.jsx(ss,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:l=>o("y2",l),defaultTitle:as("y2",s,n),hidePosition:!0})]})})]})}function nl(){const s=t.useEditorStore(x=>x.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(x=>{var h,m,g,v;return(v=(g=(m=(h=x.card)==null?void 0:h.preferences)==null?void 0:m.chartOptions)==null?void 0:g.plugins)==null?void 0:v.legend}),{setLegendOptions:r}=t.useEditorActions();if(!s||!t.chartSupportsLegend(n))return null;const d=t.getDefaultLegendConfig(n),i=(d==null?void 0:d.display)??!0,o=(d==null?void 0:d.position)??"top",c=(d==null?void 0:d.align)??"center",l=(x,h)=>{const m={...a,[x]:h};r(m)},u=["top","bottom","left","right"],p=["start","center","end"];return e.jsxs(t.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(t.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(bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:(a==null?void 0:a.display)??i,onCheckedChange:x=>l("display",x)})]}),((a==null?void 0:a.display)??i)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:(a==null?void 0:a.position)||o,onValueChange:x=>l("position",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:u.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(a==null?void 0:a.align)||c,onValueChange:x=>l("align",x),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(x=>e.jsx(t.SelectItem,{value:x,className:"text-xs",children:t.titleCase(x)},x))})]})]})]})]})})]})}function rl(){var L,F,f,k,w,V,O;const s=t.useEditorStore(P=>P.card),n=De.useEffectiveEditorCardType(),a=t.useEditorStore(P=>{var _,z;return(z=(_=P.card)==null?void 0:_.preferences)==null?void 0:z.dataLabelsConfig}),r=t.useEditorStore(P=>{var _;return(_=P.card)==null?void 0:_.preferences}),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((L=r==null?void 0:r.bulletConfig)==null?void 0:L.orientation)??(((F=r==null?void 0:r.chartOptions)==null?void 0:F.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=o!=null?o==="horizontal":((f=r==null?void 0:r.chartOptions)==null?void 0:f.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",u=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=n==="bubble"||n==="scatter",x=(w=(k=r==null?void 0:r.chartOptions)==null?void 0:k.plugins)==null?void 0:w.datalabels,h=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),m=t.getDefaultDataLabelsConfig(n,s.preferences),g=a??m,v=(m==null?void 0:m.enabled)??h??!1,b=(a==null?void 0:a.enabled)!==void 0?a.enabled:v,S=(P,_)=>{const Y={...m??{},...a??{},[P]:_};P==="enabled"&&(Y.display=_,_&&p&&!Y.position&&(Y.position="bottom")),P==="position"&&p&&(Y.position="bottom"),P==="formatMode"&&_==="inherit"&&(Y.format=void 0,Y.formatOptions=void 0);const $={...s.preferences||{},dataLabelsConfig:Y};d($);const ee={...s,preferences:$};i(ee)},E=(P,_)=>{const z=a??{},Y={...m??{},...z,font:{...z.font||{},[P]:_}},$={...s.preferences||{},dataLabelsConfig:Y};d($);const ee={...s,preferences:$};i(ee)},B=()=>{const P=n;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":c?"right":"top"},C=n!=="treemap"&&n!=="heatmap",A=n!=="treemap",T=B();let D=[];if(C)if(p)D=["bottom"];else if(l||u)D=["center"];else{const P=c?["center","left","right"]:["center","top","bottom"];D=["auto",...n==="bullet"?P:P.filter(z=>z!==T),"custom"]}const I=()=>t.titleCase(T),M=["center","start","end"],j=["center","start","end","top","bottom"],R=(g==null?void 0:g.formatMode)||(g!=null&&g.format&&!["auto"].includes(g.format)?"override":"inherit"),y=(g==null?void 0:g.format)==="none";return e.jsxs(t.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(t.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(Mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(t.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(t.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(t.Switch,{size:"sm",checked:b,onCheckedChange:P=>S("enabled",P)})]}),b&&e.jsxs(e.Fragment,{children:[C&&!l&&!u&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:p?(g==null?void 0:g.position)||"bottom":(g==null?void 0:g.position)||"auto",onValueChange:P=>S("position",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:D.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:P==="auto"?I():P==="custom"?"Custom (Advanced)":t.titleCase(P)},P))})]})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(t.Switch,{size:"sm",checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:P=>S("showTotal",P)})]}),(g==null?void 0:g.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(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(t.Select,{value:(g==null?void 0:g.anchor)||"center",onValueChange:P=>S("anchor",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:M.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:t.titleCase(P)},P))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(t.Select,{value:String((g==null?void 0:g.align)||"center"),onValueChange:P=>S("align",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:j.map(P=>e.jsx(t.SelectItem,{value:P,className:"text-xs",children:t.titleCase(P)},P))})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from the bound metric."})]}),e.jsx(t.Switch,{size:"sm",checked:R==="override",onCheckedChange:P=>S("formatMode",P?"override":"inherit")})]}),R==="override"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Raw Value"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Show the unformatted numeric value."})]}),e.jsx(t.Switch,{size:"sm",checked:y,onCheckedChange:P=>{const _=a??{},U={...m??{},..._,formatMode:"override",format:P?"none":void 0,formatOptions:P?void 0:_.formatOptions},Y={...s.preferences||{},dataLabelsConfig:U};d(Y),i({...s,preferences:Y})}})]}),!y&&e.jsx(jt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:P=>{const U={...m??{},...a??{},formatMode:"override",format:P.type&&P.type!=="auto"?P.type:void 0,formatOptions:P},Y={...s.preferences||{},dataLabelsConfig:U};d(Y),i({...s,preferences:Y})},showTitle:!1})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((V=g==null?void 0:g.font)==null?void 0:V.size)||12),onSave:P=>E("size",Number(P)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(t.Select,{value:((O=g==null?void 0:g.font)==null?void 0:O.weight)||"normal",onValueChange:P=>E("weight",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(t.Select,{value:(g==null?void 0:g.color)==="auto"||!(g!=null&&g.color)?"auto":"custom",onValueChange:P=>{P==="auto"&&S("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(He,{type:"number",placeholder:"0",value:String((g==null?void 0:g.rotation)||0),onSave:P=>S("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const ja={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%
193
- 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 ll(){var h,m,g,v,b,S,E,B,C,A;const s=t.useEditorStore(T=>T.card),{setCardPreferences:n}=t.useEditorActions(),a=De.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],d=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&d.length===0,o=r.some(T=>T.comparisonType&&T.comparisonType!=="none");if(!(a==="kpi"&&(i||o)))return null;const l=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},u=T=>{var I;const D={...s.preferences,kpiVisualOptions:{...(I=s.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...l,...T}}};n(D)},p=o||l.enabled,x=r.some(T=>T.comparisonType==="previous_period"||T.comparisonType==="same_period_last_year"||T.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.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(Ia,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[i&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:T=>u({enabled:T,...T&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&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(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const T=l.calculationType||"difference",D=ja[T];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.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:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(t.Select,{value:l.calculationType||"difference",onValueChange:T=>u({calculationType:T}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(ja).map(([T,D])=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:D.label},T))})]})]}),e.jsx(jt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:T=>u({formatOptions:T}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:l.position||"right",onValueChange:T=>u({position:T}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:T=>u({showArrow:T})}),e.jsx(t.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(t.Checkbox,{id:"show-color",checked:l.showColor!==!1,onCheckedChange:T=>u({showColor:T})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(nt,{value:((b=l.colorConfig)==null?void 0:b.increase)||"green",onChange:T=>u({colorConfig:{...l.colorConfig,increase:T}}),label:"Primary > Secondary"}),e.jsx(nt,{value:((S=l.colorConfig)==null?void 0:S.decrease)||"red",onChange:T=>u({colorConfig:{...l.colorConfig,decrease:T}}),label:"Primary < Secondary"}),e.jsx(nt,{value:((E=l.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:T=>u({colorConfig:{...l.colorConfig,noChange:T}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:l.conditionalLabel||!1,onCheckedChange:T=>u({conditionalLabel:T})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((B=l.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,increase:T.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=l.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,decrease:T.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((A=l.conditionalLabels)==null?void 0:A.noChange)??"No change",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,noChange:T.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:l.labelName??"",onChange:T=>u({labelName:T.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ol(){var i;const s=t.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.type}),n=t.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.preferences}),{setCardPreferences:a}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=n==null?void 0:n.chartOptions)==null?void 0:i.treemapColorMode)??"branch",d=o=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(c)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.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(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:o=>d(o??"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(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.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(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.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."})]})]})]})})]})}const il=Object.keys(t.HEATMAP_PRESET_PALETTES);function cl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",d=(n==null?void 0:n.heatmapConfig)||{},i=d.colorPalette??"green",o=d.legendPosition??"bottom",c=N.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),l=h=>{const m={...d,...h};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:m})},u=h=>{l({colorPalette:h,colorRange:h==="custom"?d.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(h,m)=>{const g=[...c];g[h]=m,l({colorPalette:"custom",colorRange:g})},x=h=>{l({legendPosition:h})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.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(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:i,onValueChange:h=>u(h??"blue"),className:"space-y-3",children:[il.map(h=>{const m=t.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},h)}),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(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(nt,{value:c[0],onChange:h=>p(0,h),label:"Start color"}),e.jsx(nt,{value:c[1],onChange:h=>p(1,h),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:o,onValueChange:h=>x(h??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const ba=["poor","satisfactory","good"];function va(s){if(!s)return;const n={...s};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 dl(){var L,F;const s=t.useEditorStore(f=>f.card.preferences),n=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:d}=t.useEditorActions(),i=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,u]=N.useState(i.showRanges??!1),[p,x]=N.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c,[m,g]=N.useState(h);N.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),N.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);N.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,c]);const b=N.useMemo(()=>{var f,k;return((k=(f=n==null?void 0:n.config)==null?void 0:f.metricColumns)==null?void 0:k.map(w=>{const V=w.label||w.name||w.alias||"";return{value:V,label:V}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]);N.useEffect(()=>{var z,U;if(!s||b.length===0)return;const f={};let k=!1;const w=(z=b[1])==null?void 0:z.value;!i.targetMetricKey&&w&&(f.targetMetricKey=w,k=!0);const V=(U=b[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(f.comparativeMetricKey=V,k=!0);const O=b.slice(3),P={...i.rangeKeys||{}};let _=!1;if(ba.forEach((Y,$)=>{!P[Y]&&O[$]&&(P[Y]=O[$].value,_=!0)}),_&&(f.rangeKeys=P,k=!0,i.showRanges===void 0&&(f.showRanges=!0)),k){const Y=va({...i,...f});r({...s,bulletConfig:Y})}},[b,i,s,r]);const S=f=>{const k=va({...i,...f});r({...s,bulletConfig:k})},E=(f,k)=>{const w={...i.rangeKeys||{},[f]:k.trim()};k.trim()||delete w[f],S({rangeKeys:Object.keys(w).length>0?w:void 0})},B=(f,k)=>{const w=k===""?void 0:Number(k),V={...i.ranges||{}};w===void 0||Number.isNaN(w)?delete V[f]:V[f]=w,S({ranges:Object.keys(V).length?V:void 0})},C=f=>{if(f===""){S({targetValue:void 0});return}const k=Number(f);S({targetValue:Number.isNaN(k)?void 0:k})},A=(f,k)=>{const w=k.trim(),V={...i.rangeLabels||{}};w?V[f]=w:delete V[f],S({rangeLabels:Object.keys(V).length>0?V:void 0})},T=f=>{u(f),S({showRanges:f})},D=f=>{x(f),S({rangesArePercentages:f})},I=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),M=f=>{S({orientation:f}),d(f==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(f=>({value:f.value,label:f.label}))],R=j,y=f=>{if(g(f),!f){S({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){S({disableAutoComparative:!1});return}if(i.comparativeMetricKey)S({disableAutoComparative:!1});else{const k=b.find(w=>w.value!==i.targetMetricKey);S({comparativeMetricKey:k==null?void 0:k.value,disableAutoComparative:!1})}};return e.jsxs(t.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(t.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(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:I,onValueChange:f=>M(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:f=>S({targetMetricKey:f==="__none"?void 0:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),b.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>S({comparativeMetricKey:f==="__none"?void 0:f,disableAutoComparative:f==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:j.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.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(t.Switch,{size:"sm",checked:m,onCheckedChange:f=>y(f)})]}),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(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(qe,{type:"number",className:"h-8 text-xs",value:v,onCommit:C,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(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.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(t.Switch,{size:"sm",checked:l,onCheckedChange:T})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:f=>D(f.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:ba.map(f=>{var k,w,V,O,P;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(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," LABEL"]}),e.jsx(qe,{placeholder:`Display label (${f})`,value:((k=i.rangeLabels)==null?void 0:k[f])||"",onCommit:_=>A(f,_),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((w=i.rangeKeys)==null?void 0:w[f])||"__none",onValueChange:_=>{_==="__none"?E(f,""):E(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:R.map(_=>e.jsx(t.SelectItem,{value:_.value,className:"text-xs",children:_.label},_.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN KEY"]}),e.jsx(qe,{placeholder:"Column key",value:((V=i.rangeKeys)==null?void 0:V[f])||"",onCommit:_=>E(f,_),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," VALUE"]}),e.jsx(qe,{type:"number",placeholder:p?"0.80":"Static value",value:((O=i.ranges)==null?void 0:O[f])===void 0?"":String((P=i.ranges)==null?void 0:P[f]),onCommit:_=>B(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ya(s){if(!s)return;const n={...s};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 ul(){var A,T,D,I,M,j,R,y,L,F,f,k;const s=t.useEditorStore(w=>w.card.preferences),n=t.useEditorStore(w=>w.card),a=De.useEffectiveEditorCardType(),r=t.useEditorStore(w=>w.isDevMode),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions(),o=a==="bubble",c=a==="scatter",l=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=N.useMemo(()=>{var w,V;return((V=(w=n==null?void 0:n.config)==null?void 0:w.metricColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(A=n==null?void 0:n.config)==null?void 0:A.metricColumns]),h=N.useMemo(()=>{var w,V;return((V=(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.groupByColumns]),m=N.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&h.length>=2,[l.enableGrouping,r,h.length]),[g,v]=N.useState(m);N.useEffect(()=>{v(m)},[m]);const b=w=>{const V={...s||{},bubbleScatterConfig:w};d(V),n&&i({...n,preferences:V})},S=w=>{d(w),n&&i({...n,preferences:w})};N.useEffect(()=>{if(!s||x.length===0)return;const w={};let V=!1;if(!l.xMetricKey&&x[0]&&(w.xMetricKey=x[0].value,V=!0),!l.yMetricKey&&x[1]&&(w.yMetricKey=x[1].value,V=!0),o&&!l.radiusMetricKey&&x[2]&&(w.radiusMetricKey=x[2].value,V=!0),!l.labelKey&&h[0]&&(w.labelKey=h[0].value,V=!0),m&&!l.groupKey&&h[1]&&(w.groupKey=h[1].value,w.enableGrouping=!0,V=!0),V){const O=ya({...l,...w});b(O)}},[x,h,l,s,d,o,m]);const E=w=>{const V=ya({...l,...w});b(V)},B=w=>{v(w),E({enableGrouping:w,groupKey:w?l.groupKey:void 0})};if(!o&&!c)return null;const C=o?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.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(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.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(t.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(t.Select,{value:l.labelKey||"",onValueChange:w=>E({labelKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:w=>E({labelKey:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:l.groupKey||"",onValueChange:w=>E({groupKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:w=>E({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(t.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(t.Select,{value:l.xMetricKey||"",onValueChange:w=>E({xMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:w=>E({xMetricKey:w})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:l.yMetricKey||"",onValueChange:w=>E({yMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:w=>E({yMetricKey:w})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:l.radiusMetricKey||"",onValueChange:w=>E({radiusMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:w=>E({radiusMetricKey:w})})]})]}),o&&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(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:l.radiusScale||"sqrt",onValueChange:w=>E({radiusScale:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.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(t.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=l.minRadius)==null?void 0:D.toString())||"",onCommit:w=>E({minRadius:w?Number(w):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((I=l.maxRadius)==null?void 0:I.toString())||"",onCommit:w=>E({maxRadius:w?Number(w):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(t.Slider,{value:[l.fixedRadius||10],onValueChange:([w])=>E({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(t.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(t.Slider,{value:[l.fixedRadius||5],onValueChange:([w])=>E({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(t.Switch,{size:"sm",checked:((j=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:j.enabled)??!1,onCheckedChange:w=>{var P,_,z,U;const V=l.xMetricKey||"X Axis",O=l.yMetricKey||"Y Axis";S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:w,text:((_=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:_.text)||V}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:w,text:((U=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:U.text)||O}}})}})]}),((y=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx(qe,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((F=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:F.text)||"",onCommit:w=>{var V;S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:w||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(qe,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((k=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:k.text)||"",onCommit:w=>{var V;S({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:w||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const ml=[{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 xl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",d=(n==null?void 0:n.funnelConfig)||{},i=d.percentMode??"percentOfTotal",o=d.shrinkFraction??1,c=d.labelThreshold??0,l=h=>{const m={...d,...h};a({...n||{},funnelConfig:m})},u=h=>{l({percentMode:h})},p=h=>{l({shrinkFraction:h[0]})},x=h=>{l({labelThreshold:h[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.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(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:i,onValueChange:h=>u(h),className:"space-y-2",children:ml.map(h=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[c],onValueChange:x,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function qt(){const s=t.useEditorStore(i=>i.card),{data:n}=t.useDashboardCardQuery(s),{keys:a}=t.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let d=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=t.getKeys(i);d=o.slice(1)}return{transformedMetricKeys:d,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const hl=[{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"}],pl=[{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)"}],fl=["center","start","end"],gl=["center","start","end","top","bottom"];function $t({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:d,showAppearance:i=!0}){var g,v,b,S,E,B;const o=d??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(C,A)=>{const T={...s,[C]:A};n(T)},u=(C,A)=>{const T={...s,font:{...(s==null?void 0:s.font)||{},[C]:A}};n(T)},p=(C,A)=>{const T={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:A}};n(T)},x=()=>a?"Right":"Top",h=s||{},m=h.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:h.position||"auto",onValueChange:C=>l("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?x():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),h.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:h.anchor||"center",onValueChange:C=>l("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(h.align||"center"),onValueChange:C=>l("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:gl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:C=>l("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&r?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"0",value:String(((g=h.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:C=>p("decimalPlaces",Number(C)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((v=h.formatOptions)==null?void 0:v.currency)||"USD",onValueChange:C=>p("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((b=h.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:C=>p("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((S=h.formatOptions)==null?void 0:S.locale)||"en-US",onValueChange:C=>p("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((E=h.font)==null?void 0:E.size)||12),onSave:C=>u("size",Number(C)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((B=h.font)==null?void 0:B.weight)||"normal",onValueChange:C=>u("weight",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:h.color==="auto"||!h.color?"auto":"custom",onValueChange:C=>{C==="auto"&&l("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(He,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:C=>l("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const jl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],bl=[0,1,2,3,4,5,6,8,10],vl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],yl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Nl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(t.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Cl,{})})]})}function Cl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Sl,{metricKey:n,idx:a},n))})}function Sl({metricKey:s,idx:n}){var S;const[a,r]=N.useState(!1),d=t.useEditorStore(E=>{var B;return(B=E.card)==null?void 0:B.preferences}),i=t.useEditorStore(E=>{var B,C;return(C=(B=E.card)==null?void 0:B.preferences)==null?void 0:C.datasetOptions}),o=i==null?void 0:i.find(E=>E.idx===n),{setCardPreferences:c}=t.useEditorStore(E=>E.actions),l=(o==null?void 0:o.type)||"bar",u=(o==null?void 0:o.yAxisId)||"y",p=((S=o==null?void 0:o.dataLabels)==null?void 0:S.enabled)??!1,x=l==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const B={idx:n,type:l,yAxisId:u,dataLabels:o==null?void 0:o.dataLabels,...E};if(!o)c({...d||{},datasetOptions:[...i||[],B]});else{const C=i==null?void 0:i.map(A=>A.idx===n?{...A,...B}:A);c({...d||{},datasetOptions:C})}}function m(E){h({type:E})}function g(E){h({yAxisId:E})}function v(E){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:E}})}function b(E){h({dataLabels:E})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(x,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:u==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:jl.map(({type:E,icon:B,label:C})=>{const A=l===E;return e.jsxs("button",{onClick:()=>m(E),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",A?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:C})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:u,onValueChange:E=>g(E),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:E=>h({lineStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:E=>h({pointRadius:Number(E)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(E=>e.jsx(t.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:E=>h({pointStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:p,onCheckedChange:v})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ns=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],wl=[0,1,2,3,4,5,6,8,10],Tl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],El=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Il(s){return s==null?"origin":s===!1?"false":s}function Dl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(t.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(kl,{})})]})}function kl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Al,{metricKey:n,idx:a},n))})}function Al({metricKey:s,idx:n}){var v;const[a,r]=N.useState(!1),d=t.useEditorStore(b=>{var S;return(S=b.card)==null?void 0:S.preferences}),i=t.useEditorStore(b=>{var S,E;return(E=(S=b.card)==null?void 0:S.preferences)==null?void 0:E.datasetOptions}),o=i==null?void 0:i.find(b=>b.idx===n),{setCardPreferences:c}=t.useEditorStore(b=>b.actions),l=Il(o==null?void 0:o.fill),u=((v=o==null?void 0:o.dataLabels)==null?void 0:v.enabled)??!1,p=ns.find(b=>b.value===l)||ns[0];function x(b){const S={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...b};if(!o)c({...d||{},datasetOptions:[...i||[],S]});else{const E=i==null?void 0:i.map(B=>B.idx===n?{...B,...S}:B);c({...d||{},datasetOptions:E})}}function h(b){x({fill:b==="false"?!1:b})}function m(b){x({dataLabels:{...o==null?void 0:o.dataLabels,enabled:b}})}function g(b){x({dataLabels:b})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:l,onValueChange:b=>h(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ns.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:b=>x({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:b=>x({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:b=>x({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},b))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:u,onCheckedChange:m})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ml=[0,1,2,3,4,5,6,8,10],Ll=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Fl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(t.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Rl,{})})]})}function Rl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Ol,{metricKey:n,idx:a},n))})}function Ol({metricKey:s,idx:n}){var b;const[a,r]=N.useState(!1),d=t.useEditorStore(S=>{var E;return(E=S.card)==null?void 0:E.preferences}),i=t.useEditorStore(S=>{var E,B;return(B=(E=S.card)==null?void 0:E.preferences)==null?void 0:B.datasetOptions}),o=i==null?void 0:i.find(S=>S.idx===n),{setCardPreferences:c}=t.useEditorStore(S=>S.actions),l=(o==null?void 0:o.lineStyle)||"solid",u=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",x=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,h=rs.find(S=>S.value===l)||rs[0];function m(S){const E={idx:n,lineStyle:l,pointRadius:u,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...S};if(!o)c({...d||{},datasetOptions:[...i||[],E]});else{const B=i==null?void 0:i.map(C=>C.idx===n?{...C,...E}:C);c({...d||{},datasetOptions:B})}}function g(S){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:S}})}function v(S){m({dataLabels:S})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.TrendingUp,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:l,onValueChange:S=>m({lineStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rs.map(({value:S,label:E})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:E},S))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(u),onValueChange:S=>m({pointRadius:Number(S)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(S=>e.jsx(t.SelectItem,{value:String(S),className:"text-xs",children:S===0?"None":S},S))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:S=>m({pointStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(({value:S,label:E})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:E},S))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Pl=[0,2,4,6,8,10,12,16,20];function Bl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(t.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Vl,{})})]})}function Vl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(zl,{metricKey:n,idx:a},n))})}function zl({metricKey:s,idx:n}){var g;const[a,r]=N.useState(!1),d=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.type}),i=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),o=t.useEditorStore(v=>{var b,S;return(S=(b=v.card)==null?void 0:b.preferences)==null?void 0:S.datasetOptions}),c=o==null?void 0:o.find(v=>v.idx===n),{setCardPreferences:l}=t.useEditorStore(v=>v.actions),u=(c==null?void 0:c.borderRadius)??0,p=((g=c==null?void 0:c.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const b={idx:n,borderRadius:u,dataLabels:c==null?void 0:c.dataLabels,...v};if(!c)l({...i||{},datasetOptions:[...o||[],b]});else{const S=o==null?void 0:o.map(E=>E.idx===n?{...E,...b}:E);l({...i||{},datasetOptions:S})}}function h(v){x({dataLabels:{...c==null?void 0:c.dataLabels,enabled:v}})}function m(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:u>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",u]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(u),onValueChange:v=>x({borderRadius:Number(v)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(v=>e.jsx(t.SelectItem,{value:String(v),className:"text-xs",children:v===0?"None":`${v}px`},v))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:c==null?void 0:c.dataLabels,onChange:m,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _l=[0,1,2,3,4,5,6,8,10],ql=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],$l=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Kl(){const s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const o=(c,l)=>{const u={...n||{},lineStyleConfig:{...r,[c]:l}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.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(Dn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>o("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>o("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>o("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}const Gl=[0,2,4,6,8,10,12,16,20],Ul=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Hl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Ql(){const s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(c,l)=>{const u={...n||{},barStyleConfig:{...r,[c]:l}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.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(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>o("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>o("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>o("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}function Jl(){const s=t.useEditorStore(a=>{var r,d;return(d=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(at,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:a=>{n(a)}})]})})]})}const Yl=["kpi"],Na={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ls=2;function lt(s){return typeof s=="string"?s.trim().toLowerCase():((s==null?void 0:s.id)||(s==null?void 0:s.qualifiedFieldName)||(s==null?void 0:s.name)||(s==null?void 0:s.label)||"").trim().toLowerCase()}function Wl(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Xl(s){return{...s,role:"groupby"}}function Zl(){var E,B;const s=t.useEditorStore(C=>C.card),n=t.useEditorStore(C=>C.actions.updateCardConfig),a=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),d=((E=s.config)==null?void 0:E.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},o=i.breakdownDimensions||[],c=Yl.includes(a),l=d.length>0,u=i.enabled===!0,p=c&&l,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),h=Na[x]||Na.none,m=Array.from(new Map(r.filter(Wl).map(C=>[lt(C),Xl(C)])).values()),g=new Set(m.map(C=>lt(C))),v=new Set(o.map(C=>lt(C)).filter(C=>C&&g.has(C)));if(!c)return null;const b=C=>{n(s.id,{summary:{...i,...C}})},S=(C,A)=>{const T=lt(C),D=m.filter(M=>v.has(lt(M))),I=A?v.has(T)?D:[...D,C].slice(0,ls):D.filter(M=>lt(M)!==T);b({breakdownDimensions:I})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.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(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:u,disabled:!p,onCheckedChange:C=>{if(!C){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",h]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!u,onCheckedChange:C=>b({showOnCard:C})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!u,onCheckedChange:C=>b({includeInDashboardSummary:C})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",ls]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(C=>{const A=lt(C),T=v.has(A),D=v.size>=ls,I=!u||!T&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${A}`,checked:T,disabled:I,onCheckedChange:M=>S(C,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${A}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},A)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!u,onCheckedChange:C=>b({anomalyEnabled:C})})]})]})]})}const eo=[];function to(){var d;const s=t.useEditorStore(i=>i.card),n=((d=s==null?void 0:s.config)==null?void 0:d.metricColumns)??eo,{updateMetricColumn:a,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||n.length===0?null:e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(t.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(hn,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:n.map(i=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:i.label||i.name}),e.jsx(hs,{value:i.format,onChange:o=>{var c;a(s.id,i.id,{format:o}),r({...s,config:{...s.config,metricColumns:(((c=s.config)==null?void 0:c.metricColumns)||[]).map(l=>l.id===i.id?{...l,format:o}:l)}})}})]},i.id))})]})}const so=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function ao(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions();if(!s||!so.has(a||""))return null;const i=n==null?void 0:n.tooltipConfig,o=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",c=l=>{const u={...n||{},tooltipConfig:{...i||{},...l}};r(u),d({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.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(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.Switch,{size:"sm",checked:o==="override",onCheckedChange:l=>c({formatMode:l?"override":"inherit",mode:l?"override":"inherit"})})]}),o==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:l=>c({formatMode:"override",mode:"override",formatOptions:l}),showTitle:!1})]})]})}function $a({mode:s}){const n=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(Nl,{}),(n==="area"||n==="stackedArea")&&e.jsx(Dl,{}),n==="line"&&e.jsx(Fl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Bl,{}),e.jsx(Kl,{}),e.jsx(Ql,{}),e.jsx(ol,{}),s==="config"&&e.jsx(ll,{}),s==="config"&&e.jsx(Zl,{}),e.jsx(cl,{}),n==="bullet"&&e.jsx(dl,{}),n==="funnel"&&e.jsx(xl,{}),(n==="bubble"||n==="scatter")&&e.jsx(ul,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Jl,{}),e.jsx(to,{}),e.jsx(sl,{}),e.jsx(al,{}),e.jsx(nl,{}),e.jsx(rl,{}),e.jsx(ao,{})]})}function no(){const s=t.useEditorStore(a=>a.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:n}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx($a,{mode:"dev"})})]}):null}function ro(){const s=t.useEditorStore(d=>d.card),n=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(t.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(t.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(t.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function r(){switch(n){case"kpi":return e.jsx(Or,{});case"table":return e.jsx(Xr,{});case"map":return e.jsx(zr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Va,{})});case"text":return e.jsx(el,{});default:return e.jsx(no,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function lo(){const s=N.useRef(null),n=N.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),d=t.useEditorStore(x=>x.showAIDialog),[i,o]=N.useState(!1),c=a&&!d,l=c&&(!r||i),u=r&&c,p=()=>o(x=>!x);return N.useEffect(()=>{var x,h,m,g;d?((x=s.current)==null||x.resize(0),(h=n.current)==null||h.resize(0)):((m=s.current)==null||m.resize(25),(g=n.current)==null||g.resize(25))},[d]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Zn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(ro,{})})}),!d&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function oo(s){var Ee;t.useAIInteractionStore(K=>K.currentAIContext);const[n,a]=N.useState(""),[r,d]=N.useState(null),{authToken:i,tokenProps:o}=t.useSemaphorContext(),c=t.useEditorStore(K=>K.card.id),l=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.sql}),u=t.useEditorStore(K=>K.isDevMode),p=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.python}),{setCardPython:x,setCardSql:h,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],S=t.useEditorStore(K=>K.userInputForAI),E=t.useEditorStore(K=>K.triggerAIRun),B=t.useEditorStore(K=>K.card),C=t.useEditorStore(K=>K.selectedDatabaseName),A=t.useEditorStore(K=>K.selectedTableName),T=t.useEditorStore(K=>K.selectedConnectionId),D=t.useEditorStore(K=>K.selectedSchemaName),I=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:M,refetch:j,data:R}=t.useDashboardCardQuery(B),{setTriggerAIRun:y,setCurrentAssitantScope:L,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:k,selectedDatamodelId:w}=t.useEditorAside(),V=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,O=N.useRef(t.createAssistantConversationId()),P=N.useRef(null),_=N.useRef(c),z=N.useRef(!1),U=()=>{const K=P.current;K&&(P.current=null,O.current=t.createAssistantConversationId(),K==="clear"&&$([]))},{messages:Y,setMessages:$,regenerate:ee,error:ne,sendMessage:me,status:ve,addToolResult:se,stop:re,clearError:de}=t.useChat({transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:O.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var le;if(z.current=!1,K.name==="AbortError"||(le=K.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",K),U()},onToolCall:ue,onFinish({isAbort:K,isDisconnect:le,isError:Ne}){z.current=!1,a(""),console.log(K?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":Ne?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),pe=N.useCallback(K=>{z.current=!0;try{const le=me(K);return t.isPromiseLike(le)?le.catch(Ne=>{throw z.current=!1,Ne}):le}catch(le){throw z.current=!1,le}},[me]),X=N.useCallback(()=>{z.current=!0;try{const K=ee();return t.isPromiseLike(K)?K.catch(le=>{throw z.current=!1,le}):K}catch(K){throw z.current=!1,K}},[ee]),Z=K=>{let le=!1;$(Ne=>{const Pe=typeof K=="function"?K(Ne):K;if(Pe.length===0){if(z.current)return P.current="clear",le=!0,Ne;P.current=null,O.current=t.createAssistantConversationId()}return Pe}),le&&re()};N.useEffect(()=>{if(_.current!==c){if(_.current=c,z.current){P.current!=="clear"&&(P.current="rotate"),re();return}P.current=null,O.current=t.createAssistantConversationId()}},[c,re]),N.useEffect(()=>{E&&S&&(pe({role:"user",parts:[{type:"text",text:S}]}),y(!1))},[E,S,pe,y]);async function ue({toolCall:K}){var le,Ne,Pe,W,fe,Ce,ke,Se,Be,ze,Xe,Ye,We,ae,Ie,Oe;if(["createChartFromSql","createForecast"].includes(K.toolName)){const be=((le=K.input)==null?void 0:le.sql)??((Ne=K.args)==null?void 0:Ne.sql),Ge=((Pe=K.input)==null?void 0:Pe.python)??((W=K.args)==null?void 0:W.python),Te=((fe=K.input)==null?void 0:fe.chartType)??((Ce=K.args)==null?void 0:Ce.chartType);g(Te),h(be),x(Ge),m(!0),se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!l){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:l,python:p||""}})}else if(K.toolName==="generateQueryConfig"){a("Generating query config...");const be=((ke=K.input)==null?void 0:ke.chartType)??((Se=K.args)==null?void 0:Se.chartType),Ge=((Be=K.input)==null?void 0:Be.queryConfig)??((ze=K.args)==null?void 0:ze.queryConfig);((Xe=K.input)==null?void 0:Xe.cardConfig)??((Ye=K.args)==null||Ye.cardConfig),g(be),F(Ge),h(void 0),x(void 0);const Te=await j();if((We=Te==null?void 0:Te.data)!=null&&We.error){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:Ge,message:(ae=Te==null?void 0:Te.data)==null?void 0:ae.error.message}});return}if((Ie=Te==null?void 0:Te.data)!=null&&Ie.records){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Oe=Te==null?void 0:Te.data)==null?void 0:Oe.records}})}else a("Analyzing...")}function Fe(K){const le=t.removeFromScopeArray(b,K);te(le)}function te(K){const le=t.sanitizeAIScope(K);L(le),$(Ne=>[...Ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(le)}`}]}])}function ge(){const K={databaseName:C||"",schemaName:D||"",tableName:A||"",datamodelId:w||"",datamodelName:t.resolveDatamodelName(f),connectionId:T||"",connectionType:k||""},le=t.dedup([...b,K]);te(le)}function ye(){const K={databaseName:C||"",schemaName:D||"",tableName:A||"",datamodelName:t.resolveDatamodelName(f),connectionId:T||"",connectionType:k||"",datamodelId:w||""};if(!t.isInAiScopeArray([...I||[],...b],K)||b.length===0){const Ne=t.dedup([...I||[],...b,K]).filter(Pe=>Pe.connectionId===K.connectionId);te(Ne)}}const je=!["ready","error"].includes(ve),we=t.getErrorMessage(ne);return{messages:Y,setMessages:Z,sendMessage:pe,regenerate:X,isLoading:je,handleSetAIScope:ye,handleAddCurrentTableToScope:ge,removeFromCurrentSelections:Fe,currentAssitantScope:b,setCurrentAssitantScope:L,stop:re,status:ve,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:we,clearError:de}}const io=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ca({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=N.useRef(null),d=N.useRef(!1),[i,o]=N.useState(!1),[c,l]=N.useState(t.isDevEnv),[u,p]=N.useState(!1),[x,h]=N.useState(!1),[m,g]=N.useState(!1),v=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:S,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:C}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:T}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),M=t.useEditorStore(ae=>{var Ie;return(Ie=ae.card.dataSource)==null?void 0:Ie.selectedEntities}),j=t.useEditorStore(ae=>ae.actions.setCardSql),R=t.useEditorStore(ae=>ae.actions.setRunSql),y=t.useEditorStore(ae=>ae.showAIDialog),L=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:k}=t.useEditorActions(),{assistantProfile:w}=t.useAssistantProfile(),{messages:V,setMessages:O,sendMessage:P,isLoading:_,stop:z,status:U,llmUsage:Y,errorMessage:$,clearError:ee}=oo(),[ne,me]=N.useState(""),ve=ae=>{me(ae.target.value)},se=ae=>{ae.preventDefault();const Ie=ne.trim();if(!Ie&&A.length===0)return;const Oe=[];Ie&&Oe.push({type:"text",text:Ie}),A.forEach(be=>{be.data&&Oe.push({type:"file",mediaType:be.type,filename:be.name,url:`data:${be.type};base64,${be.data}`})}),P({role:"user",parts:Oe}),me(""),C("editor"),je({force:!0})},{visibleMessages:re,hasMoreMessages:de,totalMessageCount:pe,loadMoreMessages:X,resetMessageWindow:Z}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ue,contentRef:Fe,isAtBottom:te,hasNewMessages:ge,newMessageCount:ye,scrollToBottom:je,handleScroll:we,resetNewMessageCount:Ee}=t.useAutoScroll(re,{threshold:40,behavior:"smooth",isStreaming:_});N.useEffect(()=>{var ae;y&&!d.current&&((ae=r.current)==null||ae.focus()),d.current=y},[y]),N.useEffect(()=>{y&&(E(!1),S({selectedEntities:M||[]}))},[D,M,S,E,y]),t.useAutoSubmitQueue({assistantType:"editor",status:U,isLoading:_,sendMessage:P});const{hasActiveTools:K,activeToolText:le}=t.useActiveToolStatus(V),Ne=N.useCallback(ae=>{n==null||n(ae),s===void 0&&g(ae)},[s,n]);N.useEffect(()=>{if(!v)return;function ae(Ie){Ie.key==="Escape"&&Ne(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[v,Ne]);const Pe=N.useCallback(ae=>{P({role:"user",parts:[{type:"text",text:ae}]}),je({force:!0})},[P,je]),W=N.useCallback(async()=>{const ae=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[V]),fe=N.useCallback(()=>{Ne(!v)},[v,Ne]);function Ce(ae,Ie){Ie==="sql"?(j(ae),R(!0)):Ie==="python"&&(f(ae),R(!0))}function ke(){b.selectedEntities.length===0&&S({selectedEntities:T})}function Se(ae){ke();const Ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};P(Ie)}function Be(ae){ke(),P({role:"user",parts:[{type:"text",text:ae}]})}function ze(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:o,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function Xe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ye=(ne==null?void 0:ne.length)===0&&(V==null?void 0:V.filter(ae=>ae.role==="user").length)===0,We=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",v&&"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:[Xe(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(w==null?void 0:w.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[ze(),c&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:W,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:fe,children:v?e.jsx(t.Minimize2,{className:"size-4"}):e.jsx(t.Maximize2,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{O([]),B("editor"),ee(),Z()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:ue,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:we,children:e.jsxs("div",{ref:Fe,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[de&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:X,className:"text-xs",children:["Load ",Math.min(5,pe-re.length)," ","more messages (",pe-re.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:re,showTools:c,handleRun:Ce,showSystemMessage:u,onQuickReply:Pe,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:U,errorMessage:$,activeToolText:_&&K?le:void 0})]})}),y&&!te&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{je({force:!0}),Ee()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),ge&&ye>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:ye>9?"9+":ye})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ye&&!w&&e.jsx(t.Placeholders,{onClick:Se,placeholders:io}),e.jsx("div",{children:Ye&&w&&e.jsx(t.SeedQuestions,{seedQuestions:w.seedQuestions||[],handleSeedQuestionClick:Be})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:me,stop:z,input:ne,handleInputChange:ve,handleSubmit:ae=>{ke(),se(ae),je({force:!0})},isLoading:_,status:U,assistantType:"editor",onFocus:()=>{}})]}),Y&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",Y.inputTokens," prompt tokens, ",Y.outputTokens," ","completion tokens, ",Y.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:T,open:x,onOpenChange:h,dataSource:I||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{E(!0),S({...b,selectedEntities:ae})}})]});return v&&a?cn.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:We})}),a):We}function co(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,d=n.qualifiedEntityName,i=d&&n.name?`${d}.${n.name}`:r;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const l=t.getSelectedDateFilterColumn(o,a),u=l.split("."),p=u[u.length-1]||l,x=u.length>1?u.slice(0,-1).join("."):void 0,h=o.qualifiedTableName||x,m=h?`${h}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===n.name:m?m===i:p===n.name})}function uo({aliasTemplate:s,onAliasTemplateChange:n}){var l;const[a,r]=N.useState(s),[d,i]=N.useState(!1),o=(l=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],c=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:d?a:s,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&d&&a!==s?(n(a),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),d&&a!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function mo({valueAliases:s,onValueAliasesChange:n}){const[a,r]=N.useState(null),[d,i]=N.useState(""),[o,c]=N.useState(""),l=()=>{n({...s,"":""})},u=x=>{const h={...s};delete h[x],n(h)},p=x=>{const h={...s};delete h[x],h[d]=o,n(h),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,h],m)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:o,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(h)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function xo({idx:s}){var c;const n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=t.useEditorStore(l=>{var u;return(u=l.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),d=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,i=a==null?void 0:a.find(l=>l.idx===s);function o(l,u){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:p}]});else{const x={...i};x.datalabels=p;const h=a==null?void 0:a.map(m=>m.idx===u?x:m);r({...n,datasetOptions:h})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>o("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function ps({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ho(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function po({col:s,idx:n,className:a,iconClassName:r,children:d}){const i=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),o=t.useEditorStore(p=>{var x,h;return(h=(x=p.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),c=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=t.useEditorStore(p=>p.actions);function u(p){if(!c)l({...i,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...c};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const h=o==null?void 0:o.map(m=>m.idx===n?x:m);l({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[d||e.jsx(ps,{className:"max-w-[100px]",title:s,children:ho(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>u("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>u("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>u("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xo,{idx:n})]})]})}function fo(){const s=t.useEditorStore(c=>c.card.type),n=t.useEditorStore(c=>c.isDevMode),a=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=t.useEditorStore(c=>c.actions);function d(c){var p;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(u)}function i(){var c,l,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.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:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function o(){var c,l,u;return e.jsx("div",{children:e.jsxs(t.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:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?i():o()})}function go({column:s}){const n=t.useEditorStore(l=>l.card.type),a=t.useEditorStore(l=>{var u,p;return(p=(u=l.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],d=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=d?r.indexOf(d):-1;function o(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx(po,{idx:i,col:d,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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(fo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&c()]})}function jo({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:d}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),o=i==null?void 0:i.dataSource,c=["attribute-values",s.entityName,s.name,n,a],l=t.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:o.connectionId,cardConfig:u,cardDataSource:o,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const x=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const v=g[h]||g[s.alias||h]||g[s.label];return{id:v||"",value:v||"",label:String(v||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!s&&!!(o!=null&&o.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 Ka({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:d,onSave:i}){var B,C;const o=!!d,[c,l]=N.useState(o?"values":"fields"),[u,p]=N.useState(""),[x,h]=N.useState({id:(d==null?void 0:d.id)||t.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),m=a.filter(A=>{var D;return o?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(I=>I.field.id===A.id))&&A.label.toLowerCase().includes(u.toLowerCase())}),g=A=>{h({...x,field:A}),l("values")},v=()=>{if(x.field&&x.selectedValues.length>0){const A={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let T;if(o){const D=((r==null?void 0:r.conditions)||[]).map(I=>I.id===d.id?A:I);T={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];T={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,A],groups:[]}}i(T),n(!1)}},b=()=>{if(!o||!d)return;const A=((r==null?void 0:r.conditions)||[]).filter(T=>T.id!==d.id);if(A.length>0){const T={...r,conditions:A};i(T)}else i(void 0);n(!1)},S=A=>{h({...x,selectedValues:A})},E=()=>{o&&d?(h({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),l("values")):(h({id:t.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return N.useEffect(()=>{s&&E()},[s,o,d]),e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:o?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(C=x.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(A=>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:[A.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(A.value)?`${A.value.length} values`:String(A.value)})]},A.id))})]}),c==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search fields...",value:u,onChange:A=>p(A.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(A=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(A),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(A.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:A.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[A.entityName,".",A.name]})]})]},A.id))}),m.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),m.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(bo,{field:x.field,selectedValues:x.selectedValues,onValuesChange:S,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(t.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:E,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function bo({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[d,i]=N.useState(""),{values:o,isLoading:c,isFetching:l}=jo({field:s,searchQuery:d,limit:500}),u=d?o.filter(h=>String(h.value).toLowerCase().includes(d.toLowerCase())):o,p=h=>{const m=n.includes(h);a(m?n.filter(g=>g!==h):[...n,h])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:d,onChange:h=>i(h.target.value),className:"pl-10"})]}),c||l?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.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(t.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(t.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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(h.value),children:[e.jsx(t.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>p(h.value)}),e.jsx(ps,{className:"text-sm",children:h.label})]},h.id))})]})]})}function vo({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:d,hasPivotColumns:i=!1,cardType:o}){var Ns,Cs,Ss,ws,Ts,Es,Is,Ds,ks,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs,Zs,ea;const{attributes:c,listeners:l,setNodeRef:u,transform:p,transition:x,isDragging:h}=t.useSortable({id:s.id}),m=t.useEditorStore(G=>G.card),g=t.useEditorStore(G=>G.frame),v=t.useDashboardStore(G=>G.isVisualEditing),b=t.useDashboardStore(G=>G.selectedSheetId),S=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:B,isLoading:C}=t.useFilterableFields(),{userContext:A}=t.useCurrentUserInfo(),T=(A==null?void 0:A.type)==="organization",{updateLabel:D,handleAggregationChange:I,handleDateFormatChange:M,handleGranularityChange:j,handleAliasTemplateChange:R,handleValueAliasesChange:y,handleMetricFormatChange:L,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:k,handleMetricWindowOrderByChange:w,handleMetricWindowDirectionChange:V,handleMetricWindowPartitionToggle:O,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:U,handleMetricPercentOfTotalOutputChange:Y,handleKpiShowTrendlineChange:$,handleKpiTrendlineWindowChange:ee,handleKpiTrendlineGranularityChange:ne,handleMetricTargetValueChange:me}=t.useFieldManagement(m),[ve,se]=N.useState(!1),[re,de]=N.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[pe,X]=N.useState(!1),[Z,ue]=N.useState(!1),[Fe,te]=N.useState(null),ge=N.useMemo(()=>{const G=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Q=G(s.id),ce=E.find(oe=>{if(s.qualifiedFieldName&&oe.qualifiedFieldName&&oe.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&oe.qualifiedEntityName&&oe.qualifiedEntityName===s.qualifiedEntityName&&oe.name===s.name)return!0;const Ae=G(oe.id);return!!(Q&&Ae&&Q===Ae)});return{dataType:(ce==null?void 0:ce.dataType)||s.dataType,resolvedFromScopedField:!!ce}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),ye=t.getGranularityOptionsForFieldType(ge.dataType),[je,we]=N.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,K]=N.useState(s.customFormat||""),[le,Ne]=N.useState(!!s.customFormat),Pe=N.useRef(null),[W,fe]=N.useState(s.aliasTemplate||""),[Ce,ke]=N.useState(s.valueAliases||{}),[Se,Be]=N.useState((Ns=s.parameters)==null?void 0:Ns.filters),ze=G=>{G==="custom"?Ne(!0):(Ne(!1),we(G),(n==="groupBy"||mt)&&M(a,G,"",n))},Xe=G=>{K(G),(n==="groupBy"||mt)&&M(a,"custom",G,n)},Ye=G=>{var oe;const ce=(oe=t.getDateFormatOptionsForGranularity(G)[0])==null?void 0:oe.value;ce&&!le&&(we(ce),n==="groupBy"&&M(a,ce,"",n)),n==="groupBy"&&j(a,G)},We=G=>{fe(G),n==="metrics"&&R(a,G)},ae=G=>{ke(G),n==="metrics"&&y(a,G)},Ie=G=>{D(n,a,G)},Oe=t.getExpressionFieldKind(s),be=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),Te=s.role==="metric"&&Ge,bt=Ge&&(Oe==="user_calculated"||Oe==="inline_expression"&&s.fieldScope!=="domain"),Ze=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(G=>t.matchesCalculatedField(G,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Ze),Ue=Oe==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=Ue?"domain":Tt?"dashboard":"card",et=Ue?Et||s:Tt&&Ze?Ze:s,It=G=>{var Q;if(Be(G),n==="metrics"){const ce={...s,parameters:{...s.parameters,filters:G}},oe=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];oe[a]=ce,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}X(!1)},vt=()=>{F(n,a)},Kt={transform:t.CSS.Transform.toString(p),transition:x},Dt=t.getDataType(ge.dataType||s.dataType),dt=Dt==="date",ut=o==="kpi",mt=n==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,Qe=t.useDashboardStore(G=>{var Q;return(Q=G.dashboard)==null?void 0:Q.filters}),Gt=t.useDashboardStore(G=>G.filterValues),tt=s.granularity||"day",kt=ye.includes(tt)?tt:"day",yt=n==="groupBy"&&!ye.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=le?"custom":ht.some(G=>G.value===je)?je:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";N.useEffect(()=>{var ce;if(C||!yt){Pe.current=null;return}const G=`${s.id}:${tt}:${ge.dataType||s.dataType||""}:${a}`;if(Pe.current===G)return;Pe.current=G;const Q="day";if(j(a,Q),!le){const oe=(ce=t.getDateFormatOptionsForGranularity(Q)[0])==null?void 0:ce.value;oe&&(we(oe),M(a,oe,"",n))}},[s.dataType,s.id,M,j,yt,a,le,C,tt,ge.dataType,n]);const Ht=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Qt=o==="kpi"||o==="table",Ke=N.useMemo(()=>$e==null?void 0:$e.find(G=>t.getDataType(G.dataType||"")==="date"),[$e]),At=N.useMemo(()=>($e||[]).some(G=>t.getDataType(G.dataType||"")==="date"),[$e]),pt=N.useMemo(()=>{var oe;if(!Ke)return!1;const G=(oe=m.config)==null?void 0:oe.filters;if(!G)return!1;const Q=Ae=>{const Le=Ae.field;return Le?Ke.id&&Le.id===Ke.id||Ke.qualifiedFieldName&&Le.qualifiedFieldName===Ke.qualifiedFieldName?!0:Le.name===Ke.name:!1},ce=Ae=>Ae.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&Q(_e))?!0:Ae.groups.some(_e=>ce(_e));return ce(G)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=N.useMemo(()=>co(Qe||[],Ke,Gt),[Qe,Gt,Ke]),Nt=pt||Mt,q=s,J=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",H=t.isMetricTransformEnabled(q),ie=H?J:null,xe=t.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:m.config||{},metric:q,transformMode:ie||"running_total"}),he=!!q.comparisonType&&q.comparisonType!=="none",Me=t.getRunningTotalOrderByCandidates($e||[]),Re=((Ms=(As=(ks=q.parameters)==null?void 0:ks.windowTransform)==null?void 0:As.orderBy)==null?void 0:Ms.fieldId)||"",Je=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Me.find(G=>G.id===Re),st=ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta",Ve=H&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:m.config||{},orderByFieldId:Re||void 0}),Jt=new Set(((Ps=(Os=q.parameters)==null?void 0:Os.windowTransform)==null?void 0:Ps.partitionByFieldIds)||ft),Yt=o==="pivotTable"||t.isSubtotalEnabledAggregateTable(o||"table",m.config||{}),gs=[...($e||[]).filter(G=>G.id&&(!st||G.id!==Re)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(G=>G.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Ua=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Ha=((Hs=(Us=(Gs=q.parameters)==null?void 0:Gs.windowTransform)==null?void 0:Us.previousPeriodDelta)==null?void 0:Hs.mode)||"absolute",bs=((Ys=(Js=(Qs=q.parameters)==null?void 0:Qs.windowTransform)==null?void 0:Js.percentOfTotal)==null?void 0:Ys.scope)||"grand_total",Qa=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Ja=N.useMemo(()=>(xt||[]).some(G=>G.comparisonType==="start_vs_end"),[xt]);N.useEffect(()=>{H&&de(!0)},[H]);const Ya=n!=="pivotBy"&&n!=="sortBy",Wa=dt&&n==="groupBy"&&(!ut||Ja),Xa=!ut&&dt&&(n==="groupBy"||mt),Za=o==="kpi"&&dt&&n==="groupBy",en=n==="metrics",vs=Ht&&n==="metrics",tn=()=>{const G=s,Q=n==="metrics"&&Te;return e.jsxs("div",{className:"space-y-1",children:[!Q&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:ce=>{ce.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Q&&G.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(G.calculatedFormula),onPointerDown:ce=>{ce.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:["= ",t.formatDisplayFormula(G.calculatedFormula)]})]})},sn=()=>Ya?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(He,{value:s.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,an=()=>n!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:r||"asc",onValueChange:G=>d(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),ys=()=>Wa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:kt,onValueChange:Ye,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(t.SelectContent,{children:ye.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,nn=()=>Xa?e.jsxs(e.Fragment,{children:[ys(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:Ut,onValueChange:ze,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ht.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),le&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Ee,onChange:G=>{G.stopPropagation(),Xe(G.target.value)},onClick:G=>G.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,rn=()=>{var Q,ce,oe,Ae;const G=Za;return G?e.jsx(e.Fragment,{children:G&&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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((Q=m.config)==null?void 0:Q.showTrendline)||!1,onCheckedChange:$})]})}),((ce=m.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input,{type:"number",min:"1",max:"365",value:((oe=m.config)==null?void 0:oe.trendlineWindow)||30,onChange:Le=>{const _e=parseInt(Le.target.value)||30;ee(_e)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Ae=m.config)==null?void 0:Ae.trendlineGranularity)||"day",onValueChange:ne,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})}):null},ln=()=>{if(!en)return null;const G=Te;return e.jsxs(e.Fragment,{children:[G&&T&&!Ue&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>ue(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Q=>{I(a,Q)},disabled:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(hs,{value:q.format,onChange:Q=>L(a,Q),showTitle:!1})]}),e.jsx(t.Collapsible,{open:re,onOpenChange:de,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!re&&e.jsx("span",{className:"mr-2",children:H?t.toTitleCase(J.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",re?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:H?J:"none",onValueChange:Q=>k(a,Q),disabled:!xe.supported&&!H,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"None"}),e.jsx(t.SelectItem,{value:"running_total",disabled:he,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:he,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:he,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:he,children:"Percent of Total"})]})]}),!xe.supported&&!H&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xe.reason}),he&&!H&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),H&&e.jsxs(e.Fragment,{children:[st&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:Re,onValueChange:Q=>w(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Me.filter(Q=>!!Q.id).map(Q=>e.jsx(t.SelectItem,{value:Q.id,className:"text-xs",children:Q.label||Q.name},Q.id))})]}),!Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Ve&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(t.Select,{value:Je,onValueChange:Q=>V(a,Q),disabled:!Re,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),ie==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input,{type:"number",min:1,className:"h-8 text-xs",value:js,onChange:Q=>P(a,Number(Q.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:js,className:"h-8 text-xs",value:Ua,onChange:Q=>_(a,Number(Q.target.value))})]}),ie==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:Q=>z(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),ie==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:bs,onValueChange:Q=>U(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Qa,onValueChange:Q=>Y(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta"||ie==="percent_of_total"&&bs==="partition_total")&&gs.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:gs.map(Q=>{const ce=!!Q.id&&Jt.has(Q.id);return e.jsxs("button",{type:"button",onClick:()=>Q.id&&O(a,Q.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ce?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Q.label||Q.name}),ce?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Q.id)})})]})]})]})]})}),vs&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:q.comparisonType||"none",disabled:H,onValueChange:Q=>f(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Q=!At||!Nt,ce=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(Ae,Le)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ae,disabled:Q,title:ce,children:Le})}),Q&&ce&&e.jsx(t.TooltipContent,{side:"right",children:ce})]})});return e.jsxs(e.Fragment,{children:[oe("previous_period","Previous Period"),oe("same_period_last_year","Same Period Last Year"),oe("start_vs_end","Start vs End")]})})(),Qt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),vs&&q.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input,{type:"number",value:q.targetValue!==void 0&&q.targetValue!==null?String(q.targetValue):"",onChange:Q=>{const ce=Q.target.value;if(ce===""){me(a,void 0);return}const oe=Number(ce);me(a,Number.isFinite(oe)?oe:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(Q=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{te(Q),X(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.value.map((ce,oe)=>e.jsx("div",{children:String(ce)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var Ae;ce.stopPropagation();const oe=Se.conditions.filter(Le=>Le.id!==Q.id);if(oe.length>0){const Le={...Se,conditions:oe};It(Le)}else if(Be(void 0),n==="metrics"){const Le={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((Ae=m.config)==null?void 0:Ae.metricColumns)||[]];_e[a]=Le,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{te(null),X(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(go,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(uo,{aliasTemplate:W,onAliasTemplateChange:We}),e.jsx(mo,{valueAliases:Ce,onValueAliasesChange:ae})]})]})},on=(Se==null?void 0:Se.conditions)&&Se.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:Kt,className:t.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",ve&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",h&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...c,...l,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:G=>{G.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(t.IconForFieldType,{dataType:Dt}),be&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,be.badgeClassName),children:be.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",on&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((ea=Se==null?void 0:Se.conditions)==null?void 0:ea.length)&&!ve&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.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 text-primary/90",children:[e.jsx(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),d(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),se(!ve)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ve?"rotate-180":""}`})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ve&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[tn(),an(),sn(),o==="kpi"&&ys(),nn(),rn(),ln()]})]}),pe&&e.jsx(Ka,{open:pe,onOpenChange:G=>{X(G),G||te(null)},availableFields:B,existingFilters:Se,editingCondition:Fe,onSave:G=>{var Q;if(G)It(G);else if(Be(void 0),n==="metrics"){const ce={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];oe[a]=ce,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}te(null)}}),Z&&n==="metrics"&&Te&&e.jsx(t.CalculatedFieldEditor,{open:Z,onOpenChange:ue,availableFields:E,existingField:et,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{var Ft;if(G.role!=="metric")return;const{card:Q,frame:ce,actions:oe}=t.useEditorStore.getState(),Ae=((Ft=Q.config)==null?void 0:Ft.metricColumns)||[],Le=ce.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:Ae,storedFields:Q.calculatedFields||[],sharedFields:Le,updatedField:G,editingField:et,previousScope:ct});_e&&oe.updateCardConfig(m.id,{metricColumns:_e}),oe.updateCard(m.id,{calculatedFields:Ct}),Lt!==Le&&t.commitSharedCalculatedFields({nextSharedFields:Lt,currentSharedFields:Le,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:S})},onSaveToDashboard:G=>{var ta;if(G.role!=="metric")return;const{card:Q,frame:ce,actions:oe}=t.useEditorStore.getState(),Ae=s,Le=((ta=Q.config)==null?void 0:ta.metricColumns)||[],_e=ce.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Le,storedFields:Q.calculatedFields||[],sharedFields:_e,updatedField:{...G,id:Ae.id,aliasTemplate:Ae.aliasTemplate,valueAliases:Ae.valueAliases,parameters:Ae.parameters,customFormat:Ae.customFormat},editingField:et,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:S}),Ct&&oe.updateCardConfig(m.id,{metricColumns:Ct}),oe.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function yo({concept:s}){const n=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-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"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}const No={groupBy:zt,pivotBy:cs,metrics:In,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:n,label:a,placeholder:r,shouldShow:d,hasPivotColumns:i=!1,activeField:o=null}){const{isOver:c,setNodeRef:l}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(S=>S.card),x=t.useEditorStore(S=>S.card.type),h=n.length>0,m=N.useMemo(()=>!o||!c?!0:t.validateFieldForChartType(o,s,x).isValid,[o,c,s,x]),g=(S,E)=>{var C;!((C=p.config)!=null&&C.sortByColumns)||p.config.sortByColumns.findIndex(A=>A.id===S)===-1||u(p.id,S,{direction:E})};if(s==="sortBy"&&d===!1)return null;const v=s!=="sortBy"&&x!=="kpi",b=No[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:a})}),e.jsx("div",{ref:l,className:t.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":c&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":c&&!m,"border-solid border-border/55 bg-background":!c&&h,"min-h-[56px] border-dashed border-border/60 bg-background":!c&&!h}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(b,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),v&&e.jsx(yo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(S=>S.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((S,E)=>{const C=S.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(vo,{field:S,zone:s,index:E,sortDirection:C,onSortDirectionChange:A=>g(S.id,A),hasPivotColumns:i,cardType:x})})},S.id)})})})})]})}function Co({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:d,activeField:i}){var z,U,Y;const[o,c]=N.useState(!1),l=t.useEditorStore($=>{var ee;return!!((ee=$.card.customCardPreferences)!=null&&ee.url)}),u=t.useEditorStore($=>$.card),p=t.useEditorStore($=>$.frame),x=t.findCustomVisualConfigCard(p,u),{manifest:h}=t.useCustomVisual(((z=x==null?void 0:x.customCardPreferences)==null?void 0:z.url)||""),m=(U=h==null?void 0:h.visuals)==null?void 0:U.find($=>{var ee;return $.name===((ee=x==null?void 0:x.customCardPreferences)==null?void 0:ee.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((Y=x==null?void 0:x.customCardPreferences)!=null&&Y.url),b=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore($=>$.actions.updateCardConfig);const S=t.useEditorStore($=>$.actions.updateCard),E=t.useEditorStore($=>$.actions.updateFrame),B=t.useDashboardStore($=>$.isVisualEditing),C=t.useDashboardStore($=>$.selectedSheetId),A=t.useDashboardStore($=>$.actions.updateSheetCalculatedFields),{scopedFields:T}=t.useScopedFields(),{userContext:D}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===u.id&&b?b:u==null?void 0:u.type,M=I==="detailTable",j=s.length>0||a.length>0||d.length>0,R=!M&&(I!=="kpi"||a.length<=2),y=!M,L=!M&&I!=="kpi",F=I!=="kpi"&&j,f=M,k="Drop sort fields here",w=(D==null?void 0:D.type)==="organization",V=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),O=L&&!V,P=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},_=()=>I==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[R&&e.jsx(wt,{zone:"groupBy",fields:s,label:P().label,placeholder:P().placeholder,activeField:i}),O&&e.jsx(wt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),y&&e.jsx(wt,{zone:"metrics",fields:a,label:_().label,placeholder:_().placeholder,hasPivotColumns:n.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&w&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),F&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:k,activeField:i})]})]}),(!l||v)&&e.jsxs(t.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx($a,{mode:"config"})})})]}),(l||v)&&e.jsxs(t.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Va,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:o,onOpenChange:c,availableFields:T,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{if($.role!=="metric")return;const{nextStoredFields:ee}=t.saveCalculatedFieldToCardScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:$,previousScope:"card"});S(u.id,{calculatedFields:ee})},onSaveToDashboard:$=>{if($.role!=="metric")return;const ee=p.calculatedFields||[],{nextSharedFields:ne}=t.saveCalculatedFieldToSharedScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:ee,updatedField:$,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:ne,currentSharedFields:ee,isVisualEditing:B,selectedSheetId:C,updateFrame:E,updateSheetCalculatedFields:A})},cardId:u.id})]})}function So({onEditJoins:s}){const n=t.useEditorStore(c=>c.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,d=(r==null?void 0:r.joins)||[];if(d.length===0)return null;const i=c=>!c||c.length===0?"No conditions":c.map(l=>{var h,m,g,v;const u=`${(h=l.source)==null?void 0:h.entityName}.${(m=l.source)==null?void 0:m.name}`,p=`${(g=l.target)==null?void 0:g.entityName}.${(v=l.target)==null?void 0:v.name}`,x=l.operator||"=";return`${u} ${x} ${p}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?i(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,u)=>({id:u,operator:l.operator,condition:i(l.keys)}));return e.jsx(t.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",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(Ln,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:d.map((c,l)=>{const u=o(c),p=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(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(t.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:p?u.map(x=>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:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.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)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}const Sa={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(n){return console.warn(`Failed to read from localStorage (${s}):`,n),null}},setItem(s,n){if(!(typeof window>"u"))try{localStorage.setItem(s,n)}catch(a){console.warn(`Failed to write to localStorage (${s}):`,a)}}};function wo({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:o,activeField:c}){var M,j;const[l,u]=N.useState(()=>Sa.getItem("chart-selector-expanded")==="true"),[p,x]=N.useState(!1),h=t.useEditorStore(R=>R.card),m=t.useEditorStore(R=>R.actions.updateCardConfig),g=a.length>0||r.length>0||d.length>0||o.length>0,{data:v,autoJoinMetadata:b}=t.useDashboardCardQuery(h),S=g||!!v,E=((M=h==null?void 0:h.config)==null?void 0:M.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),B=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],C=R=>{m(h.id,{...h==null?void 0:h.config,joinPlan:R}),x(!1)},A=()=>{m(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},T=()=>{x(!1)},D=()=>{x(!0)};N.useEffect(()=>{Sa.setItem("chart-selector-expanded",String(l))},[l]);const I=()=>{u(R=>!R)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:t.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(us,{selectedChart:s,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:I})})]})}),S&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(De.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",S?"pt-1":"pt-4"),children:[e.jsx(So,{onEditJoins:D}),e.jsx(Co,{groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:o,activeField:c})]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:B,onSave:C,onCancel:T,onRemove:A,children:e.jsx("div",{})})]})}function To({initialFilters:s,availableFields:n}={}){const[a,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:d,isLoading:i}=t.useFilterableFields(),o=n||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},l=C=>{const A=T=>{if(T.id===C){const D=o[0]||c,I=t.getDataType(D.dataType)==="date";return{...T,conditions:[...T.conditions,{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}]}}return{...T,groups:T.groups.map(A)}};r(A(a))},u=C=>{const A=T=>{if(T.id===C){const D=o[0]||c,I=t.getDataType(D.dataType)==="date";return{...T,groups:[...T.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}],groups:[]}]}}return{...T,groups:T.groups.map(A)}};r(A(a))},p=(C,A)=>{const T=D=>D.id===C?{...D,conditions:D.conditions.filter(I=>I.id!==A)}:{...D,groups:D.groups.map(T)};r(T(a))},x=(C,A)=>{const T=D=>D.id===C?{...D,groups:D.groups.filter(I=>I.id!==A)}:{...D,groups:D.groups.map(T)};r(T(a))},h=(C,A,T,D)=>{if(T==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=M=>M.id===C?{...M,conditions:M.conditions.map(j=>j.id===A?{...j,[T]:D}:j)}:{...M,groups:M.groups.map(I)};r(I(a))},m=(C,A,T)=>{const D=I=>I.id===C?{...I,conditions:I.conditions.map(M=>M.id===A?{...M,...T}:M)}:{...I,groups:I.groups.map(D)};r(D(a))},g=(C,A)=>{const T=D=>D.id===C?{...D,logicalOperator:A}:{...D,groups:D.groups.map(T)};r(T(a))},v=(C,A)=>{const T=D=>D.id===C?{...D,negate:A}:{...D,groups:D.groups.map(T)};r(T(a))},b=(C,A,T)=>{const D=I=>I.id===C?{...I,conditions:t.arrayMove(I.conditions,A,T)}:{...I,groups:I.groups.map(D)};r(D(a))},S=(C,A,T)=>{const D=I=>I.id===C?{...I,groups:t.arrayMove(I.groups,A,T)}:{...I,groups:I.groups.map(D)};r(D(a))},E=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const A=D=>{let I="";typeof D.field=="object"?I=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:I=String(D.field);const M=D.operator;let j=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(j)&&j.length===2){const R=j[0]?`'${j[0]}'`:"NULL",y=j[1]?`'${j[1]}'`:"NULL";return`${I} BETWEEN ${R} AND ${y}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(j)){const R=j.map(y=>y?`'${y}'`:"NULL").join(", ");return`${I} ${M} (${R})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(j)?R=j.map(y=>typeof y=="string"?`'${y}'`:String(y)):typeof j=="string"?R=j.split(",").map(y=>{const L=y.trim();return D.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(R=[String(j)]),j=`(${R.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${I} LIKE '${j.replace(/'/g,"")}%'`:`${I} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"isNull":return`${I} IS NULL`;case"isNotNull":return`${I} IS NOT NULL`;default:return`${I} ${M} ${j}`}},T=D=>{const I=D.conditions.map(A),M=D.groups.map(L=>T(L)),j=[...I,...M].filter(Boolean);if(j.length===0)return"";const R=j.join(` ${D.logicalOperator} `),y=j.length>1?`(${R})`:R;return D.negate?`NOT ${y}`:y};return T(C)},B=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:l,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:E,hasAnyFilters:B}}function Eo({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Io=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Do({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:d="w-64"}){const[i,o]=N.useState(!1),c=N.useMemo(()=>{const l={};return a.forEach(u=>{const p=Io(u);l[p]||(l[p]={}),l[p][u.entityId]||(l[p][u.entityId]=[]),l[p][u.entityId].push(u)}),l},[a]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Eo,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(c).map(([l,u])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(u).map(([p,x])=>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:[t.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((h,m)=>e.jsxs(t.CommandItem,{value:h.id,onSelect:()=>{n(h),o(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+m))]},`${l}-${p}`))},l))})]})})]})}function fs(s){var v;const n=t.useEditorStore(b=>b.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),d=t.useEditorStore(b=>b.card.config),i=d==null?void 0:d.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[o],metricColumns:[c],sortByColumns:[l]},p=((v=n.dataSource)==null?void 0:v.connectionId)||n.connectionId,{data:x,isPending:h,error:m}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:u,cardDataSource:n.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:h,error:m}}function ko({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:d}){const[i,o]=Pt.useState(!1),{filterValues:c}=fs(s),l=p=>{a(n.filter(x=>x!==p))},u=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:i,onOpenChange:o,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(p=>{const x=c.find(h=>h.value===p);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:h=>{h.key==="Enter"&&l(p)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),l(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:c.map((p,x)=>e.jsxs(t.CommandItem,{onSelect:()=>u(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function Ao({field:s,value:n,onChange:a,placeholder:r="Select value...",className:d}){const{filterValues:i,isPending:o,error:c}=fs(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.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(t.Select,{value:n,onValueChange:a,children:[e.jsx(t.SelectTrigger,{className:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:n})}),e.jsx(t.SelectContent,{children:i.map((l,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+u))})]})}function Mo({value:s,operator:n,onChange:a,className:r}){var m,g,v;const{tokenProps:d}=t.useSemaphorContext(),i=((g=(m=d==null?void 0:d.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=d==null?void 0:d.params)==null?void 0:v.timezone),o=i||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",l=N.useMemo(()=>{if(!(!s||!c)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,S=s[1]?new Date(s[1]):void 0;if(b&&S)return{from:b,to:S}}},[s,c]),u=N.useMemo(()=>{if(!s||c)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const S=new Date(b);if(!isNaN(S.getTime()))return S},[s,c]),p=b=>n==="<="||n===">"?t.endOfDayInTimezone(b,o):t.startOfDayInTimezone(b,o),x=b=>{if(!b){a([]);return}if(b.from&&b.to){a([b.from.toISOString(),b.to.toISOString()]);return}a([])},h=b=>{if(!b){a("");return}const S=p(b);a(S.toISOString())};return e.jsx(t.DateRangePicker,{value:c?l:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:u,onChange:x,onSingleChange:h,timezone:i,showRelativeTab:c,className:r,placeholder:"Select date..."})}const Lo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Fo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ro=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Oo=["=","!=","isNull","isNotNull"],Po=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Bo={"=":"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 wa(s){return Bo[s]||t.titleCase(s)}function Vo(s){switch(s){case"string":return Fo;case"number":return Ro;case"boolean":return Oo;case"date":return Po;default:return Lo}}function Ga({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:d,onRemoveCondition:i,onUpdateGroupOperator:o,availableFields:c,updateConditionFields:l}){const{attributes:u,listeners:p,setNodeRef:x,transform:h,transition:m,isDragging:g}=t.useSortable({id:s.id}),{isPending:v,error:b}=fs(s.field),S={transform:t.CSS.Transform.toString(h),transition:m};return e.jsxs("div",{ref:x,style:S,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(t.Select,{value:r,onValueChange:E=>o(a,E),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:s.field,onValueChange:E=>{const B=E,C=t.getDataType(B.dataType)==="date";l(a,s.id,{field:B,value:"",operator:C?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?l(a,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?l(a,s.id,{operator:E,value:null}):E==="between"||E==="not between"?l(a,s.id,{operator:E,value:[]}):l(a,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?wa(s.operator):""})}),e.jsx(t.SelectContent,{children:Vo(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:wa(E)},E))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?v?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>l(a,s.id,{value:E}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Ao,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:E=>l(a,s.id,{value:E==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Mo,{value:s.value,operator:s.operator,onChange:E=>l(a,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>d(a,s.id,"value",E.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(a,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function zo({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:d,onRemoveGroup:i,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onReorderConditions:u,onReorderGroups:p,onAddCondition:x,onAddGroup:h,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:S,setNodeRef:E,transform:B,transition:C,isDragging:A}=t.useSortable({id:s.id}),T={transform:t.CSS.Transform.toString(B),transition:C},D=M=>{const{active:j,over:R}=M;if(R&&j.id!==R.id){const y=s.conditions.findIndex(F=>F.id===j.id),L=s.conditions.findIndex(F=>F.id===R.id);y!==-1&&L!==-1&&u(s.id,y,L)}},I=M=>{const{active:j,over:R}=M;if(R&&j.id!==R.id&&a){const y=s.groups.findIndex(F=>F.id===j.id),L=s.groups.findIndex(F=>F.id===R.id);y!==-1&&L!==-1&&p(a,y,L)}};return e.jsxs("div",{ref:E,style:T,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${A?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...S,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:M=>r(s.id,M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&i(a,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:D,children:e.jsx(t.SortableContext,{items:s.conditions.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((M,j)=>e.jsx(Ga,{condition:M,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},M.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:I,children:e.jsx(t.SortableContext,{items:s.groups.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(M=>g(M,n+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function _o({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:d}){const{currentFilters:i,availableFields:o,isLoading:c,addCondition:l,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:E,hasAnyFilters:B,setCurrentFilters:C}=To({initialFilters:s,availableFields:n}),A=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[T,D]=N.useState(!1),I=(R,y,L)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(k=>k.id===y?{...k,field:L,dataType:L.dataType}:k)}:{...f,groups:f.groups.map(F)};C(F(i))},M=(R,y=0,L)=>y===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const w=R.conditions.findIndex(O=>O.id===f.id),V=R.conditions.findIndex(O=>O.id===k.id);w!==-1&&V!==-1&&b(R.id,w,V)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Ga,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const w=R.groups.findIndex(O=>O.id===f.id),V=R.groups.findIndex(O=>O.id===k.id);w!==-1&&V!==-1&&S(R.id,w,V)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>M(F,y+1,R.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),T&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(zo,{group:R,depth:y,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:S,onAddCondition:l,onAddGroup:u,availableFields:o,renderFilterGroup:M,updateConditionFields:m},R.id),j=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[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..."})]}):M(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:T,onCheckedChange:R=>D(R)}),e.jsx(t.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:E(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(B?i:null),children:"Apply Filters"})]})]})}function qo({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:d,isOpen:i,onOpenChange:o}){const c=u=>{a(s,u),o(!1)},l=()=>{r(s),o(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:o,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(_o,{filters:n,availableFields:d,onSave:c,onCancel:()=>o(!1),onClearAll:l})]})]})}function $o({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,B;const[d,i]=N.useState(null),o=t.useEditorStore(C=>C.card),c=t.useEditorStore(C=>C.actions.updateCardConfig),l=t.useEditorStore(C=>C.actions.setCardPreferences),u=(E=o==null?void 0:o.config)==null?void 0:E.joinPlan,p=N.useCallback(C=>C.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),x=(B=o==null?void 0:o.dataSource)==null?void 0:B.semanticDomainId,{data:h}=t.useJoinabilityMap(x),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=N.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||n.find(A=>A.id===C)?"source":a("groupBy").find(A=>A.id===C)?"groupBy":a("metrics").find(A=>A.id===C)?"metrics":a("pivotBy").find(A=>A.id===C)?"pivotBy":a("sortBy").find(A=>A.id===C)?"sortBy":a("detailColumns").find(A=>A.id===C)?"detailColumns":null,[n,a]),v=N.useCallback(C=>{i(C.active.id)},[]),b=N.useCallback(C=>{var R;const{active:A,over:T}=C;if(!T||!s){i(null);return}const D=A.id,I=T.id,M=g(D),j=g(I)||I;if(j==="sortBy"){if(M==="source"){const y=n.find(F=>F.id===D);if(!y){i(null);return}if(!(a("groupBy").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName)||a("metrics").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName)||a("detailColumns").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName))){i(null);return}}else if(M==="pivotBy"){i(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){i(null);return}}if(M==="source"&&j==="sortBy"){const y=[...n].find(k=>k.id===D);if(!y){i(null);return}const L=a("sortBy");if(t.fieldAlreadyExists(y,L)){i(null);return}const F=t.validateFieldForChartType(y,"sortBy",o.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const f=t.getNewField(y,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(M==="source"&&j!=="source"&&j!=="sortBy"){const y=[...n].find(O=>O.id===D);if(!y){i(null);return}const L=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],F=L.filter(O=>!p(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){i(null);return}if(O!==y.qualifiedEntityName&&!p(y)&&y.qualifiedEntityName)if(x&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(y,{joinabilityMap:h.joinabilityMap,selectedFields:L,baseEntityName:(R=u==null?void 0:u.baseEntity)==null?void 0:R.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!u){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(O,y.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=a(j);if(t.fieldAlreadyExists(y,f)){i(null);return}const k=t.validateFieldForChartType(y,j,o.type);if(!k.isValid){t.ue.error("Invalid Field Type",{description:k.reason,position:"top-center",duration:3e3}),i(null);return}const w=t.getNewField(y,j,f),V=[...f,w];if(i(null),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(o,w,o.preferences);O&&l(O),t.cleanupKpiMetricComparisonMode(o.type,o.config,c,s,V)}return}if(M&&j&&M!=="source"&&j!=="source"&&M!==j){const y=a(M),L=a(j),F=y.find(O=>O.id===D);if(!F){i(null);return}const f=t.validateFieldForChartType(F,j,o.type);if(!f.isValid){t.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),i(null);return}const k=t.getNewField(F,j,L);if(i(null),j==="sortBy"){t.fieldAlreadyExists(F,L)||r(j,[...L,k]);return}const w=y.filter(O=>O.id!==D),V=[...L,k];if(r(M,w),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(o,k,o.preferences);O&&l(O),t.cleanupKpiMetricComparisonMode(o.type,o.config,c,s,V)}return}if(M&&j&&M===j&&M!=="source"){const y=a(M),L=y.findIndex(f=>f.id===D),F=y.findIndex(f=>f.id===I);if(L!==F){const f=t.arrayMove(y,L,F);r(M,f)}}i(null)},[s,n,a,r,g,u,x,h,p,o,c,l]),S=d?m.find(C=>C.id===d):null;return{activeId:d,activeField:S,handleDragStart:v,handleDragEnd:b}}function Ko({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(c=>c.card),{config:d}=N.useContext(t.SemaphorContext).tokenProps,i=(d==null?void 0:d.showInfoTab)!==!1,o=()=>a?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.Tabs,{value:s,onValueChange:c=>n(c),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),o()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&i&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})})}const Go=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Uo(){var l,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=N.useState(!1),[d,i]=N.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(s.id,parseInt(p))},c=p=>{const x=p.target.value;i(x),x&&!isNaN(parseInt(x))&&n(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:u.toString())||"100",onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Go.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Ho({card:s,queryData:n,isLoading:a,isFetching:r,pagination:d,onPaginationChange:i,onSortChange:o,sortState:c,splitViewEnabled:l,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const x=N.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),h=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Pa,{fallbackPreview:e.jsx(ot,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return h?l?e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:o,sortState:c})]})})]}):m:!l||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ot,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:o,sortState:c})]})})]})}const Qo="semaphor-split-view-enabled";function Jo(){return Aa(Qo,!0)}function Yo({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:d}){var de,pe,X;const i=t.useEditorStore(Z=>Z.card),o=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),c=t.useEditorStore(Z=>Z.actions.removeCardInlineFilterValue),l=t.useDashboardStore(Z=>Z.filterValues),u=t.useDashboardStore(Z=>Z.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:h,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(Z=>Z.showAIDialog),v=t.useEditorStore(Z=>Z.isDevMode),b=t.useDashboardStore(Z=>Z.isVisualEditing),[S,E]=N.useState(!1),[B,C]=N.useState(!1),[A,T]=N.useState(!1),[D,I]=N.useState(null),{config:M}=N.useContext(t.SemaphorContext).tokenProps,j=(M==null?void 0:M.showInfoTab)!==!1,R=(M==null?void 0:M.showQueryDebugTools)!==!1,[y,L]=Jo();t.useEditorStore(Z=>{var ue;return!!((ue=Z.card.customCardPreferences)!=null&&ue.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:k,errorMessage:w,isLoading:V,isFetching:O,errorSql:P,pagination:_,refetch:z,comparisonMetadata:U,queryRequestPayload:Y}=t.useDashboardCardQuery(r),$=N.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[ee,ne]=N.useState(!1);N.useEffect(()=>{O||ne(!1)},[O]);const me=()=>{const Z=!y;Z&&s==="table"&&n("chart"),L(Z)},ve=(Z,ue)=>{const Fe={...r,paginationConfig:{page:Z+1,pageSize:ue}};x(Fe),h(Fe)},se=Z=>{if(!i.config)return;const ue=t.sortStateToSortByColumns(Z,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);p(i.id,{...i.config,sortByColumns:ue})},re=N.useMemo(()=>{var Z;return t.sortByColumnsToSortState((Z=i.config)==null?void 0:Z.sortByColumns)},[(de=i.config)==null?void 0:de.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&b}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&g&&!f&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:v?"secondary":"ghost"})}),e.jsx(Ko,{activeView:s,onViewChange:n,splitViewEnabled:y}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(pe=r.config)==null?void 0:pe.filters,cardFilterCount:t.getFilterCount(((X=r.config)==null?void 0:X.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:o,sheetId:u||"",removeInlineFilterValue:Z=>c(r.id,Z)}),U&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Uo,{})}),g&&e.jsx(De.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:V||O,onClick:()=>{ne(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":ee})})}),s==="chart"&&!f&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),!g&&e.jsx(t.IconButton,{onClick:()=>m(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(xn,{className:"size-4"})}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:me,children:[y?e.jsx(gn,{className:"mr-2 h-4 w-4"}):e.jsx(An,{className:"mr-2 h-4 w-4"}),y?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Ba,{onCustomize:()=>T(!0)})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":y&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Ho,{card:r,queryData:k,isLoading:V,isFetching:O,pagination:_,onPaginationChange:ve,onSortChange:se,sortState:re,splitViewEnabled:y,isDynamicInspectorOpen:A,onDynamicInspectorOpenChange:T})}),s==="table"&&(k==null?void 0:k.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(V||O)&&(k==null?void 0:k.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:$,comparisonMetadata:U,paginationMetadata:_,onPaginationChange:ve,isLoading:V||O,onSortChange:se,sortState:re})]}),s==="info"&&j&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:w?e.jsx(ds,{error:w,errorSql:P,onSendFeedback:()=>{const Z=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:l,errorMessage:w,errorSql:P,generatedSql:k==null?void 0:k.sql});I(Z),C(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const Z=t.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(P||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):(k==null?void 0:k.sql)&&e.jsx(La,{sql:k.sql,showCardDetails:!0,debugPayloads:R?{queryRequest:Y,queryResponse:k,columns:d,dashboardFilters:l}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:B,onOpenChange:C,feedbackData:D})]})})}function Wo({activeField:s}){const[n,a]=N.useState(!0);return N.useEffect(()=>{s&&a(!0)},[s]),s?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(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(t.IconForFieldType,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Xo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const 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 d;if((d=r.reason)!=null&&d.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=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Zo({column:s,isSelected:n,onSelect:a,availableFields:r,width:d,onWidthChange:i}){var O,P,_;const o=t.useEditorStore(z=>z.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[x,h]=N.useState(!1),[m,g]=N.useState(!1),v=N.useRef(null),b=N.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:d||150};const U=$=>{if(!v.current)return;const ee=$.clientX-v.current.startX,ne=Math.max(80,v.current.startWidth+ee);i==null||i(s.id,ne)},Y=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",Y)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",Y)},[d,s.id,i]),S=(O=o==null?void 0:o.config)==null?void 0:O.filters,E=(P=S==null?void 0:S.conditions)==null?void 0:P.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),B=z=>{z?p(o.id,z):c(o.id,{filters:void 0})},{attributes:C,listeners:A,setNodeRef:T,transform:D,transition:I,isDragging:M}=t.useSortable({id:s.id}),j={transform:t.CSS.Transform.toString(D),transition:I},R=t.getDataType(s.dataType),y=ei(R),L=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],U=z.findIndex($=>$.name===s.name);if(U!==-1){const $=[...z];$[U]={...$[U],direction:"asc"},c(o.id,{sortByColumns:$})}else c(o.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],U=z.findIndex($=>$.name===s.name);if(U!==-1){const $=[...z];$[U]={...$[U],direction:"desc"},c(o.id,{sortByColumns:$})}else c(o.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.groupByColumns)||[];if(!z.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(o.id,{groupByColumns:[...z,$]})}},k=z=>{var $;const U=(($=o==null?void 0:o.config)==null?void 0:$.metricColumns)||[];if(!U.some(ee=>ee.name===s.name&&ee.aggregate===z)){const ee={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};c(o.id,{metricColumns:[...U,ee]})}},w=()=>{s.role==="groupby"?l(o.id,s.id):s.role==="metric"&&u(o.id,s.id)},V={...j,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:T,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",n&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...A,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(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:t.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(y,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),E&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:L,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuSub,{children:[e.jsxs(t.DropdownMenuSubTrigger,{children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(t.DropdownMenuSubContent,{children:[e.jsx(t.DropdownMenuItem,{onClick:()=>k("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:f,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:w,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(Ka,{open:x,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:S,editingCondition:E?(_=S==null?void 0:S.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function ei(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function ti({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[],filterableFields:d=r}){var M,j,R,y;const i=t.useEditorStore(L=>L.card),{updateCardConfig:o}=t.useEditorActions(),[c,l]=N.useState(null),[u,p]=N.useState({}),[x,h]=N.useState(!1),m=N.useMemo(()=>{var f,k;const L=((f=i==null?void 0:i.config)==null?void 0:f.groupByColumns)||[],F=((k=i==null?void 0:i.config)==null?void 0:k.metricColumns)||[];return[...L,...F]},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),g=N.useMemo(()=>{const L=new Set(m.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!L.has(`${F.qualifiedEntityName}.${F.name}`))},[r,m]),{data:v,isLoading:b}=t.useDashboardCardQuery(i),S=(v==null?void 0:v.records)||[],E=N.useCallback((L,F)=>{p(f=>({...f,[L]:F}))},[]),B=N.useCallback(L=>{var w,V;const F=t.getDataType(L.dataType),f=((w=i==null?void 0:i.config)==null?void 0:w.groupByColumns)||[],k=((V=i==null?void 0:i.config)==null?void 0:V.metricColumns)||[];if(F==="number"){const O={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(i.id,{metricColumns:[...k,O]})}else{const O={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};o(i.id,{groupByColumns:[...f,O]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(y=i==null?void 0:i.config)==null?void 0:y.metricColumns,i.id,o]),C=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),A=L=>{l(L.active.id)},T=L=>{const{active:F,over:f}=L;if(l(null),!f||F.id===f.id)return;const k=m.findIndex(V=>V.id===F.id),w=m.findIndex(V=>V.id===f.id);if(k!==-1&&w!==-1){const V=t.arrayMove(m,k,w),O=V.filter(_=>_.role==="groupby"),P=V.filter(_=>_.role==="metric");o(i.id,{groupByColumns:O,metricColumns:P})}},D=c?m.find(L=>L.id===c):null,I=L=>{let F="";for(;L>=0;)F=String.fromCharCode(L%26+65)+F,L=Math.floor(L/26)-1;return F};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):m.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(t.DndContext,{sensors:C,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:T,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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map((L,F)=>e.jsx("th",{style:{width:u[L.id]?`${u[L.id]}px`:void 0,minWidth:u[L.id]?`${u[L.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:I(F)},`letter-${L.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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map(L=>e.jsx(Zo,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>n(L),availableFields:d,width:u[L.id],onWidthChange:E},L.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:x,onOpenChange:h,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:g.map(L=>{const F=t.getDataType(L.dataType),f=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:L.label||L.name,onSelect:()=>B(L),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:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.entityName})]})]},L.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):S.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):S.slice(0,100).map((L,F)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",F%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:F+1}),m.map(f=>{const k=L[f.name]??L[f.label??""];return e.jsx("td",{style:{width:u[f.id]?`${u[f.id]}px`:void 0,minWidth:u[f.id]?`${u[f.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===f.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:si(k,f)})},`${F}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:D&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:D.label||D.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(S.length,100)," of ",S.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function si(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const a=new Date(s);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function ai({entityGroups:s,isLoading:n=!1}){var B,C;const a=t.useEditorStore(A=>A.card),{updateCardConfig:r,removeGroupByColumn:d,removeMetricColumn:i}=t.useEditorActions(),[o,c]=N.useState(!0),[l,u]=N.useState(""),[p,x]=N.useState(new Set),h=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],m=((C=a==null?void 0:a.config)==null?void 0:C.metricColumns)||[],g=A=>{const T=new Set(p);T.has(A)?T.delete(A):T.add(A),x(T)},v=A=>h.some(T=>T.name===A.name&&T.qualifiedEntityName===A.qualifiedEntityName)||m.some(T=>T.name===A.name&&T.qualifiedEntityName===A.qualifiedEntityName),b=(A,T)=>{if(T)if(t.getDataType(A.dataType)==="number"){const I={...A,id:`metric-${A.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...m,I]})}else{const I={...A,id:`groupby-${A.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...h,I]})}else{const D=h.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName),I=m.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName);D!==-1&&d(a.id,h[D].id),I!==-1&&i(a.id,m[I].id)}},S=A=>{if(!l)return A;const T=l.toLowerCase();return A.filter(D=>D.name.toLowerCase().includes(T)||D.label&&D.label.toLowerCase().includes(T))},E=A=>{switch(t.getDataType(A)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return o?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(t.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(Sn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:l,onChange:A=>u(A.target.value),className:"h-8 pl-8 text-sm"})]})}),(h.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(zt,{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:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(A=>{const T=E(A.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]}),m.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.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:m.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(A=>{const T=E(A.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.aggregate}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]})]}),e.jsx(t.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"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(A=>{const T=S(A.columns);if(T.length===0)return null;const D=p.has(A.entityId)||l.length>0;return e.jsxs(t.Collapsible,{open:D,onOpenChange:()=>g(A.entityId),children:[e.jsxs(t.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(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",D&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:A.label||A.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:T.map(I=>{const M=E(I.dataType),j=v(I);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",j&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:j,onCheckedChange:R=>b(I,R),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.id)})})})]},A.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(wn,{className:"h-4 w-4"})})})}const ni=[{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 ri({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:d,availableColumns:i}){const[o,c]=N.useState(!1),[l,u]=N.useState("column"),p=N.useRef(null);N.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!o&&a(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,a,o]);const x=g=>{const v=`[${g.label||g.name}]`,b=p.current;if(b){const S=b.selectionStart||0,E=b.selectionEnd||0,B=s.slice(0,S)+v+s.slice(E);n(B),setTimeout(()=>{b.setSelectionRange(S+v.length,S+v.length),b.focus()},0)}else n(s+v);c(!1)},h=g=>{const v=p.current;if(v){const b=v.selectionStart||0,S=v.selectionEnd||0,E=s.slice(0,b)+g.syntax+s.slice(S);n(E),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else n(s+g.syntax);c(!1)},m=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.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:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&l==="function",onOpenChange:g=>{c(g),g&&u("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(kn,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search functions..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No functions found."}),e.jsx(t.CommandGroup,{heading:"Functions",children:ni.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>h(g),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:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:o&&l==="column",onOpenChange:g=>{c(g),g&&u("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.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(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:i.map(g=>{const v=m(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>x(g),children:[e.jsx(v,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:p,value:s,onChange:g=>n(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.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(t.X,{className:"h-4 w-4"})}),e.jsx(t.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(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function li({className:s}){var m,g,v,b;const n=t.useEditorStore(S=>S.card),[a,r]=N.useState(null),[d,i]=N.useState(""),{columns:o=[],columnGroups:c=[],isLoading:l}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(g=n==null?void 0:n.config)!=null&&g.metricColumns,(v=n==null?void 0:n.config)!=null&&v.groupByColumns,(b=n==null?void 0:n.config)!=null&&b.pivotByColumns;const p=S=>{r(S),i(S?`[${S.label||S.name}]`:"")},x=S=>{console.log("Formula submitted:",S),i(""),r(null)},h=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(ri,{value:d,onChange:i,onSubmit:x,onCancel:h,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(ti,{selectedColumn:a,onColumnSelect:p,isLoading:l,sourceFields:o,filterableFields:u})}),e.jsx(ai,{entityGroups:c,isLoading:l})]})]})}function oi(){var w,V;const[s,n]=N.useState("chart"),[a,r]=N.useState(!1),[d,i]=N.useState(!0),o=t.useEditorStore(O=>O.showAIDialog),c=t.useDashboardStore(O=>O.isVisualEditing),{setCardType:l}=t.useEditorActions(),u=t.useEditorStore(O=>O.card.type);N.useEffect(()=>Xo(),[]);const p=O=>{l(O)},x=t.useEditorStore(O=>O.frame),h=t.useEditorStore(O=>O.card);t.useEditorStore(O=>O.activeTabCardId),t.useEditorStore(O=>O.actions.getAvailableFields);const{addCard:m,removeCard:g,updateCard:v,setActiveCard:b,updateFilters:S}=t.useEditorActions(),{columnFields:E=[],scopedFields:B=[],filterableFields:C=[]}=t.useFilterableFields(),A=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),T=h,{getFieldsForContainer:D,setFieldsForContainer:I}=t.useFieldManagement(T),{activeField:M,handleDragStart:j,handleDragEnd:R}=$o({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:D,setFieldsForContainer:I}),y=(O,P)=>{P&&S(O,P)},L=O=>{var P;v(O,{config:{...(P=x.cards.find(_=>_.id===O))==null?void 0:P.config,filters:void 0}})},F=C,f=O=>{if(!O)return 0;let P=O.conditions.length;return O.groups.forEach(_=>{P+=f(_)}),P},k=f(((w=T==null?void 0:T.config)==null?void 0:w.filters)||null);return e.jsxs(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ma,{isVisible:d,onToggleVisibility:()=>i(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(li,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(wo,{selectedChart:u,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:M}),e.jsx(Yo,{selectedChart:u,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:k,activeCard:T,columns:E,getFieldsForContainer:D,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:b})]})}),!d&&c&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),T&&e.jsx(qo,{cardId:T.id,filters:((V=T.config)==null?void 0:V.filters)||null,onFiltersChange:y,onClearFilters:L,availableFields:F,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Wo,{activeField:M||null})})]})}function ii({authToken:s,onSave:n,onClose:a}){const r=N.useRef(null),d=t.useEditorStore(T=>T.showAIDialog),i=t.useEditorStore(T=>T.isDevMode),o=t.useAssistantLayoutStore(T=>T.setFullscreen),c=t.useAssistantLayoutStore(T=>T.setPanelOpen),l=t.useAssistantLayoutStore(T=>T.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),h=p==="editor",m=N.useCallback(T=>{l("editor",T)},[l]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:S}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();N.useEffect(()=>{n&&b(n),a&&S(a)},[n,b,a,S]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var T,D;d?((T=r.current)==null||T.resize(40),c("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),c("editor",!1),p==="editor"&&o(null),E(null))},[d,c,E,o,p]);function B(T){var D;T<1?(v(!1),c("editor",!1),p==="editor"&&o(null),E(null),(D=r.current)==null||D.resize(0)):(d||(v(!0),E("editor")),u.isOpen||c("editor",!0))}function C(){return e.jsxs(e.Fragment,{children:[e.jsx(Ma,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(lo,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.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(Ca,{isFullscreen:h,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function A(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(oi,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.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(Ca,{isFullscreen:h,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()}):A()})}function ci(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),n=t.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=t.useDashboardStore(l=>l.actions),d=t.useDashboardStore(l=>l.isVisualEditing),i=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){var h,m,g;const u=s?(h=n==null?void 0:n.sheets)==null?void 0:h.some(v=>{var b;return v.id===s&&((b=v.frames)==null?void 0:b.some(S=>S.id===l.id))}):!1,p=(g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(v=>{var b;return(b=v.frames)==null?void 0:b.some(S=>S.id===l.id)}))==null?void 0:g.id,x=u?s:p||null;x&&(i(x,l),s!==x&&r(x),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!d}),children:e.jsx(ii,{onSave:o,onClose:c})})}exports.default=ci;
193
+ 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 ll(){var h,m,g,v,b,S,E,B,C,A;const s=t.useEditorStore(T=>T.card),{setCardPreferences:n}=t.useEditorActions(),a=De.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],d=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&d.length===0,o=r.some(T=>T.comparisonType&&T.comparisonType!=="none");if(!(a==="kpi"&&(i||o)))return null;const l=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},u=T=>{var I;const D={...s.preferences,kpiVisualOptions:{...(I=s.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...l,...T}}};n(D)},p=o||l.enabled,x=r.some(T=>T.comparisonType==="previous_period"||T.comparisonType==="same_period_last_year"||T.comparisonType==="start_vs_end");return e.jsxs(t.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(t.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(Ia,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[i&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(t.Switch,{size:"sm",id:"enable-comparison",checked:l.enabled||!1,onCheckedChange:T=>u({enabled:T,...T&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&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(t.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const T=l.calculationType||"difference",D=ja[T];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:D==null?void 0:D.label}),e.jsx("p",{children:D==null?void 0:D.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:D==null?void 0:D.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",D==null?void 0:D.example]})]})})()})]})]}),e.jsxs(t.Select,{value:l.calculationType||"difference",onValueChange:T=>u({calculationType:T}),children:[e.jsx(t.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Object.entries(ja).map(([T,D])=>e.jsx(t.SelectItem,{value:T,className:"text-xs",children:D.label},T))})]})]}),e.jsx(jt,{formatOptions:l.formatOptions||{},onFormatOptionsChange:T=>u({formatOptions:T}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||i)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),i&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:l.position||"right",onValueChange:T=>u({position:T}),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(t.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(t.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"show-arrow",checked:l.showArrow!==!1,onCheckedChange:T=>u({showArrow:T})}),e.jsx(t.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(t.Checkbox,{id:"show-color",checked:l.showColor!==!1,onCheckedChange:T=>u({showColor:T})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(nt,{value:((b=l.colorConfig)==null?void 0:b.increase)||"green",onChange:T=>u({colorConfig:{...l.colorConfig,increase:T}}),label:"Primary > Secondary"}),e.jsx(nt,{value:((S=l.colorConfig)==null?void 0:S.decrease)||"red",onChange:T=>u({colorConfig:{...l.colorConfig,decrease:T}}),label:"Primary < Secondary"}),e.jsx(nt,{value:((E=l.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:T=>u({colorConfig:{...l.colorConfig,noChange:T}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Checkbox,{id:"conditional-label",checked:l.conditionalLabel||!1,onCheckedChange:T=>u({conditionalLabel:T})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(t.Input,{id:"label-increase",type:"text",value:((B=l.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,increase:T.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(t.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(t.Input,{id:"label-decrease",type:"text",value:((C=l.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,decrease:T.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(t.Input,{id:"label-no-change",type:"text",value:((A=l.conditionalLabels)==null?void 0:A.noChange)??"No change",onChange:T=>u({conditionalLabels:{...l.conditionalLabels,noChange:T.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(t.Input,{id:"label-name",type:"text",value:l.labelName??"",onChange:T=>u({labelName:T.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ol(){var i;const s=t.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.type}),n=t.useEditorStore(o=>{var c;return(c=o.card)==null?void 0:c.preferences}),{setCardPreferences:a}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=n==null?void 0:n.chartOptions)==null?void 0:i.treemapColorMode)??"branch",d=o=>{const c={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};a(c)};return e.jsxs(t.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(t.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(t.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(t.RadioGroup,{value:r,onValueChange:o=>d(o??"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(t.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(t.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(t.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(t.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."})]})]})]})})]})}const il=Object.keys(t.HEATMAP_PRESET_PALETTES);function cl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",d=(n==null?void 0:n.heatmapConfig)||{},i=d.colorPalette??"green",o=d.legendPosition??"bottom",c=N.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),l=h=>{const m={...d,...h};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:m})},u=h=>{l({colorPalette:h,colorRange:h==="custom"?d.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(h,m)=>{const g=[...c];g[h]=m,l({colorPalette:"custom",colorRange:g})},x=h=>{l({legendPosition:h})};return r?e.jsxs(t.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(t.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(t.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(t.RadioGroup,{value:i,onValueChange:h=>u(h??"blue"),className:"space-y-3",children:[il.map(h=>{const m=t.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${m.start}, ${m.end})`}})]})]},h)}),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(t.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(nt,{value:c[0],onChange:h=>p(0,h),label:"Start color"}),e.jsx(nt,{value:c[1],onChange:h=>p(1,h),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(t.Select,{value:o,onValueChange:h=>x(h??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const ba=["poor","satisfactory","good"];function va(s){if(!s)return;const n={...s};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 dl(){var L,F;const s=t.useEditorStore(f=>f.card.preferences),n=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:d}=t.useEditorActions(),i=N.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=t.hasValidCardConfig(n==null?void 0:n.config)&&!a,[l,u]=N.useState(i.showRanges??!1),[p,x]=N.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c,[m,g]=N.useState(h);N.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),N.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);N.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!c;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,c]);const b=N.useMemo(()=>{var f,k;return((k=(f=n==null?void 0:n.config)==null?void 0:f.metricColumns)==null?void 0:k.map(w=>{const V=w.label||w.name||w.alias||"";return{value:V,label:V}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]);N.useEffect(()=>{var z,U;if(!s||b.length===0)return;const f={};let k=!1;const w=(z=b[1])==null?void 0:z.value;!i.targetMetricKey&&w&&(f.targetMetricKey=w,k=!0);const V=(U=b[2])==null?void 0:U.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(f.comparativeMetricKey=V,k=!0);const O=b.slice(3),P={...i.rangeKeys||{}};let _=!1;if(ba.forEach((Y,$)=>{!P[Y]&&O[$]&&(P[Y]=O[$].value,_=!0)}),_&&(f.rangeKeys=P,k=!0,i.showRanges===void 0&&(f.showRanges=!0)),k){const Y=va({...i,...f});r({...s,bulletConfig:Y})}},[b,i,s,r]);const S=f=>{const k=va({...i,...f});r({...s,bulletConfig:k})},E=(f,k)=>{const w={...i.rangeKeys||{},[f]:k.trim()};k.trim()||delete w[f],S({rangeKeys:Object.keys(w).length>0?w:void 0})},B=(f,k)=>{const w=k===""?void 0:Number(k),V={...i.ranges||{}};w===void 0||Number.isNaN(w)?delete V[f]:V[f]=w,S({ranges:Object.keys(V).length?V:void 0})},C=f=>{if(f===""){S({targetValue:void 0});return}const k=Number(f);S({targetValue:Number.isNaN(k)?void 0:k})},A=(f,k)=>{const w=k.trim(),V={...i.rangeLabels||{}};w?V[f]=w:delete V[f],S({rangeLabels:Object.keys(V).length>0?V:void 0})},T=f=>{u(f),S({showRanges:f})},D=f=>{x(f),S({rangesArePercentages:f})},I=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),M=f=>{S({orientation:f}),d(f==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(f=>({value:f.value,label:f.label}))],R=j,y=f=>{if(g(f),!f){S({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){S({disableAutoComparative:!1});return}if(i.comparativeMetricKey)S({disableAutoComparative:!1});else{const k=b.find(w=>w.value!==i.targetMetricKey);S({comparativeMetricKey:k==null?void 0:k.value,disableAutoComparative:!1})}};return e.jsxs(t.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(t.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(t.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(t.Select,{value:I,onValueChange:f=>M(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:i.targetMetricKey||"__none",onValueChange:f=>S({targetMetricKey:f==="__none"?void 0:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none",className:"text-xs",children:"None"}),b.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>S({comparativeMetricKey:f==="__none"?void 0:f,disableAutoComparative:f==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:j.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.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(t.Switch,{size:"sm",checked:m,onCheckedChange:f=>y(f)})]}),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(t.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(qe,{type:"number",className:"h-8 text-xs",value:v,onCommit:C,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(t.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:200,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(t.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(t.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(t.Switch,{size:"sm",checked:l,onCheckedChange:T})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:f=>D(f.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:ba.map(f=>{var k,w,V,O,P;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(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," LABEL"]}),e.jsx(qe,{placeholder:`Display label (${f})`,value:((k=i.rangeLabels)==null?void 0:k[f])||"",onCommit:_=>A(f,_),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((w=i.rangeKeys)==null?void 0:w[f])||"__none",onValueChange:_=>{_==="__none"?E(f,""):E(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:R.map(_=>e.jsx(t.SelectItem,{value:_.value,className:"text-xs",children:_.label},_.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN KEY"]}),e.jsx(qe,{placeholder:"Column key",value:((V=i.rangeKeys)==null?void 0:V[f])||"",onCommit:_=>E(f,_),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," VALUE"]}),e.jsx(qe,{type:"number",placeholder:p?"0.80":"Static value",value:((O=i.ranges)==null?void 0:O[f])===void 0?"":String((P=i.ranges)==null?void 0:P[f]),onCommit:_=>B(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ya(s){if(!s)return;const n={...s};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 ul(){var A,T,D,I,M,j,R,y,L,F,f,k;const s=t.useEditorStore(w=>w.card.preferences),n=t.useEditorStore(w=>w.card),a=De.useEffectiveEditorCardType(),r=t.useEditorStore(w=>w.isDevMode),{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions(),o=a==="bubble",c=a==="scatter",l=N.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(n==null?void 0:n.config)&&!r,x=N.useMemo(()=>{var w,V;return((V=(w=n==null?void 0:n.config)==null?void 0:w.metricColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(A=n==null?void 0:n.config)==null?void 0:A.metricColumns]),h=N.useMemo(()=>{var w,V;return((V=(w=n==null?void 0:n.config)==null?void 0:w.groupByColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(T=n==null?void 0:n.config)==null?void 0:T.groupByColumns]),m=N.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&h.length>=2,[l.enableGrouping,r,h.length]),[g,v]=N.useState(m);N.useEffect(()=>{v(m)},[m]);const b=w=>{const V={...s||{},bubbleScatterConfig:w};d(V),n&&i({...n,preferences:V})},S=w=>{d(w),n&&i({...n,preferences:w})};N.useEffect(()=>{if(!s||x.length===0)return;const w={};let V=!1;if(!l.xMetricKey&&x[0]&&(w.xMetricKey=x[0].value,V=!0),!l.yMetricKey&&x[1]&&(w.yMetricKey=x[1].value,V=!0),o&&!l.radiusMetricKey&&x[2]&&(w.radiusMetricKey=x[2].value,V=!0),!l.labelKey&&h[0]&&(w.labelKey=h[0].value,V=!0),m&&!l.groupKey&&h[1]&&(w.groupKey=h[1].value,w.enableGrouping=!0,V=!0),V){const O=ya({...l,...w});b(O)}},[x,h,l,s,d,o,m]);const E=w=>{const V=ya({...l,...w});b(V)},B=w=>{v(w),E({enableGrouping:w,groupKey:w?l.groupKey:void 0})};if(!o&&!c)return null;const C=o?t.Circle:t.ChartScatter;return e.jsxs(t.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(t.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"h-4 w-4"}),e.jsxs("span",{children:[o?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(t.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(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(t.Info,{className:"h-3 w-3"})}),e.jsx(t.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(t.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(t.Select,{value:l.labelKey||"",onValueChange:w=>E({labelKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:w=>E({labelKey:w})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(t.Switch,{size:"sm",checked:g,onCheckedChange:B})]}),g&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(t.Select,{value:l.groupKey||"",onValueChange:w=>E({groupKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:w=>E({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(t.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(t.Select,{value:l.xMetricKey||"",onValueChange:w=>E({xMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:w=>E({xMetricKey:w})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:l.yMetricKey||"",onValueChange:w=>E({yMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:w=>E({yMetricKey:w})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:l.radiusMetricKey||"",onValueChange:w=>E({radiusMetricKey:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:x.map(w=>e.jsx(t.SelectItem,{value:w.value,children:w.label},w.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:w=>E({radiusMetricKey:w})})]})]}),o&&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(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:l.radiusScale||"sqrt",onValueChange:w=>E({radiusScale:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.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(t.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((D=l.minRadius)==null?void 0:D.toString())||"",onCommit:w=>E({minRadius:w?Number(w):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(qe,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((I=l.maxRadius)==null?void 0:I.toString())||"",onCommit:w=>E({maxRadius:w?Number(w):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(t.Slider,{value:[l.fixedRadius||10],onValueChange:([w])=>E({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(t.Label,{className:"text-xs",children:["Point Size: ",l.fixedRadius||5]}),e.jsx(t.Slider,{value:[l.fixedRadius||5],onValueChange:([w])=>E({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(t.Switch,{size:"sm",checked:((j=(M=s==null?void 0:s.xAxisConfig)==null?void 0:M.name)==null?void 0:j.enabled)??!1,onCheckedChange:w=>{var P,_,z,U;const V=l.xMetricKey||"X Axis",O=l.yMetricKey||"Y Axis";S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:w,text:((_=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:_.text)||V}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:w,text:((U=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:U.text)||O}}})}})]}),((y=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"X Title"}),e.jsx(qe,{className:"h-8 text-xs",placeholder:l.xMetricKey||"X Axis",value:((F=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:F.text)||"",onCommit:w=>{var V;S({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:w||l.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(qe,{className:"h-8 text-xs",placeholder:l.yMetricKey||"Y Axis",value:((k=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:k.text)||"",onCommit:w=>{var V;S({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:w||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const ml=[{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 xl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:a}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",d=(n==null?void 0:n.funnelConfig)||{},i=d.percentMode??"percentOfTotal",o=d.shrinkFraction??1,c=d.labelThreshold??0,l=h=>{const m={...d,...h};a({...n||{},funnelConfig:m})},u=h=>{l({percentMode:h})},p=h=>{l({shrinkFraction:h[0]})},x=h=>{l({labelThreshold:h[0]})};return r?e.jsxs(t.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(t.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(t.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(t.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(t.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(t.RadioGroup,{value:i,onValueChange:h=>u(h),className:"space-y-2",children:ml.map(h=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(t.RadioGroupItem,{id:`funnel-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(t.Slider,{value:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"LABEL VISIBILITY THRESHOLD"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Show All"}),e.jsx(t.Slider,{value:[c],onValueChange:x,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function qt(){const s=t.useEditorStore(i=>i.card),{data:n}=t.useDashboardCardQuery(s),{keys:a}=t.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let d=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:o}=t.getKeys(i);d=o.slice(1)}return{transformedMetricKeys:d,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const hl=[{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"}],pl=[{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)"}],fl=["center","start","end"],gl=["center","start","end","top","bottom"];function $t({config:s,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:d,showAppearance:i=!0}){var g,v,b,S,E,B;const o=d??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(C,A)=>{const T={...s,[C]:A};n(T)},u=(C,A)=>{const T={...s,font:{...(s==null?void 0:s.font)||{},[C]:A}};n(T)},p=(C,A)=>{const T={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[C]:A}};n(T)},x=()=>a?"Right":"Top",h=s||{},m=h.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(t.Select,{value:h.position||"auto",onValueChange:C=>l("position",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:o.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"?x():C==="custom"?"Custom (Advanced)":t.titleCase(C)},C))})]})]}),h.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:h.anchor||"center",onValueChange:C=>l("anchor",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:fl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(h.align||"center"),onValueChange:C=>l("align",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:gl.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:t.titleCase(C)},C))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(t.Select,{value:m,onValueChange:C=>l("format",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(C=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:C==="auto"&&r?"Auto (Use Axis)":C==="none"?"None (Raw Value)":t.titleCase(C)},C))})]})]}),!["auto","none"].includes(m)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"0",value:String(((g=h.formatOptions)==null?void 0:g.decimalPlaces)??(m==="currency"?2:m==="percent"?1:0)),onSave:C=>p("decimalPlaces",Number(C)),className:""})})]}),m==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Currency"}),e.jsxs(t.Select,{value:((v=h.formatOptions)==null?void 0:v.currency)||"USD",onValueChange:C=>p("currency",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]}),["number","currency"].includes(m)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(t.Switch,{size:"sm",checked:((b=h.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:C=>p("useSuffix",C)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((S=h.formatOptions)==null?void 0:S.locale)||"en-US",onValueChange:C=>p("locale",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:pl.map(C=>e.jsx(t.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Appearance"}),e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(He,{type:"number",placeholder:"12",value:String(((E=h.font)==null?void 0:E.size)||12),onSave:C=>u("size",Number(C)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Weight"}),e.jsxs(t.Select,{value:((B=h.font)==null?void 0:B.weight)||"normal",onValueChange:C=>u("weight",C),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:h.color==="auto"||!h.color?"auto":"custom",onValueChange:C=>{C==="auto"&&l("color","auto")},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(t.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Rotation"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-12",children:e.jsx(He,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:C=>l("rotation",Number(C)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const jl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],bl=[0,1,2,3,4,5,6,8,10],vl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],yl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Nl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(t.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Cl,{})})]})}function Cl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Sl,{metricKey:n,idx:a},n))})}function Sl({metricKey:s,idx:n}){var S;const[a,r]=N.useState(!1),d=t.useEditorStore(E=>{var B;return(B=E.card)==null?void 0:B.preferences}),i=t.useEditorStore(E=>{var B,C;return(C=(B=E.card)==null?void 0:B.preferences)==null?void 0:C.datasetOptions}),o=i==null?void 0:i.find(E=>E.idx===n),{setCardPreferences:c}=t.useEditorStore(E=>E.actions),l=(o==null?void 0:o.type)||"bar",u=(o==null?void 0:o.yAxisId)||"y",p=((S=o==null?void 0:o.dataLabels)==null?void 0:S.enabled)??!1,x=l==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const B={idx:n,type:l,yAxisId:u,dataLabels:o==null?void 0:o.dataLabels,...E};if(!o)c({...d||{},datasetOptions:[...i||[],B]});else{const C=i==null?void 0:i.map(A=>A.idx===n?{...A,...B}:A);c({...d||{},datasetOptions:C})}}function m(E){h({type:E})}function g(E){h({yAxisId:E})}function v(E){h({dataLabels:{...o==null?void 0:o.dataLabels,enabled:E}})}function b(E){h({dataLabels:E})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(x,{className:"h-3 w-3"}),l==="line"?"Line":"Bar"]}),e.jsx("span",{className:t.cn("rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:u==="y2"?"Y2":"Y1"})]})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"flex items-end gap-4",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:jl.map(({type:E,icon:B,label:C})=>{const A=l===E;return e.jsxs("button",{onClick:()=>m(E),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",A?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:C})]},E)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(t.Select,{value:u,onValueChange:E=>g(E),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(t.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),l==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:E=>h({lineStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:E=>h({pointRadius:Number(E)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(E=>e.jsx(t.SelectItem,{value:String(E),className:"text-xs",children:E===0?"None":E},E))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:E=>h({pointStyle:E}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(({value:E,label:B})=>e.jsx(t.SelectItem,{value:E,className:"text-xs",children:B},E))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:p,onCheckedChange:v})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ns=[{value:"origin",label:"Origin (X-axis)",description:"Fill to the X-axis (y=0)"},{value:"start",label:"Start (Top)",description:"Fill to the top of chart area"},{value:"end",label:"End (Bottom)",description:"Fill to the bottom of chart area"},{value:"-1",label:"Previous Series",description:"Fill to the series below"},{value:"+1",label:"Next Series",description:"Fill to the series above"},{value:"false",label:"No Fill (Line)",description:"Show as line without fill"}],wl=[0,1,2,3,4,5,6,8,10],Tl=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],El=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Il(s){return s==null?"origin":s===!1?"false":s}function Dl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(t.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(kl,{})})]})}function kl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Al,{metricKey:n,idx:a},n))})}function Al({metricKey:s,idx:n}){var v;const[a,r]=N.useState(!1),d=t.useEditorStore(b=>{var S;return(S=b.card)==null?void 0:S.preferences}),i=t.useEditorStore(b=>{var S,E;return(E=(S=b.card)==null?void 0:S.preferences)==null?void 0:E.datasetOptions}),o=i==null?void 0:i.find(b=>b.idx===n),{setCardPreferences:c}=t.useEditorStore(b=>b.actions),l=Il(o==null?void 0:o.fill),u=((v=o==null?void 0:o.dataLabels)==null?void 0:v.enabled)??!1,p=ns.find(b=>b.value===l)||ns[0];function x(b){const S={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...b};if(!o)c({...d||{},datasetOptions:[...i||[],S]});else{const E=i==null?void 0:i.map(B=>B.idx===n?{...B,...S}:B);c({...d||{},datasetOptions:E})}}function h(b){x({fill:b==="false"?!1:b})}function m(b){x({dataLabels:{...o==null?void 0:o.dataLabels,enabled:b}})}function g(b){x({dataLabels:b})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(t.Select,{value:l,onValueChange:b=>h(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ns.map(b=>e.jsx(t.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:(o==null?void 0:o.lineStyle)||"solid",onValueChange:b=>x({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:El.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:b=>x({pointRadius:Number(b)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wl.map(b=>e.jsx(t.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:b=>x({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Tl.map(({value:b,label:S})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:S},b))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:u,onCheckedChange:m})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ml=[0,1,2,3,4,5,6,8,10],Ll=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Fl(){return t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(t.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Rl,{})})]})}function Rl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(Ol,{metricKey:n,idx:a},n))})}function Ol({metricKey:s,idx:n}){var b;const[a,r]=N.useState(!1),d=t.useEditorStore(S=>{var E;return(E=S.card)==null?void 0:E.preferences}),i=t.useEditorStore(S=>{var E,B;return(B=(E=S.card)==null?void 0:E.preferences)==null?void 0:B.datasetOptions}),o=i==null?void 0:i.find(S=>S.idx===n),{setCardPreferences:c}=t.useEditorStore(S=>S.actions),l=(o==null?void 0:o.lineStyle)||"solid",u=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",x=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,h=rs.find(S=>S.value===l)||rs[0];function m(S){const E={idx:n,lineStyle:l,pointRadius:u,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...S};if(!o)c({...d||{},datasetOptions:[...i||[],E]});else{const B=i==null?void 0:i.map(C=>C.idx===n?{...C,...E}:C);c({...d||{},datasetOptions:B})}}function g(S){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:S}})}function v(S){m({dataLabels:S})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.TrendingUp,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Style"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(t.Select,{value:l,onValueChange:S=>m({lineStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:rs.map(({value:S,label:E})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:E},S))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(t.Select,{value:String(u),onValueChange:S=>m({pointRadius:Number(S)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ml.map(S=>e.jsx(t.SelectItem,{value:String(S),className:"text-xs",children:S===0?"None":S},S))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:S=>m({pointStyle:S}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ll.map(({value:S,label:E})=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:E},S))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:x,onCheckedChange:g})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:o==null?void 0:o.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Pl=[0,2,4,6,8,10,12,16,20];function Bl(){const s=t.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(t.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(t.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(t.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsx(Vl,{})})]})}function Vl(){const{transformedMetricKeys:s}=qt();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,a)=>e.jsx(zl,{metricKey:n,idx:a},n))})}function zl({metricKey:s,idx:n}){var g;const[a,r]=N.useState(!1),d=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.type}),i=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),o=t.useEditorStore(v=>{var b,S;return(S=(b=v.card)==null?void 0:b.preferences)==null?void 0:S.datasetOptions}),c=o==null?void 0:o.find(v=>v.idx===n),{setCardPreferences:l}=t.useEditorStore(v=>v.actions),u=(c==null?void 0:c.borderRadius)??0,p=((g=c==null?void 0:c.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const b={idx:n,borderRadius:u,dataLabels:c==null?void 0:c.dataLabels,...v};if(!c)l({...i||{},datasetOptions:[...o||[],b]});else{const S=o==null?void 0:o.map(E=>E.idx===n?{...E,...b}:E);l({...i||{},datasetOptions:S})}}function h(v){x({dataLabels:{...c==null?void 0:c.dataLabels,enabled:v}})}function m(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{className:"flex w-full items-center justify-between gap-3 overflow-hidden px-3 py-2 text-left hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsx(t.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:s,children:s})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:u>0&&e.jsxs("span",{className:t.cn("flex items-center gap-1 rounded px-1.5 py-0.5 text-xs","border border-border bg-background text-muted-foreground"),children:[e.jsx(t.ChartColumn,{className:"h-3 w-3"}),"r:",u]})})]})}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"border-t border-border",children:e.jsxs("div",{className:"space-y-4 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Style"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(t.Select,{value:String(u),onValueChange:v=>x({borderRadius:Number(v)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.map(v=>e.jsx(t.SelectItem,{value:String(v),className:"text-xs",children:v===0?"None":`${v}px`},v))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx($t,{config:c==null?void 0:c.dataLabels,onChange:m,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _l=[0,1,2,3,4,5,6,8,10],ql=[{value:"circle",label:"Circle ●"},{value:"rect",label:"Square ■"},{value:"rectRounded",label:"Rounded ▢"},{value:"rectRot",label:"Diamond ◆"},{value:"triangle",label:"Triangle ▲"},{value:"cross",label:"Cross +"},{value:"crossRot",label:"X ×"},{value:"star",label:"Star ★"},{value:"dash",label:"Dash —"},{value:"line",label:"Line │"}],$l=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Kl(){const s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(a))return null;const o=(c,l)=>{const u={...n||{},lineStyleConfig:{...r,[c]:l}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(t.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(Dn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all series. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(t.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:c=>o("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:$l.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:c=>o("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:_l.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:c=>o("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ql.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}const Gl=[0,2,4,6,8,10,12,16,20],Ul=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}],Hl=[{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70%"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"1",label:"100%"}];function Ql(){const s=t.useEditorStore(c=>c.card),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),a=De.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:d,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(c,l)=>{const u={...n||{},barStyleConfig:{...r,[c]:l}};d(u),i({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(t.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(t.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(t.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default styles for all bars. Override per-series in the Series section."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:c=>o("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:c=>o("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:c=>o("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(({value:c,label:l})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:l},c))})]})]})]})})]})}function Jl(){const s=t.useEditorStore(a=>{var r,d;return(d=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:d.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(t.AccordionItem,{value:"stacked-sort",children:[e.jsx(t.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(t.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort Order"}),e.jsx(at,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:a=>{n(a)}})]})})]})}const Yl=["kpi"],Na={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ls=2;function lt(s){return typeof s=="string"?s.trim().toLowerCase():((s==null?void 0:s.id)||(s==null?void 0:s.qualifiedFieldName)||(s==null?void 0:s.name)||(s==null?void 0:s.label)||"").trim().toLowerCase()}function Wl(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Xl(s){return{...s,role:"groupby"}}function Zl(){var E,B;const s=t.useEditorStore(C=>C.card),n=t.useEditorStore(C=>C.actions.updateCardConfig),a=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),d=((E=s.config)==null?void 0:E.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},o=i.breakdownDimensions||[],c=Yl.includes(a),l=d.length>0,u=i.enabled===!0,p=c&&l,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,a),h=Na[x]||Na.none,m=Array.from(new Map(r.filter(Wl).map(C=>[lt(C),Xl(C)])).values()),g=new Set(m.map(C=>lt(C))),v=new Set(o.map(C=>lt(C)).filter(C=>C&&g.has(C)));if(!c)return null;const b=C=>{n(s.id,{summary:{...i,...C}})},S=(C,A)=>{const T=lt(C),D=m.filter(M=>v.has(lt(M))),I=A?v.has(T)?D:[...D,C].slice(0,ls):D.filter(M=>lt(M)!==T);b({breakdownDimensions:I})};return e.jsxs(t.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(t.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(t.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!l&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(t.Switch,{size:"sm",id:"summary-enabled",checked:u,disabled:!p,onCheckedChange:C=>{if(!C){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({enabled:!0,showOnCard:i.showOnCard??!0,includeInDashboardSummary:i.includeInDashboardSummary??!0,anomalyEnabled:i.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",h]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(t.Switch,{size:"sm",id:"summary-show-on-card",checked:i.showOnCard===!0,disabled:!u,onCheckedChange:C=>b({showOnCard:C})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(t.Switch,{size:"sm",id:"summary-include-rollup",checked:i.includeInDashboardSummary===!0,disabled:!u,onCheckedChange:C=>b({includeInDashboardSummary:C})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[o.length,"/",ls]})]}),m.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:m.map(C=>{const A=lt(C),T=v.has(A),D=v.size>=ls,I=!u||!T&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${A}`,checked:T,disabled:I,onCheckedChange:M=>S(C,M===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${A}`,className:"cursor-pointer text-xs",children:C.label||C.name})]},A)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(t.Switch,{size:"sm",id:"summary-anomaly",checked:i.anomalyEnabled!==!1,disabled:!u,onCheckedChange:C=>b({anomalyEnabled:C})})]})]})]})}const eo=[];function to(){var d;const s=t.useEditorStore(i=>i.card),n=((d=s==null?void 0:s.config)==null?void 0:d.metricColumns)??eo,{updateMetricColumn:a,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||n.length===0?null:e.jsxs(t.AccordionItem,{value:"metric-formats",className:"border-b-0",children:[e.jsx(t.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(hn,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:n.map(i=>e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 p-3",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:i.label||i.name}),e.jsx(hs,{value:i.format,onChange:o=>{var c;a(s.id,i.id,{format:o}),r({...s,config:{...s.config,metricColumns:(((c=s.config)==null?void 0:c.metricColumns)||[]).map(l=>l.id===i.id?{...l,format:o}:l)}})}})]},i.id))})]})}const so=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function ao(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:d}=t.useEditorActions();if(!s||!so.has(a||""))return null;const i=n==null?void 0:n.tooltipConfig,o=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",c=l=>{const u={...n||{},tooltipConfig:{...i||{},...l}};r(u),d({...s,preferences:u})};return e.jsxs(t.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(t.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(t.Info,{className:"h-4 w-4"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Override metric format"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Keep this off to inherit from each metric."})]}),e.jsx(t.Switch,{size:"sm",checked:o==="override",onCheckedChange:l=>c({formatMode:l?"override":"inherit",mode:l?"override":"inherit"})})]}),o==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:l=>c({formatMode:"override",mode:"override",formatOptions:l}),showTitle:!1})]})]})}function $a({mode:s}){const n=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(Nl,{}),(n==="area"||n==="stackedArea")&&e.jsx(Dl,{}),n==="line"&&e.jsx(Fl,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Bl,{}),e.jsx(Kl,{}),e.jsx(Ql,{}),e.jsx(ol,{}),s==="config"&&e.jsx(ll,{}),s==="config"&&e.jsx(Zl,{}),e.jsx(cl,{}),n==="bullet"&&e.jsx(dl,{}),n==="funnel"&&e.jsx(xl,{}),(n==="bubble"||n==="scatter")&&e.jsx(ul,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Jl,{}),e.jsx(to,{}),e.jsx(sl,{}),e.jsx(al,{}),e.jsx(nl,{}),e.jsx(rl,{}),e.jsx(ao,{})]})}function no(){const s=t.useEditorStore(a=>a.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:n}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx($a,{mode:"dev"})})]}):null}function ro(){const s=t.useEditorStore(d=>d.card),n=s.type;if(t.getVisualizationMode(s)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(t.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(t.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(t.AlertDescription,{children:"Built-in chart settings are hidden while this card is in dynamic mode. Query and data edits still apply, and the dynamic visual editor in the main panel controls the rendered output."})]})});function r(){switch(n){case"kpi":return e.jsx(Or,{});case"table":return e.jsx(Xr,{});case"map":return e.jsx(zr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Va,{})});case"text":return e.jsx(el,{});default:return e.jsx(no,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function lo(){const s=N.useRef(null),n=N.useRef(null),a=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),d=t.useEditorStore(x=>x.showAIDialog),[i,o]=N.useState(!1),c=a&&!d,l=c&&(!r||i),u=r&&c,p=()=>o(x=>!x);return N.useEffect(()=>{var x,h,m,g;d?((x=s.current)==null||x.resize(0),(h=n.current)==null||h.resize(0)):((m=s.current)==null||m.resize(25),(g=n.current)==null||g.resize(25))},[d]),e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Zn,{})}),e.jsx(t.ResizableHandle,{withHandle:!0,className:"data-[panel-group-direction=vertical]:ml-2 data-[panel-group-direction=vertical]:mr-6 data-[panel-group-direction=vertical]:w-auto"}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:l?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(ro,{})})}),!d&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(ma,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function oo(s){var Ee;t.useAIInteractionStore(K=>K.currentAIContext);const[n,a]=N.useState(""),[r,d]=N.useState(null),{authToken:i,tokenProps:o}=t.useSemaphorContext(),c=t.useEditorStore(K=>K.card.id),l=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.sql}),u=t.useEditorStore(K=>K.isDevMode),p=t.useEditorStore(K=>{var le;return(le=K==null?void 0:K.card)==null?void 0:le.python}),{setCardPython:x,setCardSql:h,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore(K=>K.currentAssitantScope)||[],S=t.useEditorStore(K=>K.userInputForAI),E=t.useEditorStore(K=>K.triggerAIRun),B=t.useEditorStore(K=>K.card),C=t.useEditorStore(K=>K.selectedDatabaseName),A=t.useEditorStore(K=>K.selectedTableName),T=t.useEditorStore(K=>K.selectedConnectionId),D=t.useEditorStore(K=>K.selectedSchemaName),I=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:M,refetch:j,data:R}=t.useDashboardCardQuery(B),{setTriggerAIRun:y,setCurrentAssitantScope:L,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:k,selectedDatamodelId:w}=t.useEditorAside(),V=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,O=N.useRef(t.createAssistantConversationId()),P=N.useRef(null),_=N.useRef(c),z=N.useRef(!1),U=()=>{const K=P.current;K&&(P.current=null,O.current=t.createAssistantConversationId(),K==="clear"&&$([]))},{messages:Y,setMessages:$,regenerate:ee,error:ne,sendMessage:me,status:ve,addToolResult:se,stop:re,clearError:de}=t.useChat({transport:new t.DefaultChatTransport({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:O.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var le;if(z.current=!1,K.name==="AbortError"||(le=K.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",K),U()},onToolCall:ue,onFinish({isAbort:K,isDisconnect:le,isError:Ne}){z.current=!1,a(""),console.log(K?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":Ne?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),pe=N.useCallback(K=>{z.current=!0;try{const le=me(K);return t.isPromiseLike(le)?le.catch(Ne=>{throw z.current=!1,Ne}):le}catch(le){throw z.current=!1,le}},[me]),X=N.useCallback(()=>{z.current=!0;try{const K=ee();return t.isPromiseLike(K)?K.catch(le=>{throw z.current=!1,le}):K}catch(K){throw z.current=!1,K}},[ee]),Z=K=>{let le=!1;$(Ne=>{const Pe=typeof K=="function"?K(Ne):K;if(Pe.length===0){if(z.current)return P.current="clear",le=!0,Ne;P.current=null,O.current=t.createAssistantConversationId()}return Pe}),le&&re()};N.useEffect(()=>{if(_.current!==c){if(_.current=c,z.current){P.current!=="clear"&&(P.current="rotate"),re();return}P.current=null,O.current=t.createAssistantConversationId()}},[c,re]),N.useEffect(()=>{E&&S&&(pe({role:"user",parts:[{type:"text",text:S}]}),y(!1))},[E,S,pe,y]);async function ue({toolCall:K}){var le,Ne,Pe,W,fe,Ce,ke,Se,Be,ze,Xe,Ye,We,ae,Ie,Oe;if(["createChartFromSql","createForecast"].includes(K.toolName)){const be=((le=K.input)==null?void 0:le.sql)??((Ne=K.args)==null?void 0:Ne.sql),Ge=((Pe=K.input)==null?void 0:Pe.python)??((W=K.args)==null?void 0:W.python),Te=((fe=K.input)==null?void 0:fe.chartType)??((Ce=K.args)==null?void 0:Ce.chartType);g(Te),h(be),x(Ge),m(!0),se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!l){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:l,python:p||""}})}else if(K.toolName==="generateQueryConfig"){a("Generating query config...");const be=((ke=K.input)==null?void 0:ke.chartType)??((Se=K.args)==null?void 0:Se.chartType),Ge=((Be=K.input)==null?void 0:Be.queryConfig)??((ze=K.args)==null?void 0:ze.queryConfig);((Xe=K.input)==null?void 0:Xe.cardConfig)??((Ye=K.args)==null||Ye.cardConfig),g(be),F(Ge),h(void 0),x(void 0);const Te=await j();if((We=Te==null?void 0:Te.data)!=null&&We.error){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:Ge,message:(ae=Te==null?void 0:Te.data)==null?void 0:ae.error.message}});return}if((Ie=Te==null?void 0:Te.data)!=null&&Ie.records){se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}se({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Oe=Te==null?void 0:Te.data)==null?void 0:Oe.records}})}else a("Analyzing...")}function Fe(K){const le=t.removeFromScopeArray(b,K);te(le)}function te(K){const le=t.sanitizeAIScope(K);L(le),$(Ne=>[...Ne,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(le)}`}]}])}function ge(){const K={databaseName:C||"",schemaName:D||"",tableName:A||"",datamodelId:w||"",datamodelName:t.resolveDatamodelName(f),connectionId:T||"",connectionType:k||""},le=t.dedup([...b,K]);te(le)}function ye(){const K={databaseName:C||"",schemaName:D||"",tableName:A||"",datamodelName:t.resolveDatamodelName(f),connectionId:T||"",connectionType:k||"",datamodelId:w||""};if(!t.isInAiScopeArray([...I||[],...b],K)||b.length===0){const Ne=t.dedup([...I||[],...b,K]).filter(Pe=>Pe.connectionId===K.connectionId);te(Ne)}}const je=!["ready","error"].includes(ve),we=t.getErrorMessage(ne);return{messages:Y,setMessages:Z,sendMessage:pe,regenerate:X,isLoading:je,handleSetAIScope:ye,handleAddCurrentTableToScope:ge,removeFromCurrentSelections:Fe,currentAssitantScope:b,setCurrentAssitantScope:L,stop:re,status:ve,toolStatus:n,llmUsage:r,onFinish:s,errorMessage:we,clearError:de}}const io=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ca({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:a}){const r=N.useRef(null),d=N.useRef(!1),[i,o]=N.useState(!1),[c,l]=N.useState(t.isDevEnv),[u,p]=N.useState(!1),[x,h]=N.useState(!1),[m,g]=N.useState(!1),v=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:S,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:C}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:T}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),M=t.useEditorStore(ae=>{var Ie;return(Ie=ae.card.dataSource)==null?void 0:Ie.selectedEntities}),j=t.useEditorStore(ae=>ae.actions.setCardSql),R=t.useEditorStore(ae=>ae.actions.setRunSql),y=t.useEditorStore(ae=>ae.showAIDialog),L=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:k}=t.useEditorActions(),{assistantProfile:w}=t.useAssistantProfile(),{messages:V,setMessages:O,sendMessage:P,isLoading:_,stop:z,status:U,llmUsage:Y,errorMessage:$,clearError:ee}=oo(),[ne,me]=N.useState(""),ve=ae=>{me(ae.target.value)},se=ae=>{ae.preventDefault();const Ie=ne.trim();if(!Ie&&A.length===0)return;const Oe=[];Ie&&Oe.push({type:"text",text:Ie}),A.forEach(be=>{be.data&&Oe.push({type:"file",mediaType:be.type,filename:be.name,url:`data:${be.type};base64,${be.data}`})}),P({role:"user",parts:Oe}),me(""),C("editor"),je({force:!0})},{visibleMessages:re,hasMoreMessages:de,totalMessageCount:pe,loadMoreMessages:X,resetMessageWindow:Z}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:ue,contentRef:Fe,isAtBottom:te,hasNewMessages:ge,newMessageCount:ye,scrollToBottom:je,handleScroll:we,resetNewMessageCount:Ee}=t.useAutoScroll(re,{threshold:40,behavior:"smooth",isStreaming:_});N.useEffect(()=>{var ae;y&&!d.current&&((ae=r.current)==null||ae.focus()),d.current=y},[y]),N.useEffect(()=>{y&&(E(!1),S({selectedEntities:M||[]}))},[D,M,S,E,y]),t.useAutoSubmitQueue({assistantType:"editor",status:U,isLoading:_,sendMessage:P});const{hasActiveTools:K,activeToolText:le}=t.useActiveToolStatus(V),Ne=N.useCallback(ae=>{n==null||n(ae),s===void 0&&g(ae)},[s,n]);N.useEffect(()=>{if(!v)return;function ae(Ie){Ie.key==="Escape"&&Ne(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[v,Ne]);const Pe=N.useCallback(ae=>{P({role:"user",parts:[{type:"text",text:ae}]}),je({force:!0})},[P,je]),W=N.useCallback(async()=>{const ae=JSON.stringify(V??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),t.ue.success("Conversation copied")}catch(Ie){console.error("Failed to copy conversation",Ie),t.ue.error("Unable to copy conversation")}},[V]),fe=N.useCallback(()=>{Ne(!v)},[v,Ne]);function Ce(ae,Ie){Ie==="sql"?(j(ae),R(!0)):Ie==="python"&&(f(ae),R(!0))}function ke(){b.selectedEntities.length===0&&S({selectedEntities:T})}function Se(ae){ke();const Ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};P(Ie)}function Be(ae){ke(),P({role:"user",parts:[{type:"text",text:ae}]})}function ze(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:o,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:l,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function Xe(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Ye=(ne==null?void 0:ne.length)===0&&(V==null?void 0:V.filter(ae=>ae.role==="user").length)===0,We=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",v&&"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:[Xe(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(w==null?void 0:w.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[ze(),c&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:W,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:fe,children:v?e.jsx(t.Minimize2,{className:"size-4"}):e.jsx(t.Maximize2,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{O([]),B("editor"),ee(),Z()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{F(!1)},children:e.jsx(t.X,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:ue,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:we,children:e.jsxs("div",{ref:Fe,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[de&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:X,className:"text-xs",children:["Load ",Math.min(5,pe-re.length)," ","more messages (",pe-re.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:re,showTools:c,handleRun:Ce,showSystemMessage:u,onQuickReply:Pe,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:U,errorMessage:$,activeToolText:_&&K?le:void 0})]})}),y&&!te&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{je({force:!0}),Ee()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(t.ChevronDown,{className:"h-4 w-4"}),ge&&ye>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:ye>9?"9+":ye})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Ye&&!w&&e.jsx(t.Placeholders,{onClick:Se,placeholders:io}),e.jsx("div",{children:Ye&&w&&e.jsx(t.SeedQuestions,{seedQuestions:w.seedQuestions||[],handleSeedQuestionClick:Be})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:me,stop:z,input:ne,handleInputChange:ve,handleSubmit:ae=>{ke(),se(ae),je({force:!0})},isLoading:_,status:U,assistantType:"editor",onFocus:()=>{}})]}),Y&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",Y.inputTokens," prompt tokens, ",Y.outputTokens," ","completion tokens, ",Y.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:T,open:x,onOpenChange:h,dataSource:I||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{E(!0),S({...b,selectedEntities:ae})}})]});return v&&a?cn.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:We})}),a):We}function co(s,n,a){if(!n)return!1;const r=n.qualifiedFieldName,d=n.qualifiedEntityName,i=d&&n.name?`${d}.${n.name}`:r;return s.some(o=>{if(!(t.getDataType(o.dataType||"")==="date"))return!1;const l=t.getSelectedDateFilterColumn(o,a),u=l.split("."),p=u[u.length-1]||l,x=u.length>1?u.slice(0,-1).join("."):void 0,h=o.qualifiedTableName||x,m=h?`${h}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===n.name:m?m===i:p===n.name})}function uo({aliasTemplate:s,onAliasTemplateChange:n}){var l;const[a,r]=N.useState(s),[d,i]=N.useState(!1),o=(l=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],c=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:d?a:s,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&d&&a!==s?(n(a),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),d&&a!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function mo({valueAliases:s,onValueAliasesChange:n}){const[a,r]=N.useState(null),[d,i]=N.useState(""),[o,c]=N.useState(""),l=()=>{n({...s,"":""})},u=x=>{const h={...s};delete h[x],n(h)},p=x=>{const h={...s};delete h[x],h[d]=o,n(h),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([x,h],m)=>e.jsx("div",{className:"flex items-center gap-2",children:a===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:g=>i(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:o,onChange:g=>c(g.target.value),className:"h-8 w-24 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Enter"?p(x):g.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(x),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),c(h)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},x+m)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function xo({idx:s}){var c;const n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),a=t.useEditorStore(l=>{var u;return(u=l.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),d=(c=n==null?void 0:n.chartOptions)==null?void 0:c.indexAxis,i=a==null?void 0:a.find(l=>l.idx===s);function o(l,u){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...n,datasetOptions:[...a||[],{idx:u,datalabels:p}]});else{const x={...i};x.datalabels=p;const h=a==null?void 0:a.map(m=>m.idx===u?x:m);r({...n,datasetOptions:h})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(t.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>o("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(vn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>o("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>o("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(yn,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function ps({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function ho(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function po({col:s,idx:n,className:a,iconClassName:r,children:d}){const i=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),o=t.useEditorStore(p=>{var x,h;return(h=(x=p.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),c=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=t.useEditorStore(p=>p.actions);function u(p){if(!c)l({...i,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...c};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const h=o==null?void 0:o.map(m=>m.idx===n?x:m);l({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[d||e.jsx(ps,{className:"max-w-[100px]",title:s,children:ho(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.ChartColumnIncreasing,{onClick:()=>u("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartLine,{onClick:()=>u("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(t.ChartArea,{onClick:()=>u("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xo,{idx:n})]})]})}function fo(){const s=t.useEditorStore(c=>c.card.type),n=t.useEditorStore(c=>c.isDevMode),a=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:r}=t.useEditorStore(c=>c.actions);function d(c){var p;const l={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},u={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...l}}};r(u)}function i(){var c,l,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.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:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function o(){var c,l,u;return e.jsx("div",{children:e.jsxs(t.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:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?i():o()})}function go({column:s}){const n=t.useEditorStore(l=>l.card.type),a=t.useEditorStore(l=>{var u,p;return(p=(u=l.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],d=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=d?r.indexOf(d):-1;function o(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx(po,{idx:i,col:d,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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(fo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&c()]})}function jo({field:s,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:d}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),o=i==null?void 0:i.dataSource,c=["attribute-values",s.entityName,s.name,n,a],l=t.useQuery({queryKey:c,queryFn:async()=>{if(!(o!=null&&o.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:o.connectionId,cardConfig:u,cardDataSource:o,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const x=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=s.name;return((x==null?void 0:x.records)||[]).map(g=>{const v=g[h]||g[s.alias||h]||g[s.label];return{id:v||"",value:v||"",label:String(v||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!s&&!!(o!=null&&o.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 Ka({open:s,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:d,onSave:i}){var B,C;const o=!!d,[c,l]=N.useState(o?"values":"fields"),[u,p]=N.useState(""),[x,h]=N.useState({id:(d==null?void 0:d.id)||t.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),m=a.filter(A=>{var D;return o?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(I=>I.field.id===A.id))&&A.label.toLowerCase().includes(u.toLowerCase())}),g=A=>{h({...x,field:A}),l("values")},v=()=>{if(x.field&&x.selectedValues.length>0){const A={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let T;if(o){const D=((r==null?void 0:r.conditions)||[]).map(I=>I.id===d.id?A:I);T={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];T={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,A],groups:[]}}i(T),n(!1)}},b=()=>{if(!o||!d)return;const A=((r==null?void 0:r.conditions)||[]).filter(T=>T.id!==d.id);if(A.length>0){const T={...r,conditions:A};i(T)}else i(void 0);n(!1)},S=A=>{h({...x,selectedValues:A})},E=()=>{o&&d?(h({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),l("values")):(h({id:t.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return N.useEffect(()=>{s&&E()},[s,o,d]),e.jsx(t.Dialog,{open:s,onOpenChange:n,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:o?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(C=x.field)==null?void 0:C.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.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(A=>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:[A.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(A.value)?`${A.value.length} values`:String(A.value)})]},A.id))})]}),c==="fields"&&!o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search fields...",value:u,onChange:A=>p(A.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(A=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(A),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(A.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:A.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[A.entityName,".",A.name]})]})]},A.id))}),m.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),m.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(bo,{field:x.field,selectedValues:x.selectedValues,onValuesChange:S,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(t.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:E,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function bo({field:s,selectedValues:n,onValuesChange:a,onBack:r}){const[d,i]=N.useState(""),{values:o,isLoading:c,isFetching:l}=jo({field:s,searchQuery:d,limit:500}),u=d?o.filter(h=>String(h.value).toLowerCase().includes(d.toLowerCase())):o,p=h=>{const m=n.includes(h);a(m?n.filter(g=>g!==h):[...n,h])},x=()=>{n.length===u.length&&u.length>0?a([]):a(u.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(t.Label,{className:"text-sm font-medium",children:["Select values for ",s.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:d,onChange:h=>i(h.target.value),className:"pl-10"})]}),c||l?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(t.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(t.Checkbox,{checked:n.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(t.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(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(h.value),children:[e.jsx(t.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>p(h.value)}),e.jsx(ps,{className:"text-sm",children:h.label})]},h.id))})]})]})}function vo({field:s,zone:n,index:a,sortDirection:r,onSortDirectionChange:d,hasPivotColumns:i=!1,cardType:o}){var Ns,Cs,Ss,ws,Ts,Es,Is,Ds,ks,As,Ms,Ls,Fs,Rs,Os,Ps,Bs,Vs,zs,_s,qs,$s,Ks,Gs,Us,Hs,Qs,Js,Ys,Ws,Xs,Zs,ea;const{attributes:c,listeners:l,setNodeRef:u,transform:p,transition:x,isDragging:h}=t.useSortable({id:s.id}),m=t.useEditorStore(G=>G.card),g=t.useEditorStore(G=>G.frame),v=t.useDashboardStore(G=>G.isVisualEditing),b=t.useDashboardStore(G=>G.selectedSheetId),S=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:B,isLoading:C}=t.useFilterableFields(),{userContext:A}=t.useCurrentUserInfo(),T=(A==null?void 0:A.type)==="organization",{updateLabel:D,handleAggregationChange:I,handleDateFormatChange:M,handleGranularityChange:j,handleAliasTemplateChange:R,handleValueAliasesChange:y,handleMetricFormatChange:L,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:k,handleMetricWindowOrderByChange:w,handleMetricWindowDirectionChange:V,handleMetricWindowPartitionToggle:O,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:U,handleMetricPercentOfTotalOutputChange:Y,handleKpiShowTrendlineChange:$,handleKpiTrendlineWindowChange:ee,handleKpiTrendlineGranularityChange:ne,handleMetricTargetValueChange:me}=t.useFieldManagement(m),[ve,se]=N.useState(!1),[re,de]=N.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[pe,X]=N.useState(!1),[Z,ue]=N.useState(!1),[Fe,te]=N.useState(null),ge=N.useMemo(()=>{const G=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Q=G(s.id),ce=E.find(oe=>{if(s.qualifiedFieldName&&oe.qualifiedFieldName&&oe.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&oe.qualifiedEntityName&&oe.qualifiedEntityName===s.qualifiedEntityName&&oe.name===s.name)return!0;const Ae=G(oe.id);return!!(Q&&Ae&&Q===Ae)});return{dataType:(ce==null?void 0:ce.dataType)||s.dataType,resolvedFromScopedField:!!ce}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),ye=t.getGranularityOptionsForFieldType(ge.dataType),[je,we]=N.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,K]=N.useState(s.customFormat||""),[le,Ne]=N.useState(!!s.customFormat),Pe=N.useRef(null),[W,fe]=N.useState(s.aliasTemplate||""),[Ce,ke]=N.useState(s.valueAliases||{}),[Se,Be]=N.useState((Ns=s.parameters)==null?void 0:Ns.filters),ze=G=>{G==="custom"?Ne(!0):(Ne(!1),we(G),(n==="groupBy"||mt)&&M(a,G,"",n))},Xe=G=>{K(G),(n==="groupBy"||mt)&&M(a,"custom",G,n)},Ye=G=>{var oe;const ce=(oe=t.getDateFormatOptionsForGranularity(G)[0])==null?void 0:oe.value;ce&&!le&&(we(ce),n==="groupBy"&&M(a,ce,"",n)),n==="groupBy"&&j(a,G)},We=G=>{fe(G),n==="metrics"&&R(a,G)},ae=G=>{ke(G),n==="metrics"&&y(a,G)},Ie=G=>{D(n,a,G)},Oe=t.getExpressionFieldKind(s),be=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),Te=s.role==="metric"&&Ge,bt=Ge&&(Oe==="user_calculated"||Oe==="inline_expression"&&s.fieldScope!=="domain"),Ze=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(G=>t.matchesCalculatedField(G,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Ze),Ue=Oe==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=Ue?"domain":Tt?"dashboard":"card",et=Ue?Et||s:Tt&&Ze?Ze:s,It=G=>{var Q;if(Be(G),n==="metrics"){const ce={...s,parameters:{...s.parameters,filters:G}},oe=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];oe[a]=ce,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}X(!1)},vt=()=>{F(n,a)},Kt={transform:t.CSS.Transform.toString(p),transition:x},Dt=t.getDataType(ge.dataType||s.dataType),dt=Dt==="date",ut=o==="kpi",mt=n==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,Qe=t.useDashboardStore(G=>{var Q;return(Q=G.dashboard)==null?void 0:Q.filters}),Gt=t.useDashboardStore(G=>G.filterValues),tt=s.granularity||"day",kt=ye.includes(tt)?tt:"day",yt=n==="groupBy"&&!ye.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=le?"custom":ht.some(G=>G.value===je)?je:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";N.useEffect(()=>{var ce;if(C||!yt){Pe.current=null;return}const G=`${s.id}:${tt}:${ge.dataType||s.dataType||""}:${a}`;if(Pe.current===G)return;Pe.current=G;const Q="day";if(j(a,Q),!le){const oe=(ce=t.getDateFormatOptionsForGranularity(Q)[0])==null?void 0:ce.value;oe&&(we(oe),M(a,oe,"",n))}},[s.dataType,s.id,M,j,yt,a,le,C,tt,ge.dataType,n]);const Ht=!!o&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),Qt=o==="kpi"||o==="table",Ke=N.useMemo(()=>$e==null?void 0:$e.find(G=>t.getDataType(G.dataType||"")==="date"),[$e]),At=N.useMemo(()=>($e||[]).some(G=>t.getDataType(G.dataType||"")==="date"),[$e]),pt=N.useMemo(()=>{var oe;if(!Ke)return!1;const G=(oe=m.config)==null?void 0:oe.filters;if(!G)return!1;const Q=Ae=>{const Le=Ae.field;return Le?Ke.id&&Le.id===Ke.id||Ke.qualifiedFieldName&&Le.qualifiedFieldName===Ke.qualifiedFieldName?!0:Le.name===Ke.name:!1},ce=Ae=>Ae.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&Q(_e))?!0:Ae.groups.some(_e=>ce(_e));return ce(G)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=N.useMemo(()=>co(Qe||[],Ke,Gt),[Qe,Gt,Ke]),Nt=pt||Mt,q=s,J=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",H=t.isMetricTransformEnabled(q),ie=H?J:null,xe=t.supportsMetricTransformForMetric({cardType:o||"table",cardConfig:m.config||{},metric:q,transformMode:ie||"running_total"}),he=!!q.comparisonType&&q.comparisonType!=="none",Me=t.getRunningTotalOrderByCandidates($e||[]),Re=((Ms=(As=(ks=q.parameters)==null?void 0:ks.windowTransform)==null?void 0:As.orderBy)==null?void 0:Ms.fieldId)||"",Je=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Me.find(G=>G.id===Re),st=ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta",Ve=H&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:o||"table",cardConfig:m.config||{},orderByFieldId:Re||void 0}),Jt=new Set(((Ps=(Os=q.parameters)==null?void 0:Os.windowTransform)==null?void 0:Ps.partitionByFieldIds)||ft),Yt=o==="pivotTable"||t.isSubtotalEnabledAggregateTable(o||"table",m.config||{}),gs=[...($e||[]).filter(G=>G.id&&(!st||G.id!==Re)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(G=>G.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Ua=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Ha=((Hs=(Us=(Gs=q.parameters)==null?void 0:Gs.windowTransform)==null?void 0:Us.previousPeriodDelta)==null?void 0:Hs.mode)||"absolute",bs=((Ys=(Js=(Qs=q.parameters)==null?void 0:Qs.windowTransform)==null?void 0:Js.percentOfTotal)==null?void 0:Ys.scope)||"grand_total",Qa=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Ja=N.useMemo(()=>(xt||[]).some(G=>G.comparisonType==="start_vs_end"),[xt]);N.useEffect(()=>{H&&de(!0)},[H]);const Ya=n!=="pivotBy"&&n!=="sortBy",Wa=dt&&n==="groupBy"&&(!ut||Ja),Xa=!ut&&dt&&(n==="groupBy"||mt),Za=o==="kpi"&&dt&&n==="groupBy",en=n==="metrics",vs=Ht&&n==="metrics",tn=()=>{const G=s,Q=n==="metrics"&&Te;return e.jsxs("div",{className:"space-y-1",children:[!Q&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:ce=>{ce.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-muted-foreground/80",children:`${s.entityName}.${s.name}`}),Q&&G.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(G.calculatedFormula),onPointerDown:ce=>{ce.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:["= ",t.formatDisplayFormula(G.calculatedFormula)]})]})},sn=()=>Ya?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(He,{value:s.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,an=()=>n!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:r||"asc",onValueChange:G=>d(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),ys=()=>Wa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:kt,onValueChange:Ye,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(t.SelectContent,{children:ye.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,nn=()=>Xa?e.jsxs(e.Fragment,{children:[ys(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:Ut,onValueChange:ze,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ht.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),le&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Ee,onChange:G=>{G.stopPropagation(),Xe(G.target.value)},onClick:G=>G.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,rn=()=>{var Q,ce,oe,Ae;const G=Za;return G?e.jsx(e.Fragment,{children:G&&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(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.Switch,{size:"sm",checked:((Q=m.config)==null?void 0:Q.showTrendline)||!1,onCheckedChange:$})]})}),((ce=m.config)==null?void 0:ce.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input,{type:"number",min:"1",max:"365",value:((oe=m.config)==null?void 0:oe.trendlineWindow)||30,onChange:Le=>{const _e=parseInt(Le.target.value)||30;ee(_e)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Ae=m.config)==null?void 0:Ae.trendlineGranularity)||"day",onValueChange:ne,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})}):null},ln=()=>{if(!en)return null;const G=Te;return e.jsxs(e.Fragment,{children:[G&&T&&!Ue&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>ue(!0),children:[e.jsx(t.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:Q=>{I(a,Q)},disabled:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Number Format"}),e.jsx(hs,{value:q.format,onChange:Q=>L(a,Q),showTitle:!1})]}),e.jsx(t.Collapsible,{open:re,onOpenChange:de,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(t.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between rounded-sm px-0.5 py-0.5 text-left",children:[e.jsx("div",{className:"text-xs font-medium text-foreground",children:"Metric Transform"}),e.jsxs("div",{className:"flex items-center text-[11px] text-muted-foreground",children:[!re&&e.jsx("span",{className:"mr-2",children:H?t.toTitleCase(J.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",re?"rotate-180":"")})]})]})}),e.jsxs(t.CollapsibleContent,{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Transform"}),e.jsxs(t.Select,{value:H?J:"none",onValueChange:Q=>k(a,Q),disabled:!xe.supported&&!H,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select transform..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"None"}),e.jsx(t.SelectItem,{value:"running_total",disabled:he,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:he,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:he,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:he,children:"Percent of Total"})]})]}),!xe.supported&&!H&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xe.reason}),he&&!H&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),H&&e.jsxs(e.Fragment,{children:[st&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order By"}),e.jsxs(t.Select,{value:Re,onValueChange:Q=>w(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select order field..."})}),e.jsx(t.SelectContent,{children:Me.filter(Q=>!!Q.id).map(Q=>e.jsx(t.SelectItem,{value:Q.id,className:"text-xs",children:Q.label||Q.name},Q.id))})]}),!Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Ve&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. The transform will follow the selected order field."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Direction"}),e.jsxs(t.Select,{value:Je,onValueChange:Q=>V(a,Q),disabled:!Re,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select direction..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]})]}),ie==="moving_average"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Window Size"}),e.jsx(t.Input,{type:"number",min:1,className:"h-8 text-xs",value:js,onChange:Q=>P(a,Number(Q.target.value))}),e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Min Periods"}),e.jsx(t.Input,{type:"number",min:1,max:js,className:"h-8 text-xs",value:Ua,onChange:Q=>_(a,Number(Q.target.value))})]}),ie==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:Q=>z(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"absolute",children:"Absolute Delta"}),e.jsx(t.SelectItem,{value:"percent",children:"Percent Delta"})]})]})]}),ie==="percent_of_total"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Scope"}),e.jsxs(t.Select,{value:bs,onValueChange:Q=>U(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select scope..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"grand_total",children:"Grand Total"}),e.jsx(t.SelectItem,{value:"partition_total",children:"Partition Total"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Qa,onValueChange:Q=>Y(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select output..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"percent",children:"Percent"}),e.jsx(t.SelectItem,{value:"fraction",children:"Fraction"})]})]})]})]}),(ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta"||ie==="percent_of_total"&&bs==="partition_total")&&gs.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Reset By"}),e.jsx("div",{className:"space-y-1",children:gs.map(Q=>{const ce=!!Q.id&&Jt.has(Q.id);return e.jsxs("button",{type:"button",onClick:()=>Q.id&&O(a,Q.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",ce?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Q.label||Q.name}),ce?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Q.id)})})]})]})]})]})}),vs&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:q.comparisonType||"none",disabled:H,onValueChange:Q=>f(a,Q),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const Q=!At||!Nt,ce=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(Ae,Le)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ae,disabled:Q,title:ce,children:Le})}),Q&&ce&&e.jsx(t.TooltipContent,{side:"right",children:ce})]})});return e.jsxs(e.Fragment,{children:[oe("previous_period","Previous Period"),oe("same_period_last_year","Same Period Last Year"),oe("start_vs_end","Start vs End")]})})(),Qt&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]})]}),vs&&q.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(t.Input,{type:"number",value:q.targetValue!==void 0&&q.targetValue!==null?String(q.targetValue):"",onChange:Q=>{const ce=Q.target.value;if(ce===""){me(a,void 0);return}const oe=Number(ce);me(a,Number.isFinite(oe)?oe:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(Q=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{te(Q),X(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Q.field.label,":"]}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(Q.value)?Q.value.length===1?String(Q.value[0]):Q.value.length<=2?Q.value.join(", "):`${Q.value.slice(0,2).join(", ")} +${Q.value.length-2}`:String(Q.value)})}),Array.isArray(Q.value)&&Q.value.length>1&&e.jsx(t.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",Q.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Q.value.map((ce,oe)=>e.jsx("div",{children:String(ce)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:ce=>{var Ae;ce.stopPropagation();const oe=Se.conditions.filter(Le=>Le.id!==Q.id);if(oe.length>0){const Le={...Se,conditions:oe};It(Le)}else if(Be(void 0),n==="metrics"){const Le={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((Ae=m.config)==null?void 0:Ae.metricColumns)||[]];_e[a]=Le,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Q.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{te(null),X(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(go,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(uo,{aliasTemplate:W,onAliasTemplateChange:We}),e.jsx(mo,{valueAliases:Ce,onValueAliasesChange:ae})]})]})},on=(Se==null?void 0:Se.conditions)&&Se.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:Kt,className:t.cn("group mx-auto flex w-full flex-col gap-2 rounded-md border border-border/55 bg-background p-2 transition-colors duration-150","hover:border-border/80 hover:bg-muted/20",ve&&"border-border/80 bg-muted/20 shadow-[inset_0_1px_0_rgba(255,255,255,0.35)]",h&&"z-50 scale-95 opacity-50","cursor-default"),children:[e.jsxs("div",{className:"flex min-w-0 grow items-center gap-2",children:[e.jsx("button",{type:"button",...c,...l,className:"flex shrink-0 cursor-grab items-center rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${t.getMetricDisplayLabel(s)}`,onClick:G=>{G.stopPropagation()},children:e.jsx(t.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(t.IconForFieldType,{dataType:Dt}),be&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,be.badgeClassName),children:be.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",on&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),n==="metrics"&&((ea=Se==null?void 0:Se.conditions)==null?void 0:ea.length)&&!ve&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.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 text-primary/90",children:[e.jsx(t.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})}),n==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),d(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),se(!ve)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${ve?"rotate-180":""}`})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 p-0 text-foreground/55 hover:text-foreground",onClick:G=>{G.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),ve&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[tn(),an(),sn(),o==="kpi"&&ys(),nn(),rn(),ln()]})]}),pe&&e.jsx(Ka,{open:pe,onOpenChange:G=>{X(G),G||te(null)},availableFields:B,existingFilters:Se,editingCondition:Fe,onSave:G=>{var Q;if(G)It(G);else if(Be(void 0),n==="metrics"){const ce={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Q=m.config)==null?void 0:Q.metricColumns)||[]];oe[a]=ce,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}te(null)}}),Z&&n==="metrics"&&Te&&e.jsx(t.CalculatedFieldEditor,{open:Z,onOpenChange:ue,availableFields:E,existingField:et,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{var Ft;if(G.role!=="metric")return;const{card:Q,frame:ce,actions:oe}=t.useEditorStore.getState(),Ae=((Ft=Q.config)==null?void 0:Ft.metricColumns)||[],Le=ce.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:Ae,storedFields:Q.calculatedFields||[],sharedFields:Le,updatedField:G,editingField:et,previousScope:ct});_e&&oe.updateCardConfig(m.id,{metricColumns:_e}),oe.updateCard(m.id,{calculatedFields:Ct}),Lt!==Le&&t.commitSharedCalculatedFields({nextSharedFields:Lt,currentSharedFields:Le,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:S})},onSaveToDashboard:G=>{var ta;if(G.role!=="metric")return;const{card:Q,frame:ce,actions:oe}=t.useEditorStore.getState(),Ae=s,Le=((ta=Q.config)==null?void 0:ta.metricColumns)||[],_e=ce.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Le,storedFields:Q.calculatedFields||[],sharedFields:_e,updatedField:{...G,id:Ae.id,aliasTemplate:Ae.aliasTemplate,valueAliases:Ae.valueAliases,parameters:Ae.parameters,customFormat:Ae.customFormat},editingField:et,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:S}),Ct&&oe.updateCardConfig(m.id,{metricColumns:Ct}),oe.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function yo({concept:s}){const n=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-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"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}const No={groupBy:zt,pivotBy:cs,metrics:In,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:n,label:a,placeholder:r,shouldShow:d,hasPivotColumns:i=!1,activeField:o=null}){const{isOver:c,setNodeRef:l}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(S=>S.card),x=t.useEditorStore(S=>S.card.type),h=n.length>0,m=N.useMemo(()=>!o||!c?!0:t.validateFieldForChartType(o,s,x).isValid,[o,c,s,x]),g=(S,E)=>{var C;!((C=p.config)!=null&&C.sortByColumns)||p.config.sortByColumns.findIndex(A=>A.id===S)===-1||u(p.id,S,{direction:E})};if(s==="sortBy"&&d===!1)return null;const v=s!=="sortBy"&&x!=="kpi",b=No[s]||t.Plus;return e.jsxs("div",{className:"mb-3 w-full",children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-2",children:e.jsx(t.Label,{className:t.cn("block text-sm font-medium text-foreground",{}),children:a})}),e.jsx("div",{ref:l,className:t.cn("rounded-lg border p-0.5 transition-colors duration-150",{"border-green-500 bg-green-50 shadow-[0_0_0_1px_rgba(34,197,94,0.18)] dark:bg-green-950":c&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":c&&!m,"border-solid border-border/55 bg-background":!c&&h,"min-h-[56px] border-dashed border-border/60 bg-background":!c&&!h}),children:n.length===0?e.jsxs("div",{className:"flex min-h-[56px] items-center justify-center gap-2 text-sm text-muted-foreground/85",children:[e.jsx(b,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80"}),e.jsx("span",{children:r}),v&&e.jsx(yo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:n.map(S=>S.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map((S,E)=>{const C=S.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(vo,{field:S,zone:s,index:E,sortDirection:C,onSortDirectionChange:A=>g(S.id,A),hasPivotColumns:i,cardType:x})})},S.id)})})})})]})}function Co({groupByFields:s,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:d,activeField:i}){var z,U,Y;const[o,c]=N.useState(!1),l=t.useEditorStore($=>{var ee;return!!((ee=$.card.customCardPreferences)!=null&&ee.url)}),u=t.useEditorStore($=>$.card),p=t.useEditorStore($=>$.frame),x=t.findCustomVisualConfigCard(p,u),{manifest:h}=t.useCustomVisual(((z=x==null?void 0:x.customCardPreferences)==null?void 0:z.url)||""),m=(U=h==null?void 0:h.visuals)==null?void 0:U.find($=>{var ee;return $.name===((ee=x==null?void 0:x.customCardPreferences)==null?void 0:ee.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((Y=x==null?void 0:x.customCardPreferences)!=null&&Y.url),b=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore($=>$.actions.updateCardConfig);const S=t.useEditorStore($=>$.actions.updateCard),E=t.useEditorStore($=>$.actions.updateFrame),B=t.useDashboardStore($=>$.isVisualEditing),C=t.useDashboardStore($=>$.selectedSheetId),A=t.useDashboardStore($=>$.actions.updateSheetCalculatedFields),{scopedFields:T}=t.useScopedFields(),{userContext:D}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===u.id&&b?b:u==null?void 0:u.type,M=I==="detailTable",j=s.length>0||a.length>0||d.length>0,R=!M&&(I!=="kpi"||a.length<=2),y=!M,L=!M&&I!=="kpi",F=I!=="kpi"&&j,f=M,k="Drop sort fields here",w=(D==null?void 0:D.type)==="organization",V=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),O=L&&!V,P=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},_=()=>I==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs(t.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full space-y-2.5",children:[e.jsxs(t.AccordionItem,{value:"fields",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.List,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(t.AccordionContent,{className:"space-y-3 pt-1.5",children:[R&&e.jsx(wt,{zone:"groupBy",fields:s,label:P().label,placeholder:P().placeholder,activeField:i}),O&&e.jsx(wt,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),y&&e.jsx(wt,{zone:"metrics",fields:a,label:_().label,placeholder:_().placeholder,hasPivotColumns:n.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),a.length>=1&&w&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),F&&e.jsx(wt,{zone:"sortBy",fields:r,label:"Sort By",placeholder:k,activeField:i})]})]}),(!l||v)&&e.jsxs(t.AccordionItem,{value:"configuration",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Settings2,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx($a,{mode:"config"})})})]}),(l||v)&&e.jsxs(t.AccordionItem,{value:"plugin",className:"rounded-xl border border-border/55 border-b-0 bg-card px-3 shadow-[0_1px_2px_rgba(15,23,42,0.04)]",children:[e.jsx(t.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2.5 text-xs font-semibold tracking-wide text-foreground/70 outline-none ring-0 hover:no-underline focus:outline-none focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-foreground/60"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(t.AccordionContent,{className:"mb-2 rounded-md bg-muted/20 px-3 py-0.5",children:e.jsx(Va,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:o,onOpenChange:c,availableFields:T,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:$=>{if($.role!=="metric")return;const{nextStoredFields:ee}=t.saveCalculatedFieldToCardScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:$,previousScope:"card"});S(u.id,{calculatedFields:ee})},onSaveToDashboard:$=>{if($.role!=="metric")return;const ee=p.calculatedFields||[],{nextSharedFields:ne}=t.saveCalculatedFieldToSharedScope({activeFields:a,storedFields:u.calculatedFields||[],sharedFields:ee,updatedField:$,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:ne,currentSharedFields:ee,isVisualEditing:B,selectedSheetId:C,updateFrame:E,updateSheetCalculatedFields:A})},cardId:u.id})]})}function So({onEditJoins:s}){const n=t.useEditorStore(c=>c.card),{autoJoinMetadata:a}=t.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,d=(r==null?void 0:r.joins)||[];if(d.length===0)return null;const i=c=>!c||c.length===0?"No conditions":c.map(l=>{var h,m,g,v;const u=`${(h=l.source)==null?void 0:h.entityName}.${(m=l.source)==null?void 0:m.name}`,p=`${(g=l.target)==null?void 0:g.entityName}.${(v=l.target)==null?void 0:v.name}`,x=l.operator||"=";return`${u} ${x} ${p}`}).join(" AND "),o=c=>!c.joinKeyGroups||c.joinKeyGroups.length===0?"No conditions defined":c.joinKeyGroups.length===1?i(c.joinKeyGroups[0].keys):c.joinKeyGroups.map((l,u)=>({id:u,operator:l.operator,condition:i(l.keys)}));return e.jsx(t.Card,{className:"border-blue-500/20 bg-blue-50/15 shadow-sm dark:bg-blue-950/10",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(Ln,{className:"size-4 text-blue-600/90 dark:text-blue-400"}),e.jsx("h3",{className:"text-xs font-semibold tracking-wide text-blue-900/90 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Badge,{variant:"secondary",className:"cursor-help bg-blue-100/80 text-xs text-blue-700 dark:bg-blue-900/70 dark:text-blue-300",children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:d.map((c,l)=>{const u=o(c),p=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(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:c.target.name})]}),e.jsx(t.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:p?u.map(x=>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:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.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)})})})]})})]}),s&&e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:s,className:"h-7 gap-1 p-2 text-xs text-blue-700/80 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(t.SquarePen,{className:"size-3.5"})})]})})}const Sa={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(n){return console.warn(`Failed to read from localStorage (${s}):`,n),null}},setItem(s,n){if(!(typeof window>"u"))try{localStorage.setItem(s,n)}catch(a){console.warn(`Failed to write to localStorage (${s}):`,a)}}};function wo({selectedChart:s,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:o,activeField:c}){var M,j;const[l,u]=N.useState(()=>Sa.getItem("chart-selector-expanded")==="true"),[p,x]=N.useState(!1),h=t.useEditorStore(R=>R.card),m=t.useEditorStore(R=>R.actions.updateCardConfig),g=a.length>0||r.length>0||d.length>0||o.length>0,{data:v,autoJoinMetadata:b}=t.useDashboardCardQuery(h),S=g||!!v,E=((M=h==null?void 0:h.config)==null?void 0:M.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),B=((j=h==null?void 0:h.dataSource)==null?void 0:j.selectedEntities)||[],C=R=>{m(h.id,{...h==null?void 0:h.config,joinPlan:R}),x(!1)},A=()=>{m(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},T=()=>{x(!1)},D=()=>{x(!0)};N.useEffect(()=>{Sa.setItem("chart-selector-expanded",String(l))},[l]);const I=()=>{u(R=>!R)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col bg-background",children:[e.jsx("div",{className:"pl-2 pr-4 pt-4",children:e.jsxs("div",{className:"rounded-xl border border-border/60 bg-card p-3 shadow-[0_1px_2px_rgba(15,23,42,0.05)]",children:[e.jsx("div",{className:t.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:l&&e.jsx(us,{selectedChart:s,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":l,"mt-2":!l}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:n,isDropdownExpanded:l,onToggleDropdown:I})})]})}),S&&e.jsx("div",{className:"pl-2 pr-4 py-3",children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(De.EditorClearButton,{label:"Reset",variant:"secondary",className:"h-7 px-2 text-xs"})})}),e.jsx(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0",children:e.jsxs("div",{className:t.cn("space-y-3 pl-2 pr-4 pb-6",S?"pt-1":"pt-4"),children:[e.jsx(So,{onEditJoins:D}),e.jsx(Co,{groupByFields:a,pivotByFields:r,metricsFields:d,sortByFields:i,detailFields:o,activeField:c})]})}),e.jsx(ka,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:B,onSave:C,onCancel:T,onRemove:A,children:e.jsx("div",{})})]})}function To({initialFilters:s,availableFields:n}={}){const[a,r]=N.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(C=>C.card.dataSource);const{filterableFields:d,isLoading:i}=t.useFilterableFields(),o=n||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},l=C=>{const A=T=>{if(T.id===C){const D=o[0]||c,I=t.getDataType(D.dataType)==="date";return{...T,conditions:[...T.conditions,{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}]}}return{...T,groups:T.groups.map(A)}};r(A(a))},u=C=>{const A=T=>{if(T.id===C){const D=o[0]||c,I=t.getDataType(D.dataType)==="date";return{...T,groups:[...T.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}],groups:[]}]}}return{...T,groups:T.groups.map(A)}};r(A(a))},p=(C,A)=>{const T=D=>D.id===C?{...D,conditions:D.conditions.filter(I=>I.id!==A)}:{...D,groups:D.groups.map(T)};r(T(a))},x=(C,A)=>{const T=D=>D.id===C?{...D,groups:D.groups.filter(I=>I.id!==A)}:{...D,groups:D.groups.map(T)};r(T(a))},h=(C,A,T,D)=>{if(T==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=M=>M.id===C?{...M,conditions:M.conditions.map(j=>j.id===A?{...j,[T]:D}:j)}:{...M,groups:M.groups.map(I)};r(I(a))},m=(C,A,T)=>{const D=I=>I.id===C?{...I,conditions:I.conditions.map(M=>M.id===A?{...M,...T}:M)}:{...I,groups:I.groups.map(D)};r(D(a))},g=(C,A)=>{const T=D=>D.id===C?{...D,logicalOperator:A}:{...D,groups:D.groups.map(T)};r(T(a))},v=(C,A)=>{const T=D=>D.id===C?{...D,negate:A}:{...D,groups:D.groups.map(T)};r(T(a))},b=(C,A,T)=>{const D=I=>I.id===C?{...I,conditions:t.arrayMove(I.conditions,A,T)}:{...I,groups:I.groups.map(D)};r(D(a))},S=(C,A,T)=>{const D=I=>I.id===C?{...I,groups:t.arrayMove(I.groups,A,T)}:{...I,groups:I.groups.map(D)};r(D(a))},E=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const A=D=>{let I="";typeof D.field=="object"?I=D.field.entityName?`${D.field.entityName}.${D.field.name}`:D.field.name:I=String(D.field);const M=D.operator;let j=D.value;if(D.field.dataType==="string"&&!["in","not in"].includes(D.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(D.field.dataType==="date"||D.field.dataType==="datetime"||D.field.dataType==="timestamp")if(D.operator==="between"&&Array.isArray(j)&&j.length===2){const R=j[0]?`'${j[0]}'`:"NULL",y=j[1]?`'${j[1]}'`:"NULL";return`${I} BETWEEN ${R} AND ${y}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(j)){const R=j.map(y=>y?`'${y}'`:"NULL").join(", ");return`${I} ${M} (${R})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(D.operator)){let R=[];Array.isArray(j)?R=j.map(y=>typeof y=="string"?`'${y}'`:String(y)):typeof j=="string"?R=j.split(",").map(y=>{const L=y.trim();return D.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(R=[String(j)]),j=`(${R.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${I} LIKE '${j.replace(/'/g,"")}%'`:`${I} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${I} LIKE '%${j.replace(/'/g,"")}'`:`${I} LIKE '%${String(j)}'`;case"isNull":return`${I} IS NULL`;case"isNotNull":return`${I} IS NOT NULL`;default:return`${I} ${M} ${j}`}},T=D=>{const I=D.conditions.map(A),M=D.groups.map(L=>T(L)),j=[...I,...M].filter(Boolean);if(j.length===0)return"";const R=j.join(` ${D.logicalOperator} `),y=j.length>1?`(${R})`:R;return D.negate?`NOT ${y}`:y};return T(C)},B=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:l,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:E,hasAnyFilters:B}}function Eo({children:s,className:n,delayDuration:a}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:a,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Io=s=>{if(s.qualifiedEntityName){const n=s.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Do({value:s,onValueChange:n,availableFields:a,placeholder:r="Select field",className:d="w-64"}){const[i,o]=N.useState(!1),c=N.useMemo(()=>{const l={};return a.forEach(u=>{const p=Io(u);l[p]||(l[p]={}),l[p][u.entityId]||(l[p][u.entityId]=[]),l[p][u.entityId].push(u)}),l},[a]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Eo,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(c).map(([l,u])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(u).map(([p,x])=>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:[t.getEntityIcon(x[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:x[0].entityName})]}),x.map((h,m)=>e.jsxs(t.CommandItem,{value:h.id,onSelect:()=>{n(h),o(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===h.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:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+m))]},`${l}-${p}`))},l))})]})})]})}function fs(s){var v;const n=t.useEditorStore(b=>b.card),{authToken:a,tokenProps:r}=t.useSemaphorContext(),d=t.useEditorStore(b=>b.card.config),i=d==null?void 0:d.joinPlan,o={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[o],metricColumns:[c],sortByColumns:[l]},p=((v=n.dataSource)==null?void 0:v.connectionId)||n.connectionId,{data:x,isPending:h,error:m}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:u,cardDataSource:n.dataSource})}catch(b){console.log(s),console.error("error",b)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:h,error:m}}function ko({field:s,selected:n,onChange:a,placeholder:r="Select items...",className:d}){const[i,o]=Pt.useState(!1),{filterValues:c}=fs(s),l=p=>{a(n.filter(x=>x!==p))},u=p=>{n.includes(p)?a(n.filter(x=>x!==p)):a([...n,p])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:i,onOpenChange:o,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(p=>{const x=c.find(h=>h.value===p);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.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:h=>{h.key==="Enter"&&l(p)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),l(p)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:c.map((p,x)=>e.jsxs(t.CommandItem,{onSelect:()=>u(p.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+x))})]})]})})]})})}function Ao({field:s,value:n,onChange:a,placeholder:r="Select value...",className:d}){const{filterValues:i,isPending:o,error:c}=fs(s);return o?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.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(t.Select,{value:n,onValueChange:a,children:[e.jsx(t.SelectTrigger,{className:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:n})}),e.jsx(t.SelectContent,{children:i.map((l,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+u))})]})}function Mo({value:s,operator:n,onChange:a,className:r}){var m,g,v;const{tokenProps:d}=t.useSemaphorContext(),i=((g=(m=d==null?void 0:d.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=d==null?void 0:d.params)==null?void 0:v.timezone),o=i||Intl.DateTimeFormat().resolvedOptions().timeZone,c=n==="between"||n==="not between",l=N.useMemo(()=>{if(!(!s||!c)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,S=s[1]?new Date(s[1]):void 0;if(b&&S)return{from:b,to:S}}},[s,c]),u=N.useMemo(()=>{if(!s||c)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const S=new Date(b);if(!isNaN(S.getTime()))return S},[s,c]),p=b=>n==="<="||n===">"?t.endOfDayInTimezone(b,o):t.startOfDayInTimezone(b,o),x=b=>{if(!b){a([]);return}if(b.from&&b.to){a([b.from.toISOString(),b.to.toISOString()]);return}a([])},h=b=>{if(!b){a("");return}const S=p(b);a(S.toISOString())};return e.jsx(t.DateRangePicker,{value:c?l:void 0,selectionMode:c?"range":"single",singleValue:c?void 0:u,onChange:x,onSingleChange:h,timezone:i,showRelativeTab:c,className:r,placeholder:"Select date..."})}const Lo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Fo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ro=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Oo=["=","!=","isNull","isNotNull"],Po=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Bo={"=":"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 wa(s){return Bo[s]||t.titleCase(s)}function Vo(s){switch(s){case"string":return Fo;case"number":return Ro;case"boolean":return Oo;case"date":return Po;default:return Lo}}function Ga({condition:s,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:d,onRemoveCondition:i,onUpdateGroupOperator:o,availableFields:c,updateConditionFields:l}){const{attributes:u,listeners:p,setNodeRef:x,transform:h,transition:m,isDragging:g}=t.useSortable({id:s.id}),{isPending:v,error:b}=fs(s.field),S={transform:t.CSS.Transform.toString(h),transition:m};return e.jsxs("div",{ref:x,style:S,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${g?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(t.Select,{value:r,onValueChange:E=>o(a,E),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Do,{value:s.field,onValueChange:E=>{const B=E,C=t.getDataType(B.dataType)==="date";l(a,s.id,{field:B,value:"",operator:C?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?l(a,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?l(a,s.id,{operator:E,value:null}):E==="between"||E==="not between"?l(a,s.id,{operator:E,value:[]}):l(a,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?wa(s.operator):""})}),e.jsx(t.SelectContent,{children:Vo(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:wa(E)},E))})]}),s.operator==="isNull"||s.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?v?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(ko,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>l(a,s.id,{value:E}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Ao,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>l(a,s.id,{value:E}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:E=>l(a,s.id,{value:E==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):t.getDataType(s.field.dataType)==="date"?e.jsx(Mo,{value:s.value,operator:s.operator,onChange:E=>l(a,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>d(a,s.id,"value",E.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(a,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function zo({group:s,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:d,onRemoveGroup:i,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onReorderConditions:u,onReorderGroups:p,onAddCondition:x,onAddGroup:h,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:S,setNodeRef:E,transform:B,transition:C,isDragging:A}=t.useSortable({id:s.id}),T={transform:t.CSS.Transform.toString(B),transition:C},D=M=>{const{active:j,over:R}=M;if(R&&j.id!==R.id){const y=s.conditions.findIndex(F=>F.id===j.id),L=s.conditions.findIndex(F=>F.id===R.id);y!==-1&&L!==-1&&u(s.id,y,L)}},I=M=>{const{active:j,over:R}=M;if(R&&j.id!==R.id&&a){const y=s.groups.findIndex(F=>F.id===j.id),L=s.groups.findIndex(F=>F.id===R.id);y!==-1&&L!==-1&&p(a,y,L)}};return e.jsxs("div",{ref:E,style:T,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${A?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...S,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:M=>r(s.id,M),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&i(a,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:D,children:e.jsx(t.SortableContext,{items:s.conditions.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((M,j)=>e.jsx(Ga,{condition:M,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:o,onUpdateField:c,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},M.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:I,children:e.jsx(t.SortableContext,{items:s.groups.map(M=>M.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(M=>g(M,n+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>x(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function _o({filters:s,availableFields:n,onSave:a,onClearAll:r,onCancel:d}){const{currentFilters:i,availableFields:o,isLoading:c,addCondition:l,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:S,generateSQLPreview:E,hasAnyFilters:B,setCurrentFilters:C}=To({initialFilters:s,availableFields:n}),A=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[T,D]=N.useState(!1),I=(R,y,L)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(k=>k.id===y?{...k,field:L,dataType:L.dataType}:k)}:{...f,groups:f.groups.map(F)};C(F(i))},M=(R,y=0,L)=>y===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const w=R.conditions.findIndex(O=>O.id===f.id),V=R.conditions.findIndex(O=>O.id===k.id);w!==-1&&V!==-1&&b(R.id,w,V)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Ga,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:o,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const w=R.groups.findIndex(O=>O.id===f.id),V=R.groups.findIndex(O=>O.id===k.id);w!==-1&&V!==-1&&S(R.id,w,V)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>M(F,y+1,R.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),T&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},R.id):e.jsx(zo,{group:R,depth:y,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:S,onAddCondition:l,onAddGroup:u,availableFields:o,renderFilterGroup:M,updateConditionFields:m},R.id),j=t.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[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..."})]}):M(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:T,onCheckedChange:R=>D(R)}),e.jsx(t.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:E(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>a(B?i:null),children:"Apply Filters"})]})]})}function qo({cardId:s,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:d,isOpen:i,onOpenChange:o}){const c=u=>{a(s,u),o(!1)},l=()=>{r(s),o(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:o,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:u=>{u.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(_o,{filters:n,availableFields:d,onSave:c,onCancel:()=>o(!1),onClearAll:l})]})]})}function $o({activeCardId:s,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var E,B;const[d,i]=N.useState(null),o=t.useEditorStore(C=>C.card),c=t.useEditorStore(C=>C.actions.updateCardConfig),l=t.useEditorStore(C=>C.actions.setCardPreferences),u=(E=o==null?void 0:o.config)==null?void 0:E.joinPlan,p=N.useCallback(C=>C.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||C.entityName==="calculated_fields"||C.qualifiedEntityName==="calculated_fields",[]),x=(B=o==null?void 0:o.dataSource)==null?void 0:B.semanticDomainId,{data:h}=t.useJoinabilityMap(x),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],g=N.useCallback(C=>C.startsWith("card-source-")?"source":C.startsWith("card-")?null:C.startsWith("source-")||n.find(A=>A.id===C)?"source":a("groupBy").find(A=>A.id===C)?"groupBy":a("metrics").find(A=>A.id===C)?"metrics":a("pivotBy").find(A=>A.id===C)?"pivotBy":a("sortBy").find(A=>A.id===C)?"sortBy":a("detailColumns").find(A=>A.id===C)?"detailColumns":null,[n,a]),v=N.useCallback(C=>{i(C.active.id)},[]),b=N.useCallback(C=>{var R;const{active:A,over:T}=C;if(!T||!s){i(null);return}const D=A.id,I=T.id,M=g(D),j=g(I)||I;if(j==="sortBy"){if(M==="source"){const y=n.find(F=>F.id===D);if(!y){i(null);return}if(!(a("groupBy").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName)||a("metrics").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName)||a("detailColumns").some(F=>F.name===y.name&&F.qualifiedEntityName===y.qualifiedEntityName))){i(null);return}}else if(M==="pivotBy"){i(null);return}else if(M!=="groupBy"&&M!=="metrics"&&M!=="sortBy"&&M!=="detailColumns"){i(null);return}}if(M==="source"&&j==="sortBy"){const y=[...n].find(k=>k.id===D);if(!y){i(null);return}const L=a("sortBy");if(t.fieldAlreadyExists(y,L)){i(null);return}const F=t.validateFieldForChartType(y,"sortBy",o.type);if(!F.isValid){t.ue.error("Invalid Field Type",{description:F.reason,position:"top-center",duration:3e3}),i(null);return}const f=t.getNewField(y,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(M==="source"&&j!=="source"&&j!=="sortBy"){const y=[...n].find(O=>O.id===D);if(!y){i(null);return}const L=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],F=L.filter(O=>!p(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){i(null);return}if(O!==y.qualifiedEntityName&&!p(y)&&y.qualifiedEntityName)if(x&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(y,{joinabilityMap:h.joinabilityMap,selectedFields:L,baseEntityName:(R=u==null?void 0:u.baseEntity)==null?void 0:R.name}).state==="unreachable"){t.showJoinRequiredNotification(),i(null);return}}else{if(!u){t.showJoinRequiredNotification(),i(null);return}if(!t.areEntitiesJoined(O,y.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=a(j);if(t.fieldAlreadyExists(y,f)){i(null);return}const k=t.validateFieldForChartType(y,j,o.type);if(!k.isValid){t.ue.error("Invalid Field Type",{description:k.reason,position:"top-center",duration:3e3}),i(null);return}const w=t.getNewField(y,j,f),V=[...f,w];if(i(null),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(o,w,o.preferences);O&&l(O),t.cleanupKpiMetricComparisonMode(o.type,o.config,c,s,V)}return}if(M&&j&&M!=="source"&&j!=="source"&&M!==j){const y=a(M),L=a(j),F=y.find(O=>O.id===D);if(!F){i(null);return}const f=t.validateFieldForChartType(F,j,o.type);if(!f.isValid){t.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),i(null);return}const k=t.getNewField(F,j,L);if(i(null),j==="sortBy"){t.fieldAlreadyExists(F,L)||r(j,[...L,k]);return}const w=y.filter(O=>O.id!==D),V=[...L,k];if(r(M,w),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(o,k,o.preferences);O&&l(O),t.cleanupKpiMetricComparisonMode(o.type,o.config,c,s,V)}return}if(M&&j&&M===j&&M!=="source"){const y=a(M),L=y.findIndex(f=>f.id===D),F=y.findIndex(f=>f.id===I);if(L!==F){const f=t.arrayMove(y,L,F);r(M,f)}}i(null)},[s,n,a,r,g,u,x,h,p,o,c,l]),S=d?m.find(C=>C.id===d):null;return{activeId:d,activeField:S,handleDragStart:v,handleDragEnd:b}}function Ko({activeView:s,onViewChange:n,splitViewEnabled:a}){const r=t.useEditorStore(c=>c.card),{config:d}=N.useContext(t.SemaphorContext).tokenProps,i=(d==null?void 0:d.showInfoTab)!==!1,o=()=>a?!1:t.getVisualizationMode(r)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.Tabs,{value:s,onValueChange:c=>n(c),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),o()&&e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&i&&e.jsx(t.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})})}const Go=[{value:"10",label:"Top 10"},{value:"20",label:"Top 20"},{value:"50",label:"Top 50"},{value:"100",label:"Top 100"},{value:"200",label:"Top 200"},{value:"500",label:"Top 500"},{value:"1000",label:"Top 1000"}];function Uo(){var l,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:n}=t.useEditorActions(),[a,r]=N.useState(!1),[d,i]=N.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(s.id,parseInt(p))},c=p=>{const x=p.target.value;i(x),x&&!isNaN(parseInt(x))&&n(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:u.toString())||"100",onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Go.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Ho({card:s,queryData:n,isLoading:a,isFetching:r,pagination:d,onPaginationChange:i,onSortChange:o,sortState:c,splitViewEnabled:l,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const x=N.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),h=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Pa,{fallbackPreview:e.jsx(ot,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return h?l?e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:m}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:o,sortState:c})]})})]}):m:!l||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(ot,{}):e.jsxs(t.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(t.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ot,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:d,onPaginationChange:i,isLoading:a||r,onSortChange:o,sortState:c})]})})]})}const Qo="semaphor-split-view-enabled";function Jo(){return Aa(Qo,!0)}function Yo({activeView:s,onViewChange:n,onFiltersClick:a,activeCard:r,columns:d}){var de,pe,X;const i=t.useEditorStore(Z=>Z.card),o=t.useEditorStore(Z=>Z.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),c=t.useEditorStore(Z=>Z.actions.removeCardInlineFilterValue),l=t.useDashboardStore(Z=>Z.filterValues),u=t.useDashboardStore(Z=>Z.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:h,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(Z=>Z.showAIDialog),v=t.useEditorStore(Z=>Z.isDevMode),b=t.useDashboardStore(Z=>Z.isVisualEditing),[S,E]=N.useState(!1),[B,C]=N.useState(!1),[A,T]=N.useState(!1),[D,I]=N.useState(null),{config:M}=N.useContext(t.SemaphorContext).tokenProps,j=(M==null?void 0:M.showInfoTab)!==!1,R=(M==null?void 0:M.showQueryDebugTools)!==!1,[y,L]=Jo();t.useEditorStore(Z=>{var ue;return!!((ue=Z.card.customCardPreferences)!=null&&ue.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:k,errorMessage:w,isLoading:V,isFetching:O,errorSql:P,pagination:_,refetch:z,comparisonMetadata:U,queryRequestPayload:Y}=t.useDashboardCardQuery(r),$=N.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[ee,ne]=N.useState(!1);N.useEffect(()=>{O||ne(!1)},[O]);const me=()=>{const Z=!y;Z&&s==="table"&&n("chart"),L(Z)},ve=(Z,ue)=>{const Fe={...r,paginationConfig:{page:Z+1,pageSize:ue}};x(Fe),h(Fe)},se=Z=>{if(!i.config)return;const ue=t.sortStateToSortByColumns(Z,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);p(i.id,{...i.config,sortByColumns:ue})},re=N.useMemo(()=>{var Z;return t.sortByColumnsToSortState((Z=i.config)==null?void 0:Z.sortByColumns)},[(de=i.config)==null?void 0:de.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":g&&b}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 pl-2 pr-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&g&&!f&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:v?"secondary":"ghost"})}),e.jsx(Ko,{activeView:s,onViewChange:n,splitViewEnabled:y}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(pe=r.config)==null?void 0:pe.filters,cardFilterCount:t.getFilterCount(((X=r.config)==null?void 0:X.filters)||null),onFiltersClick:a,inlineFilters:r.inlineFilters,inlineFilterValues:o,sheetId:u||"",removeInlineFilterValue:Z=>c(r.id,Z)}),U&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Uo,{})}),g&&e.jsx(De.EditorClearButton,{})]}),e.jsxs("div",{className:t.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(t.IconButton,{tooltip:"Refresh",disabled:V||O,onClick:()=>{ne(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":ee})})}),s==="chart"&&!f&&e.jsx(Oa,{showInlineFilters:!1,showDisplayOptions:!1}),!g&&e.jsx(t.IconButton,{onClick:()=>m(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(xn,{className:"size-4"})}),s==="chart"&&e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-8","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"size-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(t.DropdownMenuLabel,{children:"More Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:me,children:[y?e.jsx(gn,{className:"mr-2 h-4 w-4"}):e.jsx(An,{className:"mr-2 h-4 w-4"}),y?"Hide Results Table":"Show Results Table"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Ba,{onCustomize:()=>T(!0)})]})]})]})]}),e.jsxs("div",{className:"mt-2 flex min-h-0 grow flex-col",children:[s==="chart"&&e.jsx("div",{className:t.cn("flex grow flex-col pb-4",{"pb-0":y&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Ho,{card:r,queryData:k,isLoading:V,isFetching:O,pagination:_,onPaginationChange:ve,onSortChange:se,sortState:re,splitViewEnabled:y,isDynamicInspectorOpen:A,onDynamicInspectorOpenChange:T})}),s==="table"&&(k==null?void 0:k.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 py-4 pl-2 pr-4",children:[(V||O)&&(k==null?void 0:k.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(t.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(t.TableVisual,{card:r,data:$,comparisonMetadata:U,paginationMetadata:_,onPaginationChange:ve,isLoading:V||O,onSortChange:se,sortState:re})]}),s==="info"&&j&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-4",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background pl-2 pr-4",children:w?e.jsx(ds,{error:w,errorSql:P,onSendFeedback:()=>{const Z=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:l,errorMessage:w,errorSql:P,generatedSql:k==null?void 0:k.sql});I(Z),C(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const Z=t.useEditorStore.getState().actions;Z.setIsDevMode(!0),Z.setCardSql(P||""),setTimeout(()=>{Z.setRunSql(!0)},100)},100)}}):(k==null?void 0:k.sql)&&e.jsx(La,{sql:k.sql,showCardDetails:!0,debugPayloads:R?{queryRequest:Y,queryResponse:k,columns:d,dashboardFilters:l}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:B,onOpenChange:C,feedbackData:D})]})})}function Wo({activeField:s}){const[n,a]=N.useState(!0);return N.useEffect(()=>{s&&a(!0)},[s]),s?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(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(t.IconForFieldType,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Xo=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const 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 d;if((d=r.reason)!=null&&d.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=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Zo({column:s,isSelected:n,onSelect:a,availableFields:r,width:d,onWidthChange:i}){var O,P,_;const o=t.useEditorStore(z=>z.card),{updateCardConfig:c,removeGroupByColumn:l,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[x,h]=N.useState(!1),[m,g]=N.useState(!1),v=N.useRef(null),b=N.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:d||150};const U=$=>{if(!v.current)return;const ee=$.clientX-v.current.startX,ne=Math.max(80,v.current.startWidth+ee);i==null||i(s.id,ne)},Y=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",Y)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",Y)},[d,s.id,i]),S=(O=o==null?void 0:o.config)==null?void 0:O.filters,E=(P=S==null?void 0:S.conditions)==null?void 0:P.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),B=z=>{z?p(o.id,z):c(o.id,{filters:void 0})},{attributes:C,listeners:A,setNodeRef:T,transform:D,transition:I,isDragging:M}=t.useSortable({id:s.id}),j={transform:t.CSS.Transform.toString(D),transition:I},R=t.getDataType(s.dataType),y=ei(R),L=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],U=z.findIndex($=>$.name===s.name);if(U!==-1){const $=[...z];$[U]={...$[U],direction:"asc"},c(o.id,{sortByColumns:$})}else c(o.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.sortByColumns)||[],U=z.findIndex($=>$.name===s.name);if(U!==-1){const $=[...z];$[U]={...$[U],direction:"desc"},c(o.id,{sortByColumns:$})}else c(o.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var Y;const z=((Y=o==null?void 0:o.config)==null?void 0:Y.groupByColumns)||[];if(!z.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(o.id,{groupByColumns:[...z,$]})}},k=z=>{var $;const U=(($=o==null?void 0:o.config)==null?void 0:$.metricColumns)||[];if(!U.some(ee=>ee.name===s.name&&ee.aggregate===z)){const ee={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};c(o.id,{metricColumns:[...U,ee]})}},w=()=>{s.role==="groupby"?l(o.id,s.id):s.role==="metric"&&u(o.id,s.id)},V={...j,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:T,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",M&&"opacity-50",n&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...C,...A,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(t.GripVertical,{className:"h-3 w-3"})}),e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:t.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(y,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:s.label||s.name}),s.role==="metric"&&s.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",s.aggregate,")"]}),E&&e.jsx(t.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(t.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(t.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(t.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(t.Filter,{className:t.cn("mr-2 h-4 w-4",E&&"text-primary")}),E?"Edit Filter":"Filter"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:L,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuSub,{children:[e.jsxs(t.DropdownMenuSubTrigger,{children:[e.jsx(t.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(t.DropdownMenuSubContent,{children:[e.jsx(t.DropdownMenuItem,{onClick:()=>k("SUM"),children:"Sum"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("AVG"),children:"Average"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("COUNT"),children:"Count"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("DISTINCT"),children:"Count Distinct"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("MIN"),children:"Min"}),e.jsx(t.DropdownMenuItem,{onClick:()=>k("MAX"),children:"Max"})]})]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onClick:f,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{disabled:!0,children:[e.jsx(t.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(t.DropdownMenuItem,{onClick:w,className:"text-destructive focus:text-destructive",children:[e.jsx(t.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",m&&"bg-primary")}),e.jsx(Ka,{open:x,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:S,editingCondition:E?(_=S==null?void 0:S.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function ei(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function ti({selectedColumn:s,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[],filterableFields:d=r}){var M,j,R,y;const i=t.useEditorStore(L=>L.card),{updateCardConfig:o}=t.useEditorActions(),[c,l]=N.useState(null),[u,p]=N.useState({}),[x,h]=N.useState(!1),m=N.useMemo(()=>{var f,k;const L=((f=i==null?void 0:i.config)==null?void 0:f.groupByColumns)||[],F=((k=i==null?void 0:i.config)==null?void 0:k.metricColumns)||[];return[...L,...F]},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),g=N.useMemo(()=>{const L=new Set(m.map(F=>`${F.qualifiedEntityName}.${F.name}`));return r.filter(F=>!L.has(`${F.qualifiedEntityName}.${F.name}`))},[r,m]),{data:v,isLoading:b}=t.useDashboardCardQuery(i),S=(v==null?void 0:v.records)||[],E=N.useCallback((L,F)=>{p(f=>({...f,[L]:F}))},[]),B=N.useCallback(L=>{var w,V;const F=t.getDataType(L.dataType),f=((w=i==null?void 0:i.config)==null?void 0:w.groupByColumns)||[],k=((V=i==null?void 0:i.config)==null?void 0:V.metricColumns)||[];if(F==="number"){const O={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(i.id,{metricColumns:[...k,O]})}else{const O={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};o(i.id,{groupByColumns:[...f,O]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(y=i==null?void 0:i.config)==null?void 0:y.metricColumns,i.id,o]),C=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),A=L=>{l(L.active.id)},T=L=>{const{active:F,over:f}=L;if(l(null),!f||F.id===f.id)return;const k=m.findIndex(V=>V.id===F.id),w=m.findIndex(V=>V.id===f.id);if(k!==-1&&w!==-1){const V=t.arrayMove(m,k,w),O=V.filter(_=>_.role==="groupby"),P=V.filter(_=>_.role==="metric");o(i.id,{groupByColumns:O,metricColumns:P})}},D=c?m.find(L=>L.id===c):null,I=L=>{let F="";for(;L>=0;)F=String.fromCharCode(L%26+65)+F,L=Math.floor(L/26)-1;return F};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(t.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"})}):m.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(t.DndContext,{sensors:C,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:T,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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map((L,F)=>e.jsx("th",{style:{width:u[L.id]?`${u[L.id]}px`:void 0,minWidth:u[L.id]?`${u[L.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:I(F)},`letter-${L.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(t.SortableContext,{items:m.map(L=>L.id),strategy:t.horizontalListSortingStrategy,children:m.map(L=>e.jsx(Zo,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>n(L),availableFields:d,width:u[L.id],onWidthChange:E},L.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:x,onOpenChange:h,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(t.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns available."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:g.map(L=>{const F=t.getDataType(L.dataType),f=F==="number"?t.Hash:F==="date"?t.Calendar:t.Type;return e.jsxs(t.CommandItem,{value:L.label||L.name,onSelect:()=>B(L),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:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.entityName})]})]},L.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:b?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):S.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:m.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):S.slice(0,100).map((L,F)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",F%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:F+1}),m.map(f=>{const k=L[f.name]??L[f.label??""];return e.jsx("td",{style:{width:u[f.id]?`${u[f.id]}px`:void 0,minWidth:u[f.id]?`${u[f.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===f.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:si(k,f)})},`${F}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},F))})]}),e.jsx(t.DragOverlay,{children:D&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:D.label||D.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(S.length,100)," of ",S.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function si(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const a=new Date(s);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function ai({entityGroups:s,isLoading:n=!1}){var B,C;const a=t.useEditorStore(A=>A.card),{updateCardConfig:r,removeGroupByColumn:d,removeMetricColumn:i}=t.useEditorActions(),[o,c]=N.useState(!0),[l,u]=N.useState(""),[p,x]=N.useState(new Set),h=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],m=((C=a==null?void 0:a.config)==null?void 0:C.metricColumns)||[],g=A=>{const T=new Set(p);T.has(A)?T.delete(A):T.add(A),x(T)},v=A=>h.some(T=>T.name===A.name&&T.qualifiedEntityName===A.qualifiedEntityName)||m.some(T=>T.name===A.name&&T.qualifiedEntityName===A.qualifiedEntityName),b=(A,T)=>{if(T)if(t.getDataType(A.dataType)==="number"){const I={...A,id:`metric-${A.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...m,I]})}else{const I={...A,id:`groupby-${A.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...h,I]})}else{const D=h.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName),I=m.findIndex(M=>M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName);D!==-1&&d(a.id,h[D].id),I!==-1&&i(a.id,m[I].id)}},S=A=>{if(!l)return A;const T=l.toLowerCase();return A.filter(D=>D.name.toLowerCase().includes(T)||D.label&&D.label.toLowerCase().includes(T))},E=A=>{switch(t.getDataType(A)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return o?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(t.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(Sn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(t.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search columns...",value:l,onChange:A=>u(A.target.value),className:"h-8 pl-8 text-sm"})]})}),(h.length>0||m.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(zt,{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:h.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(A=>{const T=E(A.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(a.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]}),m.length>0&&e.jsxs(t.Collapsible,{defaultOpen:!0,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(t.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:m.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(A=>{const T=E(A.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(t.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:A.aggregate}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,A.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},A.id)})})})]})]}),e.jsx(t.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"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(A=>{const T=S(A.columns);if(T.length===0)return null;const D=p.has(A.entityId)||l.length>0;return e.jsxs(t.Collapsible,{open:D,onOpenChange:()=>g(A.entityId),children:[e.jsxs(t.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(t.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",D&&"rotate-90")}),e.jsx(t.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:A.label||A.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:T.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:T.map(I=>{const M=E(I.dataType),j=v(I);return e.jsxs("label",{className:t.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",j&&"bg-primary/5"),children:[e.jsx(t.Checkbox,{checked:j,onCheckedChange:R=>b(I,R),className:"h-3.5 w-3.5"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.id)})})})]},A.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(wn,{className:"h-4 w-4"})})})}const ni=[{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 ri({value:s,onChange:n,onSubmit:a,onCancel:r,selectedColumn:d,availableColumns:i}){const[o,c]=N.useState(!1),[l,u]=N.useState("column"),p=N.useRef(null);N.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!o&&a(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,a,o]);const x=g=>{const v=`[${g.label||g.name}]`,b=p.current;if(b){const S=b.selectionStart||0,E=b.selectionEnd||0,B=s.slice(0,S)+v+s.slice(E);n(B),setTimeout(()=>{b.setSelectionRange(S+v.length,S+v.length),b.focus()},0)}else n(s+v);c(!1)},h=g=>{const v=p.current;if(v){const b=v.selectionStart||0,S=v.selectionEnd||0,E=s.slice(0,b)+g.syntax+s.slice(S);n(E),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else n(s+g.syntax);c(!1)},m=g=>{switch(t.getDataType(g)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.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:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:o&&l==="function",onOpenChange:g=>{c(g),g&&u("function")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(kn,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search functions..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No functions found."}),e.jsx(t.CommandGroup,{heading:"Functions",children:ni.map(g=>e.jsx(t.CommandItem,{value:g.name,onSelect:()=>h(g),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:g.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:g.syntax})]})},g.name))})]})]})})]}),e.jsxs(t.Popover,{open:o&&l==="column",onOpenChange:g=>{c(g),g&&u("column")},children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.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(t.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search columns..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No columns found."}),e.jsx(t.CommandGroup,{heading:"Available Columns",children:i.map(g=>{const v=m(g.dataType);return e.jsxs(t.CommandItem,{value:g.label||g.name,onSelect:()=>x(g),children:[e.jsx(v,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:g.label||g.name})]},g.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:p,value:s,onChange:g=>n(g.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),s&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(t.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(t.X,{className:"h-4 w-4"})}),e.jsx(t.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(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function li({className:s}){var m,g,v,b;const n=t.useEditorStore(S=>S.card),[a,r]=N.useState(null),[d,i]=N.useState(""),{columns:o=[],columnGroups:c=[],isLoading:l}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(g=n==null?void 0:n.config)!=null&&g.metricColumns,(v=n==null?void 0:n.config)!=null&&v.groupByColumns,(b=n==null?void 0:n.config)!=null&&b.pivotByColumns;const p=S=>{r(S),i(S?`[${S.label||S.name}]`:"")},x=S=>{console.log("Formula submitted:",S),i(""),r(null)},h=()=>{i(""),r(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(ri,{value:d,onChange:i,onSubmit:x,onCancel:h,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(ti,{selectedColumn:a,onColumnSelect:p,isLoading:l,sourceFields:o,filterableFields:u})}),e.jsx(ai,{entityGroups:c,isLoading:l})]})]})}function oi(){var w,V;const[s,n]=N.useState("chart"),[a,r]=N.useState(!1),[d,i]=N.useState(!0),o=t.useEditorStore(O=>O.showAIDialog),c=t.useDashboardStore(O=>O.isVisualEditing),{setCardType:l}=t.useEditorActions(),u=t.useEditorStore(O=>O.card.type);N.useEffect(()=>Xo(),[]);const p=O=>{l(O)},x=t.useEditorStore(O=>O.frame),h=t.useEditorStore(O=>O.card);t.useEditorStore(O=>O.activeTabCardId),t.useEditorStore(O=>O.actions.getAvailableFields);const{addCard:m,removeCard:g,updateCard:v,setActiveCard:b,updateFilters:S}=t.useEditorActions(),{columnFields:E=[],scopedFields:B=[],filterableFields:C=[]}=t.useFilterableFields(),A=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),T=h,{getFieldsForContainer:D,setFieldsForContainer:I}=t.useFieldManagement(T),{activeField:M,handleDragStart:j,handleDragEnd:R}=$o({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:D,setFieldsForContainer:I}),y=(O,P)=>{P&&S(O,P)},L=O=>{var P;v(O,{config:{...(P=x.cards.find(_=>_.id===O))==null?void 0:P.config,filters:void 0}})},F=C,f=O=>{if(!O)return 0;let P=O.conditions.length;return O.groups.forEach(_=>{P+=f(_)}),P},k=f(((w=T==null?void 0:T.config)==null?void 0:w.filters)||null);return e.jsxs(t.DndContext,{sensors:A,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Ma,{isVisible:d,onToggleVisibility:()=>i(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(li,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(wo,{selectedChart:u,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:M}),e.jsx(Yo,{selectedChart:u,activeView:s,onViewChange:n,onFiltersClick:()=>r(!0),filterCount:k,activeCard:T,columns:E,getFieldsForContainer:D,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:b})]})}),!d&&c&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(t.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(t.Database,{className:"h-4 w-4"})})})]}),T&&e.jsx(qo,{cardId:T.id,filters:((V=T.config)==null?void 0:V.filters)||null,onFiltersChange:y,onClearFilters:L,availableFields:F,isOpen:a,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Wo,{activeField:M||null})})]})}function ii({authToken:s,onSave:n,onClose:a}){const r=N.useRef(null),d=t.useEditorStore(T=>T.showAIDialog),i=t.useEditorStore(T=>T.isDevMode),o=t.useAssistantLayoutStore(T=>T.setFullscreen),c=t.useAssistantLayoutStore(T=>T.setPanelOpen),l=t.useAssistantLayoutStore(T=>T.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),h=p==="editor",m=N.useCallback(T=>{l("editor",T)},[l]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:S}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();N.useEffect(()=>{n&&b(n),a&&S(a)},[n,b,a,S]),N.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),N.useEffect(()=>{var T,D;d?((T=r.current)==null||T.resize(40),c("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),c("editor",!1),p==="editor"&&o(null),E(null))},[d,c,E,o,p]);function B(T){var D;T<1?(v(!1),c("editor",!1),p==="editor"&&o(null),E(null),(D=r.current)==null||D.resize(0)):(d||(v(!0),E("editor")),u.isOpen||c("editor",!0))}function C(){return e.jsxs(e.Fragment,{children:[e.jsx(Ma,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(lo,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.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(Ca,{isFullscreen:h,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function A(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(oi,{})}),e.jsx(t.ResizableHandle,{disabled:!d}),e.jsx(t.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(Ca,{isFullscreen:h,onFullscreenChange:T=>o(T?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:C()}):A()})}function ci(){t.useDashboardStore(l=>l.selectedCardId);const s=t.useDashboardStore(l=>l.selectedSheetId),n=t.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=t.useDashboardStore(l=>l.actions),d=t.useDashboardStore(l=>l.isVisualEditing),i=t.useDashboardStore(l=>l.actions.updateFrame);function o(l){var h,m,g;const u=s?(h=n==null?void 0:n.sheets)==null?void 0:h.some(v=>{var b;return v.id===s&&((b=v.frames)==null?void 0:b.some(S=>S.id===l.id))}):!1,p=(g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(v=>{var b;return(b=v.frames)==null?void 0:b.some(S=>S.id===l.id)}))==null?void 0:g.id,x=u?s:p||null;x&&(i(x,l),s!==x&&r(x),a(!1))}function c(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!d}),children:e.jsx(ii,{onSave:o,onClose:c})})}exports.default=ci;