react-semaphor 0.1.294 → 0.1.295
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.
- package/dist/chunks/{braces-DfDQiR3J.js → braces-BdoTYzuj.js} +1 -1
- package/dist/chunks/{braces-DR-GdaLC.js → braces-DWldEFn5.js} +1 -1
- package/dist/chunks/{dashboard-controls-DGEVXgP5.js → dashboard-controls-B3lrnI_r.js} +1 -1
- package/dist/chunks/{dashboard-controls-C3Z9bpYE.js → dashboard-controls-D7U6E1sB.js} +5 -5
- package/dist/chunks/{dashboard-filter-controls-button-BIYT1ucX.js → dashboard-filter-controls-button-D0AsV28-.js} +1 -1
- package/dist/chunks/{dashboard-filter-controls-button-DxgGUl00.js → dashboard-filter-controls-button-XwenlcXw.js} +3 -3
- package/dist/chunks/{dashboard-json-BvTeHePu.js → dashboard-json-CU55qPXj.js} +1 -1
- package/dist/chunks/{dashboard-json-DQW8TN0I.js → dashboard-json-V6m6lJ_c.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-q7fx3YAK.js → dashboard-summary-settings-dialog-0CIiWsKc.js} +1 -1
- package/dist/chunks/{dashboard-summary-settings-dialog-BsmKiGud.js → dashboard-summary-settings-dialog-DRLPzp1P.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-RVl9nbDZ.js → edit-dashboard-visual-8ha6EM_g.js} +407 -364
- package/dist/chunks/{edit-dashboard-visual-ChKj-Lzr.js → edit-dashboard-visual-sSLAkmgf.js} +3 -3
- package/dist/chunks/{index-DerPpfv0.js → index-14M0TnH6.js} +29597 -28801
- package/dist/chunks/{index-BlspGR07.js → index-Ze8VskG1.js} +252 -252
- package/dist/chunks/{resource-management-panel-DnZ1rw1A.js → resource-management-panel-BL5-5ouC.js} +2 -2
- package/dist/chunks/{resource-management-panel-epydPwyM.js → resource-management-panel-CcDAn86l.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-Bcg4EgoD.js → use-create-flow-overlay-state-BbQVNDCj.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-C5vdfXhM.js → use-create-flow-overlay-state-D3PxfjYv.js} +2 -2
- package/dist/chunks/{use-visual-utils-D9Kknvjl.js → use-visual-utils-CdIOq4nt.js} +1 -1
- package/dist/chunks/{use-visual-utils-Dw_yw9zU.js → use-visual-utils-kh8p2QFm.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/dashboard.d.ts +37 -0
- package/dist/types/main.d.ts +37 -0
- package/dist/types/shared.d.ts +37 -0
- package/dist/types/surfboard.d.ts +37 -0
- package/dist/types/types.d.ts +37 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("./index-Ze8VskG1.js"),y=require("react"),it=require("./use-visual-utils-kh8p2QFm.js"),De=require("./use-create-flow-overlay-state-BbQVNDCj.js"),da=require("react-dom"),ua=require("./braces-DWldEFn5.js");function ma(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const Pt=ma(y);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -179,5 +179,5 @@ ${r}`].filter(Boolean).join(`
|
|
|
179
179
|
${a||n.sql||n.python}
|
|
180
180
|
|
|
181
181
|
`;l(u)}:void 0}}function Pn({className:s,...a}){var Te,Ee,$,le,ge;const n=t.useEditorStore(ee=>ee.card);t.useEditorStore(ee=>ee.isDevMode);const r=((Te=n.customCardPreferences)==null?void 0:Te.showCardHeader)??!0,c=(($=(Ee=n.preferences)==null?void 0:Ee.displayOptions)==null?void 0:$.showInlineFilterBar)??!0,i=t.useEditorStore(ee=>ee.frame),l=t.useEditorStore(ee=>ee.inlineFilterValuesMap[n.id]),d=t.useDashboardStore(ee=>ee.dashboard.filters),o=t.useDashboardStore(ee=>ee.selectedSheetId),[u,p]=y.useState(!1),{currentUser:x}=t.useCurrentUserInfo(),{tokenProps:h}=y.useContext(t.SemaphorContext),m=t.useEditorStore(ee=>ee.actions.setRunSql),g=t.useEditorStore(ee=>ee.actions.setCardInlineFilterValue),v=t.useEditorStore(ee=>ee.actions.removeCardInlineFilterValue),{updateFilter:b}=t.useDashboardActions(),C=d==null?void 0:d.find(ee=>ee.id===i.filterId),E=y.useMemo(()=>t.findCustomVisualConfigCard(i,n),[i,n]),{manifest:B}=t.useCustomVisual(((le=E==null?void 0:E.customCardPreferences)==null?void 0:le.url)||""),S=y.useMemo(()=>{var ee;return(ee=B==null?void 0:B.visuals)==null?void 0:ee.find(Q=>{var re;return Q.name===((re=E==null?void 0:E.customCardPreferences)==null?void 0:re.componentName)})},[B,(ge=E==null?void 0:E.customCardPreferences)==null?void 0:ge.componentName]),M=t.resolveMultiInputType(E,S),w=y.useMemo(()=>t.getCustomVisualInputCards({frame:i,configCard:E,isMultiInputVisual:M==="multiple"}),[i,E,M]),D=y.useMemo(()=>{const ee=w.findIndex(Q=>(Q==null?void 0:Q.id)===(n==null?void 0:n.id));return ee<0?-1:t.getSlotIndexForCard(n,ee)},[w,n]),I=y.useMemo(()=>!E||M!=="multiple"||D<0?n.type:t.getEffectiveCardTypeForSlot(n,D,S==null?void 0:S.slots)??n.type,[E,M,D,n,S==null?void 0:S.slots]),A=I??n.type,j=y.useMemo(()=>A===n.type?n:{...n,type:A},[n,A]),R=y.useMemo(()=>I!==n.type?{...n,type:I}:n,[n,I]),{data:N,isLoading:L,isFetching:F,errorMessage:f,errorSql:k,pagination:T}=t.useEditorCardQuery(R),{handleOpenInEditor:V,handleDebugWithAssistant:O}=On(f,k||n.sql||n.python),P=y.useMemo(()=>(N==null?void 0:N.records)||[],[N==null?void 0:N.records]),{setCard:_,updateCardInFrame:z}=t.useEditorActions(),{data:H}=t.useTopoJson(j),X=j.id,K=j.config,Z=j.interactionConfig,se=j.customCfg,me=j.preferences,je=j.queryConfig,te=!!j.sql,ne=N==null?void 0:N.records,ue=y.useMemo(()=>({id:X,type:A,config:K,interactionConfig:Z,sql:te?"__editor_sql__":""}),[X,A,K,Z,te]),be=y.useMemo(()=>{var ee;return A!=="pivotTable"||!((ee=N==null?void 0:N.records)!=null&&ee.length)?null:{records:N.records,columnSubtotalMeta:N.columnSubtotalMeta,subtotalColumns:N.subtotalColumns||[],pivotSchema:N.pivotSchema||[],groupByColumns:N.groupByColumns}},[A,N==null?void 0:N.records,N==null?void 0:N.columnSubtotalMeta,N==null?void 0:N.subtotalColumns,N==null?void 0:N.pivotSchema,N==null?void 0:N.groupByColumns]),fe=t.usePivotTableConfig(j,be),ve=()=>{p(!0)},G=y.useMemo(()=>{const ee=typeof window<"u"?window.location.href:"",Q=typeof navigator<"u"?navigator.userAgent:"",re=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:t.FeedbackCategory.QUERY_GENERATION,user:x,tokenContext:h,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:d,errorMessage:f||void 0,errorSql:k||n.sql||n.python,generatedSql:k||n.sql},metadata:{url:ee,userAgent:Q,timestamp:new Date().toISOString(),viewport:re}}},[x,h,n,d,f,k]),pe=(ee,Q)=>{var ce,Se;const re={...n,paginationConfig:{page:ee+1,pageSize:Q}};_(re),z(re),n.sql&&((Se=(ce=n.preferences)==null?void 0:ce.tablePrefs)!=null&&Se.enableDevModePagination)&&m(!0)},Ce=ee=>{var ce,Se,ye,Fe,Be;const Q=t.sortStateToSortByColumns(ee,(ce=n.config)==null?void 0:ce.metricColumns,(Se=n.config)==null?void 0:Se.groupByColumns,(ye=n.config)==null?void 0:ye.detailColumns),re={...n,config:{...n.config||{},sortByColumns:Q}};_(re),z(re),n.sql&&((Be=(Fe=n.preferences)==null?void 0:Fe.tablePrefs)!=null&&Be.enableDevModePagination)&&m(!0)},Oe=y.useMemo(()=>!X||!ne?null:t.createChartConfig({card:ue,data:ne,cardType:A,queryConfig:je,customCfg:se,preferences:me,topoJson:H}),[ue,X,se,me,je,ne,A,H]);function Ve(ee){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(t.EditorCustomVisual,{card:ee})})}function Ae(){var ee;if(N!=null&&N.records&&(N==null?void 0:N.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||n.sql||n.python,onOpenInEditor:V,onDebugWithAssistant:O,onSendFeedback:ve,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)&&(!(N!=null&&N.records)||N.records.length===0))return A==="table"||A==="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(A==="custom")return Ve(n);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(A)&&Oe)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:Oe})});if(A==="table"||A==="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:(ee=N==null?void 0:N.metadata)==null?void 0:ee.comparisonMetadata,paginationMetadata:T,onPaginationChange:pe,onSortChange:Ce,isLoading:L||F})});if(A==="pivotTable"&&fe)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:fe.data,options:fe.options,onAggregationChange:Q=>{const re=t.handleAggregationChange(Q,n.config),ce={...n,config:re};_(ce),z(ce)},onAggregationLabelChange:Q=>{const re=t.handleAggregationLabelChange(Q,n.config),ce={...n,config:re};_(ce),z(ce)}})});if(A==="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:(N==null?void 0:N.records)||[],groupByColumns:N==null?void 0:N.groupByColumns,pivotSchema:N==null?void 0:N.pivotSchema,paginationMetadata:T,onPaginationChange:pe,onAggregationChange:Q=>{const re=t.handleAggregationChange(Q,n.config),ce={...n,config:re};_(ce),z(ce)},isLoading:L||F})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[(L||F)&&(N==null?void 0:N.records)&&N.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:n.title,onSave:ee=>_({...n,title:ee}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(t.InfoHover,{card:n}),e.jsx(De.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(cr,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(t.EditableText,{value:(n.description||"").trim(),onSave:ee=>_({...n,description:ee.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(t.EditableText,{value:C.title||C.column,onSave:ee=>b({...C,title:ee}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(t.FilterComponent,{filter:C})]})]}),c&&n.inlineFilters&&n.inlineFilters.length>0&&e.jsx("div",{className:t.cn("pb-2 pr-6","pl-2"),children:e.jsx(t.InlineFilterBar,{card:n,sheetId:o||"",inlineFilterValues:l,setInlineFilterValue:ee=>g(n.id,ee),removeInlineFilterValue:ee=>v(n.id,ee)})}),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:Ae()}),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:G,showDebugInfo:!0})]})}const es=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:n,readOnly:r,embedded:!0}),dr=()=>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."})]})]}),ur=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:c})=>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:n,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:a,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:c})})]}),mr=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:c})=>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:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:c,variant:"outline",children:"Close"})]});function xr({triggerVariant:s="icon",className:a,label:n="Customize Visual"}={}){const[r,c]=y.useState(!1),[i,l]=y.useState(""),[d,o]=y.useState(""),[u,p]=y.useState(""),[x,h]=y.useState(""),m=t.useEditorStore(j=>j.card),g=De.useEffectiveEditorCardType(),v=t.useEditorStore(j=>j.card.customCfg),b=v?JSON.stringify(v,null,2):"",C=y.useMemo(()=>g!==m.type?{...m,type:g}:m,[m,g]),{data:E}=t.useEditorCardQuery(C),{data:B}=t.useTopoJson(m),{setCardCustomCfg:S,setCustomVisualCode:M}=t.useEditorActions(),w=j=>{var R,N;return JSON.stringify({...j,data:{...j.data,datasets:(N=(R=j.data)==null?void 0:R.datasets)==null?void 0:N.map(L=>({...L,data:[]}))}},null,2)},D=()=>{var R,N;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){l(w(j)),p(((N=m.preferences)==null?void 0:N.customVisualCode)||"");const L=t.merge(j,v);o(w(L))}},I=()=>{try{if(u&&M(u),d){const j=JSON.parse(d),R=t.getObjectDiff(JSON.parse(i),j);S(R),h("")}}catch{h("Invalid JSON configuration")}},A=Object.keys(v||{}).length===0;return e.jsxs(t.Dialog,{open:r,onOpenChange:c,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",A?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(t.Settings,{className:"h-4 w-4"}),e.jsx("span",{children:n})]}):e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:D,className:t.cn(A?"":"text-green-600 hover:text-green-700",a),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(dr,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Pn,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ur,{customCode:u,cardCustomCfgString:b,mergedConfig:d,onConfigChange:j=>o(j??""),onCodeChange:j=>p(j??"")})]}),e.jsx(mr,{error:x,hasCardCustomConfig:!!v,onReset:()=>{o(i),S(null)},onApply:I,onClose:()=>c(!1)})]})]})}function hr({isStarred:s,onClick:a,className:n}){const r=c=>{c.stopPropagation(),c.preventDefault(),a(c)};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",n),"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 mn({chartType:s,chartName:a,isCustom:n=!1,pluginName:r,isStarred:c,showStar:i=!0,onSelect:l,onToggleStar:d}){return e.jsxs("div",{className:"group relative",children:[i&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",c?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),children:e.jsx(hr,{isStarred:c,onClick:()=>d()})}),n&&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:l,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:a,isCustom:n,className:"h-6 w-6"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:a})]})]})}const xn=[{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 pr({onChartSelect:s,onClose:a}){const[n,r]=y.useState(""),{starredCharts:c,isStarred:i,toggleStar:l}=t.useStarredChartsStore(),{data:d=[],isLoading:o}=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:C,clearModeDrafts:E,initializeModeDrafts:B}=t.useEditorActions(),S=y.useMemo(()=>{if(!n)return xn;const j=n.toLowerCase();return xn.filter(R=>R.name.toLowerCase().includes(j))},[n]),M=y.useMemo(()=>{const j=d.filter(N=>N.componentType==="chart"&&N.pluginType!=="standard");if(!n)return j;const R=n.toLowerCase();return j.filter(N=>N.name.toLowerCase().includes(R))},[d,n]),w=j=>{m(null),p({}),v("builtin"),u(j),["custom","text","map"].includes(j)&&(x(!0),b(void 0)),s==null||s(j),a==null||a()},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);C(L),L[0]&&B(L[0]),a==null||a();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),a==null||a()},I=j=>{const R={type:"default",id:j.id,name:j.name};l(R)},A=j=>{const R={type:"custom",id:j.name,url:j.url,icon:j.icon,name:j.name};l(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:n,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:[S.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:S.map(j=>e.jsx(mn,{chartType:j.id,chartName:j.name,isCustom:!1,isStarred:i("default",j.id),onSelect:()=>w(j.id),onToggleStar:()=>I(j)},j.id))})}),M.length>0&&e.jsxs(e.Fragment,{children:[S.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:M.map((j,R)=>e.jsx(mn,{chartName:j.name,isCustom:!0,pluginName:j.pluginName,isStarred:i("custom",j.name),onSelect:()=>D(j),onToggleStar:()=>A(j)},`${j.url}-${j.name}-${R}`))})]})]}),o&&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..."})]}),S.length===0&&M.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function fr({selectedChart:s,onChartChange:a}){var w,D,I,A;const n=t.useEditorStore(j=>j.card),r=t.useEditorStore(j=>j.frame),c=t.useEditorStore(j=>j.isDevMode),{replaceFrameCards:i,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=t.useEditorActions(),u=y.useMemo(()=>t.findCustomVisualConfigCard(r,n),[r,n]),{manifest:p}=t.useCustomVisual(((w=u==null?void 0:u.customCardPreferences)==null?void 0:w.url)||""),x=y.useMemo(()=>{var j;return(j=p==null?void 0:p.visuals)==null?void 0:j.find(R=>{var N;return R.name===((N=u==null?void 0:u.customCardPreferences)==null?void 0:N.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??n.type,v=(I=n==null?void 0:n.customCardPreferences)==null?void 0:I.componentName,b=(A=u==null?void 0:u.customCardPreferences)==null?void 0:A.componentName,C=h&&!!b,E=y.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=y.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(Ea,{className:"h-4 w-4"})},[g,v]);return{displayChartType:g,displayLabel:E,displayIcon:B,showBadge:C,badgeLabel:b,isMultiInputContext:h,handleChartSelect:j=>{a==null||a(j)},handleClearCustomVisual:j=>{j.stopPropagation();const R={...n,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]),l(),d(R),c&&o(!0),a==null||a("bar")}}}function us({selectedChart:s,onChartChange:a,variant:n="ghost",className:r}){const[c,i]=y.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:u,handleChartSelect:p,handleClearCustomVisual:x}=fr({selectedChart:s,onChartChange:a});return e.jsxs("div",{className:t.cn("relative w-full",r),children:[e.jsxs(t.Popover,{open:c,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"xs",variant:n,role:"combobox","aria-expanded":c,className:t.cn("w-full justify-between gap-2",n==="ghost"&&"border border-border/70 bg-background text-foreground/90",n==="outline"&&"border-border/70 bg-background text-foreground/90",n==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(t.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:h=>h.preventDefault(),children:e.jsx(pr,{onChartSelect:h=>p(h),onClose:()=>i(!1)})})]}),o&&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 gr(){const s=t.useEditorStore(o=>{var u,p;return(p=(u=o.card.preferences)==null?void 0:u.chartOptions)==null?void 0:p.indexAxis}),a=t.useEditorStore(o=>o.card.type),{setChartOrientation:n,setCardPreferences:r}=t.useEditorStore(o=>o.actions),c=o=>{if(n(o),a!=="bullet")return;const u=o==="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 o=s??"x",u=()=>{c(o==="x"?"y":"x")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="x"?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"})})}function l(){const o=()=>{c(s==="y"||s===void 0?"x":"y")};return e.jsx(t.IconButton,{onClick:o,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(Xt,{className:"h-3.5 w-3.5"}):e.jsx(Wt,{className:"h-3.5 w-3.5"})})}function d(){const o=s??"y",u=()=>{c(o==="y"?"x":"y")};return e.jsx(t.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:o==="y"?e.jsx(Wt,{className:"h-3.5 w-3.5"}):e.jsx(Xt,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?l():a==="bullet"?d():i()})}function ms({className:s,triggerVariant:a="icon",label:n="Display Options"}){var v,b,C,E,B,S,M,w,D,I;const r=t.useEditorStore(A=>A.card),{setCardPreferences:c,updateCardInFrame:i,setCard:l}=t.useEditorActions(),[d,o]=y.useState(!1),u=((b=(v=r.preferences)==null?void 0:v.displayOptions)==null?void 0:b.showFilterInfo)??!0,p=((E=(C=r.preferences)==null?void 0:C.displayOptions)==null?void 0:E.showCardToolbar)??!0,x=((S=(B=r.preferences)==null?void 0:B.displayOptions)==null?void 0:S.showChrome)??!0,h=((w=(M=r.preferences)==null?void 0:M.displayOptions)==null?void 0:w.allowScroll)??!0,m=((I=(D=r.preferences)==null?void 0:D.displayOptions)==null?void 0:I.showInlineFilterBar)??!0,g=(A,j)=>{var L;const R={...r.preferences,displayOptions:{...(L=r.preferences)==null?void 0:L.displayOptions,[A]:j}};c(R);const N={...r,preferences:R};l(N),i(N)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(t.DropdownMenu,{modal:!1,open:d,onOpenChange:o,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:a==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n})]}):e.jsx(t.IconButton,{className:"h-7 w-7 p-0",tooltip:"Display Options",children:e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"})})}),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:A=>{g("showFilterInfo",A)},onSelect:A=>A.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:A=>{g("showCardToolbar",A)},onSelect:A=>A.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:A=>{g("showChrome",A)},onSelect:A=>A.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:A=>{g("allowScroll",A)},onSelect:A=>A.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:A=>{g("showInlineFilterBar",A)},onSelect:A=>A.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:a="icon",label:n="Inline Filters"}){var M,w,D;const[r,c]=y.useState(!1),i=t.useEditorStore(I=>I.card),l=t.useEditorStore(I=>I.selectedConnectionId),{tokenProps:d}=t.useSemaphorContext(),{setCard:o}=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=((w=(M=d==null?void 0:d.params)==null?void 0:M.calendarContext)==null?void 0:w.tz)||((D=d==null?void 0:d.params)==null?void 0:D.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone;function b(I){var P,_,z,H,X,K,Z;const A=((z=(_=(P=i==null?void 0:i.dataSource)==null?void 0:P.selectedEntities)==null?void 0:_[0])==null?void 0:z.database)||"",j=I.qualifiedFieldName||I.name;if(g.find(se=>t.doesStoredFilterMatchField(se,I)))return;const N=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:l||((H=i==null?void 0:i.dataSource)==null?void 0:H.connectionId),connectionType:(X=i==null?void 0:i.dataSource)==null?void 0:X.connectionType}),T=t.isCalculatedFilterField(f),V=!!(((K=i==null?void 0:i.dataSource)==null?void 0:K.mode)==="semanticDomain"&&((Z=k==null?void 0:k.selectedEntities)!=null&&Z.length||k!=null&&k.semanticDomainId)),O={id:t.v4(),column:j,title:I.label||I.name,dataType:I.dataType,table:I.entityName||"",database:A,qualifiedTableName:N,connectionId:l||"",operation:"in",sql:T||V?"":t.getDefaultFilterSql(I.dataType,N,F),fieldMeta:f,semanticContext:k,width:250};o({...i,inlineFilters:[...g,O]})}function C(I){const A=g.filter(j=>j.id!==I);o({...i,inlineFilters:A}),m?x(i.id,I):u(i.id,I)}function E(I,A){const j=g.map(F=>F.id===I?{...F,...A}:F);if(o({...i,inlineFilters:j}),!(Object.prototype.hasOwnProperty.call(A,"defaultValues")||Object.prototype.hasOwnProperty.call(A,"defaultDateFilter")))return;const N=j.find(F=>F.id===I);if(!N)return;const L=t.buildFilterValueFromDefaults(N,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 S=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",S&&"w-full",s),children:e.jsxs(t.Popover,{open:r,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:S?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",g.length>0&&"text-primary"),children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),g.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] 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 h-7 w-7 px-0",{"text-primary":g.length>0}),children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),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",S&&"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(jr,{filter:I,onUpdate:A=>E(I.id,A),onRemove:()=>C(I.id)},I.id))})]})]})})]})})}function jr({filter:s,onUpdate:a,onRemove:n}){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=>a(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:n,children:e.jsx(t.X,{className:"h-3 w-3"})})]})]})}const br={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function vr(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const yr={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function Vt(s,a){return`${s}:${a}`}function Nr(s,a,n){const r=new Set(n.filter(i=>i.target!=="sql_param").map(i=>Vt(i.controlId,i.target))),c=a.map(i=>{const l=t.getCompatibleBindingTargetOptions({card:s,control:i}).map(p=>p.value),d=yr[i.type],u=[...d?[d]:[],...l.filter(p=>p!==d)].find(p=>!r.has(Vt(i.id,p)));return u?{controlId:i.id,target:u}:null}).find(Boolean);return c?{controlId:c.controlId,target:c.target,mapping:{}}:null}function Cr({card:s,dashboardControls:a,bindings:n,onChange:r,availableFieldChoices:c,availableMetricChoices:i,suppressTransientStaleState:l=!1}){const d=[...a,...s.controls||[]],[o,u]=y.useState({}),p=t.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),x=t.getBindingTargetSuggestions(s),h=new Set(n.map(B=>Vt(B.controlId,B.target))),m=d.some(B=>t.getCompatibleBindingTargetOptions({card:s,control:B}).some(S=>!h.has(Vt(B.id,S.value)))),g=l?0:n.reduce((B,S)=>{const M=v(S.target),w=Object.values(S.mapping).filter(D=>{const I=S.target==="config_metric_selector"||S.target==="config_field_selector"?typeof D=="string"?D:D==null?void 0:D.id:typeof D=="string"?D:void 0;return typeof I=="string"&&!M.some(A=>A.value===I)}).length;return B+w},0);function v(B){var S,M,w,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})):((M=(S=s.config)==null?void 0:S.metricColumns)==null?void 0:M.map(I=>({value:I.id,label:I.label||I.id,target:I})))||[];case"config_field_selector":return c?c.filter(I=>!!I.target).map(I=>({value:I.target.id,label:I.target.label||I.option.label,target:I.target})):((D=(w=s.config)==null?void 0:w.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,S)=>{r(n.map((M,w)=>w!==B?M:S(M)))},C=B=>{r(n.filter((S,M)=>M!==B))},E=()=>{const B=Nr(s,d,n);B&&r([...n,B])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const B=p.map(({controlId:S,paramId:M})=>{const w=d.find(D=>D.id===S);return w?{id:S,paramId:M,label:w.label,reference:`[[param.${M}]]`}:{id:S,paramId:M,label:S,reference:`[[param.${M}]]`}});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(S=>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:S.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:S.reference}),e.jsx(t.CopyButton,{text:S.reference,ariaLabel:`Copy ${S.reference}`})]})]})},`${S.id}:${S.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,n.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."}):n.map((B,S)=>{const M=x[B.target]||[],w=d.find(f=>f.id===B.controlId),D=w?t.ensureManualSource(w):null,I=(D==null?void 0:D.source.kind)==="manual"?D.source.options:[],A=v(B.target),j=Array.from(new Set([...I.map(f=>f.value),...Object.keys(B.mapping)])).map(f=>{const k=I.find(T=>T.value===f);return{value:f,label:(k==null?void 0:k.label)||f}}),R=`${B.controlId}-${B.target}-${S}`,N=o[R]??S===0,L=Object.keys(B.mapping).length,F=w!=null&&w.type?br[w.type]||w.type:null;return e.jsxs(t.Collapsible,{open:N,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:[N?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:(w==null?void 0:w.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:()=>C(S),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."}):A.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],T=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=!l&&typeof T=="string"&&!A.some(_=>_.value===T),O=vr(k,T),P=T&&V?[...A,{value:T,label:"Needs remap",target:k}]:A;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:T||"__none__",onValueChange:_=>b(S,z=>{if(z.target==="config_metric_selector"){const X={...z.mapping};if(_==="__none__")delete X[f.value];else{const K=P.find(Z=>Z.value===_);K!=null&&K.target?X[f.value]=K.target:delete X[f.value]}return{...z,mapping:X}}if(z.target==="config_field_selector"){const X={...z.mapping};if(_==="__none__")delete X[f.value];else{const K=P.find(Z=>Z.value===_);K!=null&&K.target?X[f.value]=K.target:delete X[f.value]}return{...z,mapping:X}}const H={...z.mapping};return _==="__none__"?delete H[f.value]:H[f.value]=_,{...z,mapping:H}}),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}`)})}),M.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",M.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 Sr=[];function wr({className:s,triggerVariant:a="icon",label:n="Controls"}){var N,L;const{handleOpenChange:r,preventPassiveDismissDuringCreate:c,resolvedOpen:i,setIsCreateFlowActive:l}=De.useCreateFlowOverlayState({}),d=t.useEditorStore(F=>F.card),o=t.useEditorStore(F=>F.frame),u=t.useDashboardStore(F=>F.dashboard),x=t.useDashboardStore(F=>F.dashboard.controls)||Sr,{setCard:h,updateCardInFrame:m}=t.useEditorActions(),[g,v]=y.useState(null);y.useEffect(()=>{i&&!g&&(d!=null&&d.id)&&v(d.id)},[d==null?void 0:d.id,i,g]),y.useEffect(()=>{!i&&g!==null&&v(null)},[i,g]);const b=y.useMemo(()=>g?(o==null?void 0:o.cards.find(F=>F.id===g))||((d==null?void 0:d.id)===g?d:void 0):d,[d,o==null?void 0:o.cards,g]),C=(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"),S=t.buildCardControlUsageById({card:b,controls:C}),M={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((N=b==null?void 0:b.config)==null?void 0:N.groupByColumns)||[]).map(F=>[F.id,F]))},w={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=M.choices.map(F=>({option:F,target:M.targetMap[F.value]})),I=w.choices.map(F=>({option:F,target:w.targetMap[F.value]})),A=(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,T={...k,controls:F,controlBindings:t.syncStructuralBindingsWithControls(k.controlBindings,F)};m(T),(d==null?void 0:d.id)===T.id&&h(T)},j=F=>{if(!b)return;const f={...b,controlBindings:t.mergeConfigBindingsWithSqlParamBindings(F,b.controlBindings)};m(f),(d==null?void 0:d.id)===f.id&&h(f)},R=a==="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-7 w-full justify-start gap-2 px-2 text-[13px]",(C.length>0||B.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:n}),C.length+B.length>0&&e.jsx("span",{className:"ml-auto inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-primary text-[10px] font-medium leading-none text-primary-foreground",children:C.length+B.length})]}):e.jsxs(t.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":C.length>0||B.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),C.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:C.length+B.length})]})}),e.jsxs(t.PopoverContent,{className:"flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",align:"end",onEscapeKeyDown:c,onPointerDownOutside:c,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:C,reservedControlIds:E,usageByControlId:S,availableFieldChoices:D,availableMetricChoices:I,onCreateFlowActiveChange:l,onChange:(F,f,k)=>A(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(Cr,{card:b,dashboardControls:x,bindings:B,onChange:j,availableFieldChoices:D,availableMetricChoices:I}):null]})})]})]})})}function Bn({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:n=!0,showControls:r=!0,showDisplayOptions:c=!0}={}){const i=t.useEditorStore(m=>m.card),l=t.useEditorStore(m=>{var g,v;return(v=(g=m.card)==null?void 0:g.preferences)==null?void 0:v.chartOptions}),d=t.getChartGridStyle(l),{setChartGrid:o}=t.useEditorActions();function u(){const m=["xy","none","x","y"],v=(m.indexOf(d)+1)%m.length;o(m[v])}const p=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(i.type),x=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(i.type);return p||x||n||r||c?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[p&&e.jsx(e.Fragment,{children:e.jsx(gr,{})}),x&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:u,className:"h-7 w-7 px-0",children:[(d==="xy"||!d)&&e.jsx(t.Grid3x3,{className:"h-3.5 w-3.5"}),d==="x"&&e.jsx(cs,{className:"h-3.5 w-3.5"}),d==="y"&&e.jsx(zt,{className:"h-3.5 w-3.5"}),d==="none"&&e.jsx(t.Square,{className:"h-3.5 w-3.5"})]}),n&&e.jsx(xs,{}),r&&e.jsx(wr,{}),c&&e.jsx(ms,{})]}):null}function Tr({visible:s}){const a=t.useDashboardStore(l=>l.selectedFrameId),n=t.useManagementStore(l=>l.selectedVisual),r=t.useEditorStore(l=>l.frame),i=!!!(r!=null&&r.visualId||n!=null&&n.id)&&!!a;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 Er({isPreviewMode:s,onPreviewToggle:a,configCard:n}){var F,f,k,T,V;const r=t.useEditorStore(O=>O.frame),c=t.useEditorStore(O=>O.card),{setFrame:i,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:u,initializeModeDrafts:p}=t.useEditorActions(),{manifest:x}=t.useCustomVisual(((F=n==null?void 0:n.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=n==null?void 0:n.customCardPreferences)==null?void 0:P.componentName)}),g=t.resolveMultiInputType(n,h)==="multiple",v=(h==null?void 0:h.minInputs)??((k=n==null?void 0:n.customCardPreferences)==null?void 0:k.minInputs)??1,b=(h==null?void 0:h.maxInputs)??((T=n==null?void 0:n.customCardPreferences)==null?void 0:T.maxInputs),C=y.useMemo(()=>t.getCustomVisualInputCards({frame:r,configCard:n,isMultiInputVisual:g}),[r,n,g]),E=g?C.filter(Boolean).length:r.cards.length,B=b?E<b:!0,S=E>Math.max(v||1,1),M=!!((V=n==null?void 0:n.customCardPreferences)!=null&&V.dataInputCardIds),w=(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),[H]=z.splice(parseInt(_),1);z.splice(P,0,H),i({...r,cards:z})};function A(O){const P=(n==null?void 0:n.id)===O;if(!(M&&P?r.cards.length>1:S))return;let z=r.cards.filter(Z=>Z.id!==O);g&&!M&&(z=t.reindexSlotCards(z));const H=z[0],X={...r,cards:z,activeCardId:H.id},K=O===c.id;K&&u(),i(X),l(H.id),d(H),K&&p(H)}function j(O,P){if(!B)return;const _={...r,cards:[...r.cards,P],activeCardId:O.id};i(_),l(P.id)}function R(){if(g&&(n==null?void 0:n.id)===c.id){N(c);return}const O={...c,id:t.v4(),title:`${c.title} Copy`,tabTitle:`${c.tabTitle||c.title} Copy`,customCardPreferences:c.customCardPreferences?{...c.customCardPreferences,slotIndex:g?Math.max(-1,...C.map((P,_)=>t.getSlotIndexForCard(P,_)))+1:c.customCardPreferences.slotIndex}:void 0};j(c,O)}function N(O){var K;if(!B)return;let P=g?"table":"bar",_="Title",z="";const H=g?Math.max(-1,...C.map((Z,se)=>t.getSlotIndexForCard(Z,se)))+1:E;if(g&&((K=h==null?void 0:h.slots)!=null&&K.length)){const Z=t.getSlotDefinitionForIndex(h.slots,H);Z&&(P=t.getSlotExpectedChartType(Z),_=Z.label||`Tab ${H+1}`,z=Z.description||"")}const X={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:H}}};j(O,X)}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;d({...P,displayTab:_}),o({...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 K,Z;const _=g?t.getSlotIndexForCard(O,P):-1,z=g&&((K=h==null?void 0:h.slots)!=null&&K.length)&&_>=0?t.getSlotDefinitionForIndex(h.slots,_):null,H=z?(Array.isArray(z.expectedType)?z.expectedType[0]:z.expectedType)||"table":O.type,X=g&&((Z=h==null?void 0:h.slots)==null?void 0:Z.length)&&h.slots.every(se=>typeof se.position=="number"||typeof se.position=="string"&&!se.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!g,onDragStart:g?void 0:se=>w(se,P),onDragOver:g?void 0:D,onDrop:g?void 0:se=>I(se,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(H,"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:se=>{d({...c,tabTitle:se}),o({...c,tabTitle:se})},children:O.tabTitle||O.title},O.id)]}),r.activeCardId===O.id&&!X&&e.jsx(t.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:se=>{se.stopPropagation(),R()}}),r.activeCardId===O.id&&(M&&(n==null?void 0:n.id)===O.id?r.cards.length>1:S)&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>A(O.id)})]},O.id)}),e.jsx(t.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>N(c),disabled:!B,children:e.jsx(t.Plus,{className:"h-4 w-4"})}),g&&e.jsxs(t.Toggle,{pressed:s,onPressedChange:a,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:a=!1}={}){var Ee,$,le,ge,ee;const n=t.useEditorStore(Q=>Q.frame),r=t.useEditorStore(Q=>Q.card),[c,i]=y.useState(!1),l=y.useMemo(()=>t.findCustomVisualConfigCard(n,r),[n,r]),d=t.useEditorStore(Q=>Q.isSqlRunning);t.useEditorStore(Q=>Q.isDevMode);const{setFrame:o,setActiveTabCardId:u,setCard:p,setRunSql:x,mergeDraftsIntoCard:h,clearModeDrafts:m,initializeModeDrafts:g}=t.useEditorActions(),[v,b]=y.useState({}),[C,E]=y.useState(()=>new Set),{theme:B}=t.useTheme(),S=t.useDashboardStore(Q=>Q.themeStyle),{authToken:M}=t.useSemaphorContext(),w=t.getTokenParams(M==null?void 0:M.accessToken),D={mode:B||"system",colors:(($=(Ee=S==null?void 0:S.chart)==null?void 0:Ee.dataset)==null?void 0:$.backgroundColor)||[]},{getCard:I,manifest:A,isLoading:j}=t.useCustomVisual(((le=l==null?void 0:l.customCardPreferences)==null?void 0:le.url)||""),R=(ge=l==null?void 0:l.customCardPreferences)==null?void 0:ge.componentName,N=R?I(R):null,L=(ee=A==null?void 0:A.visuals)==null?void 0:ee.find(Q=>Q.name===R),F=t.resolveMultiInputType(l,L),f=c&&F==="multiple"&&!!l,k=y.useMemo(()=>t.getCustomVisualInputCards({frame:n,configCard:l,isMultiInputVisual:!0}).map(re=>(re==null?void 0:re.id)===r.id?r:re),[n,l,r]),T=y.useMemo(()=>t.buildSlotOrderedCards(k),[k]),V=y.useMemo(()=>{const Q=k.findIndex(re=>(re==null?void 0:re.id)===r.id);return Q<0?-1:t.getSlotIndexForCard(r,Q)},[k,r]),O=y.useMemo(()=>!l||F!=="multiple"||V<0?r.type:t.getEffectiveCardTypeForSlot(r,V,L==null?void 0:L.slots)??r.type,[l,F,V,r,L==null?void 0:L.slots]),P=y.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:H,isError:X}=t.useEditorCardQuery(P),K=y.useCallback((Q,re)=>{const ce=t.normalizeMultiInputPayload(re);b(Se=>({...Se,[Q]:ce}))},[]),Z=y.useCallback((Q,re)=>{E(ce=>{const Se=new Set(ce);return re?Se.add(Q):Se.delete(Q),Se})},[]),se=C.size>0,me=t.useInteractionStore(Q=>Q.interactionStates),je=t.useDashboardStore(Q=>{var re;return(re=Q.dashboard)==null?void 0:re.id}),te=t.useDashboardStore(Q=>Q.dashboard.filters),ne=t.useDashboardStore(Q=>Q.filterValues),ue=t.useDashboardStore(Q=>Q.selectedSheetId),be=t.useEditorStore(Q=>Q.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),fe=t.useEditorStore(Q=>Q.actions.setCardInlineFilterValue),ve=t.useEditorStore(Q=>Q.actions.removeCardInlineFilterValue),G=y.useMemo(()=>l?t.buildInlineFilterNodes({card:l,sheetId:ue||"",inlineFilterValues:be,setInlineFilterValue:Q=>fe(l.id,Q),removeInlineFilterValue:Q=>ve(l.id,Q)}):[],[l,ue,be,fe,ve]),{cardFilters:pe,cardFilterValues:Ce}=y.useMemo(()=>l?t.calculateContextAwareFilters({card:l,interactionStates:me,currentDashboardId:je,filters:te,filterValues:ne,selectedSheetId:ue}):{cardFilters:[],cardFilterValues:[]},[l,me,je,te,ne,ue]);function Oe(Q){const re=n.cards.find(ce=>ce.id===Q);re&&(it.flushPendingEditorDrafts(),h(),Ve(Q),u(Q),m(),g(re))}function Ve(Q){const re=t.useEditorStore.getState().card,ce=t.useEditorStore.getState().frame,Se={...ce,cards:ce.cards.map(Fe=>Fe.id===re.id?re:Fe),activeCardId:Q};o(Se);const ye=Se.cards.find(Fe=>Fe.id===Q);ye.sql&&x(!0),p(ye)}function Ae(){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(!N)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 re=T.map((ce,Se)=>t.getEffectiveCardTypeForSlot(ce,Se,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,Se)=>{if(!ce)return null;const ye=t.getSlotIndexForCard(ce,Se),Fe=t.getEffectiveCardTypeForSlot(ce,ye,L==null?void 0:L.slots);return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:Z,onDataChange:K,card:ce,effectiveCardType:Fe},`${ce.id}-${ye}`)}),se&&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",se&&"opacity-50"),children:e.jsx(y.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(N,{editing:!0,...t.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:T,slotTypes:re,multiInputData:v,params:w,theme:D,filters:pe,filterValues:[...Ce||[],...be||[]],inlineFilters:G})})})})]})}function Te(){var Q;return f?Ae():s&&(a||!z&&!H&&!X)?s({card:r,data:_,isLoading:z,isFetching:H,isError:X}):r.type==="kpi"?z||H?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(Tr,{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||H,isError:X,comparisonMetadata:(Q=_==null?void 0:_.metadata)==null?void 0:Q.comparisonMetadata})}),t.isCardSummaryVisibleOnCard(r)&&e.jsx(t.CardSummary,{card:r,mode:"editor"})]})}):r.type==="text"?z||H?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:d,card:r,data:_==null?void 0:_.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackVisual,children:e.jsx(Pn,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Oe,value:n.activeCardId,className:"flex grow flex-col gap-2",children:[f?e.jsx("div",{className:"mt-0 grow",children:Te()}):n.cards.map(Q=>e.jsx(t.TabsContent,{className:"mt-0 grow focus-visible:ring-0 focus-visible:ring-offset-0",value:Q.id,children:Te()},Q.id)),e.jsx(Er,{isPreviewMode:f,onPreviewToggle:i,configCard:l})]})}function Ir({onClick:s,className:a}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",a),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Vn({fallbackPreview:s,records:a,title:n,isInspectorOpen:r,onInspectorOpenChange:c}){var L;const i=t.useEditorStore(F=>F.card),l=t.useEditorStore(F=>F.actions.setCard),d=t.useEditorStore(F=>F.actions.updateCardInFrame),o=t.normalizeDynamicRendererSource((L=i.dynamicCardPreferences)==null?void 0:L.rendererCode),[u,p]=y.useState(o),[x,h]=y.useState(o);y.useEffect(()=>{p(o),h(o)},[o,i.id]);const m=y.useMemo(()=>t.normalizeDynamicRendererSource(u),[u]),g=y.useMemo(()=>t.validateDynamicRendererSource(m),[m]),v=!!o,b=y.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:n||i.title})},[i,x,n]),C=!!x,E=m!==x,B=x!==o,S=!m||!g.valid||E||B,M=m?g.valid?E?"Unapplied changes":"Pending save":"Needs attention":"Draft",w=!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 A(){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:n||i.title});l(F),d(F),c(!1),t.ue.success(x?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function R(){p(o),h(o),c(!1)}function N(){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:a,title:n,layoutMode:"fill",fallback:s},o||"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(Ir,{onClick:()=>c(!0)})]})}),e.jsx(t.Dialog,{open:r,onOpenChange:F=>{if(!F){R();return}c(!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."})]}),S&&e.jsx(t.Badge,{className:"mr-4 shrink-0",variant:w,children:M})]})}),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:C?e.jsx(t.PersistedDynamicVisual,{card:b,records:a,title:n,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:N,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:A,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 zn({onCustomize:s}){const a=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>u.frame),r=t.useEditorStore(u=>u.actions.setIsShowingVisual),{setVisualizationMode:c,setDynamicCardPreferences:i}=t.useEditorActions(),d=t.getVisualizationMode(a)==="dynamic";if(n.cards.length!==1||t.isCustomVisualizationCard(a))return null;const o=u=>{var p;u==="dynamic"&&!a.dynamicCardPreferences&&i(t.createEmptyDynamicCardPreferences(a.type,(p=a.preferences)==null?void 0:p.displayOptions)),c(u),r(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuItem,{onSelect:u=>{u.preventDefault(),o(d?"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:d,onCheckedChange:u=>o(u?"dynamic":"builtin"),onClick:u=>u.stopPropagation()})]}),d&&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 hn({children:s,visualAsideControl:a}){var je;const n=t.useQueryClient(),r=t.useEditorStore(te=>te.frame),c=t.useEditorStore(te=>te.card),i=c.type==="table"||c.type==="detailTable",l=t.useEditorStore(te=>te.isDevMode),d=t.useEditorStore(te=>te.isShowingVisual),o=t.useEditorStore(te=>te.actions.setIsShowingVisual),u=t.useDashboardStore(te=>te.isVisualEditing),{isConsoleMode:p}=t.useDashboardPreferences(),x=t.useEditorStore(te=>te.pythonStdOut),h=t.useEditorStore(te=>te.actions.setRunSql),m=De.useEffectiveEditorCardType(),v=t.getVisualizationMode(c)==="dynamic",[b,C]=y.useState(!1),{setFrame:E,setCard:B,setActiveTabCardId:S,setCardPreferences:M,mergeDraftsIntoCard:w,clearModeDrafts:D,initializeModeDrafts:I,updatePageSize:A}=t.useEditorActions(),j=y.useMemo(()=>m!==c.type?{...c,type:m}:c,[c,m]),{data:R,isLoading:N,isFetching:L,errorMessage:F,errorSql:f,refetch:k,queryKey:T,pagination:V}=t.useEditorCardQuery(j),O=y.useRef(T);O.current=T;const{handleDebugWithAssistant:P}=On(F,f),_=y.useMemo(()=>(R==null?void 0:R.records)||[],[R==null?void 0:R.records]),[z,H]=y.useState(!1);y.useEffect(()=>{L||H(!1)},[L]),y.useEffect(()=>{i&&!d&&!l&&!p&&o(!0)},[p,l,i,d,o]);function X(te,ne){var fe,ve;const ue={...c,paginationConfig:{page:te+1,pageSize:ne}};B(ue);const be={...r,cards:r.cards.map(G=>G.id===c.id?ue:G)};E(be),c.sql&&((ve=(fe=c.preferences)==null?void 0:fe.tablePrefs)!=null&&ve.enableDevModePagination)&&h(!0)}function K(te){var fe,ve,G,pe,Ce;const ne=t.sortStateToSortByColumns(te,(fe=c.config)==null?void 0:fe.metricColumns,(ve=c.config)==null?void 0:ve.groupByColumns,(G=c.config)==null?void 0:G.detailColumns),ue={...c,config:{...c.config||{},sortByColumns:ne}};B(ue);const be={...r,cards:r.cards.map(Oe=>Oe.id===c.id?ue:Oe)};E(be),c.sql&&((Ce=(pe=c.preferences)==null?void 0:pe.tablePrefs)!=null&&Ce.enableDevModePagination)&&h(!0)}function Z(){var ne;const te=JSON.stringify(R==null?void 0:R.records,null,2);typeof navigator>"u"||!((ne=navigator.clipboard)!=null&&ne.writeText)||navigator.clipboard.writeText(te).catch(ue=>{console.error("Failed to copy JSON",ue)})}function se(){const te=JSON.stringify(R==null?void 0:R.records,null,2),ne=new Blob([te],{type:"application/json"}),ue=URL.createObjectURL(ne),be=document.createElement("a");be.href=ue,be.download=`${c.title}.json`,be.click()}function me(){const ne=[Object.keys(R==null?void 0:R.records.reduce((ve,G)=>({...ve,...G}),{})).join(","),...((R==null?void 0:R.records)||[]).map(ve=>Object.values(ve).join(","))].join(`
|
|
182
|
-
`),ue=new Blob([ne],{type:"text/csv"}),be=URL.createObjectURL(ue),fe=document.createElement("a");fe.href=be,fe.download=`${c.title}.csv`,fe.click()}return c?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:[d&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(a==null?void 0:a.show)&&e.jsx(t.IconButton,{tooltip:a.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-7 w-7 px-0",buttonProps:{variant:"outline"},onClick:a.onToggle,children:a.isOpen?e.jsx(t.ChevronLeft,{className:"h-3.5 w-3.5"}):e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5"})}),!v&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:l?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:N||L,className:"h-7 w-7 px-0",onClick:()=>{if(H(!0),l){it.flushPendingEditorDrafts(),setTimeout(()=>{n.removeQueries({queryKey:O.current,exact:!0}),h(!0)},0);return}k()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":z})})}),!v&&e.jsx(Bn,{showInlineFilters:!1,showDisplayOptions:!1}),(l||p)&&e.jsxs(e.Fragment,{children:[e.jsx(Ar,{}),i&&e.jsx(kr,{})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),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(c.type)&&u&&e.jsx(xr,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(zn,{onCustomize:()=>C(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:me,children:[e.jsx(t.Download,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:se,children:[e.jsx(fa,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:Z,children:[e.jsx(t.Copy,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),d?v?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Vn,{fallbackPreview:e.jsx(ot,{}),records:_,title:c.title,isInspectorOpen:b,onInspectorOpenChange:C})}):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(Dr,{})}),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&&(l?e.jsx(or,{data:R.records,card:j,paginationMetadata:V,onPaginationChange:X,onPageSizePreferenceChange:A,onSortChange:K,isLoading:N||L}):R.records.length>0?e.jsx(t.TableVisual,{card:c,data:_,comparisonMetadata:(je=R==null?void 0:R.metadata)==null?void 0:je.comparisonMetadata,paginationMetadata:V,onPaginationChange:X,onSortChange:K,isLoading:N||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||c.sql||c.python,onDebugWithAssistant:P,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Dr(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=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:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function kr(){var d,o,u,p,x,h,m,g;const s=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>v.actions.setCard),n=t.useEditorStore(v=>v.actions.setRunSql),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=t.useEditorStore(v=>v.actions.updateCardInFrame),i=y.useMemo(()=>{var v,b;return t.getTablePageSizeOptions((b=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:b.pageSize)},[(o=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.pageSize]),l=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-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:v=>{var E,B,S;const b=Number(v),C={...s,preferences:{...s.preferences,tablePrefs:{...(E=s.preferences)==null?void 0:E.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(C),c(C),s.sql&&((S=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&S.enableDevModePagination)&&n(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(v=>e.jsx(t.SelectItem,{value:String(v),children:v},v))})]})]})}function Ar(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:n=>{a(!n)},variant:"default",size:"sm",className:"h-7 gap-1.5 rounded-[5px] border border-transparent px-2.5 text-[12px] 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-3.5 w-3.5"}),e.jsx("span",{children:"Query Output"})]})}function qe({value:s,onCommit:a,type:n="text",placeholder:r,className:c}){const[i,l]=y.useState(s),d=y.useRef(!1);y.useEffect(()=>{l(s)},[s]);const o=()=>{if(d.current){d.current=!1;return}i!==s&&a(i)},u=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:n,placeholder:r,value:i,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:u,className:c})}function nt({defaultValue:s,label:a,options:n,value:r,onValueChange:c,className:i,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:c,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:[l&&e.jsx("span",{children:l}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function Mr(s,a){return t.getSlotDefinitionForIndex(s,a)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,r,c]=a;return`Tabs ${Number(r)+1}-${Number(c)+1}`}const n=s.match(/^(\d+)\+$/);return n?`Tabs ${Number(n[1])+1}+`:`Tab ${s}`}function Lr(s){return s?Array.isArray(s)?s:[s]:[]}function ts(s){var r,c;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const a=!!((c=s.sql)!=null&&c.trim()),n=t.hasValidCardConfig(s.config);return a||n}function Fr({slots:s,cards:a,minInputs:n}){const r=[],c=a.filter(Boolean).length;return n&&c<n&&r.push({type:"too-few-inputs",message:`This visual requires at least ${n} tab${n===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const o=a[i.position];ts(o)||r.push({type:"missing-required",message:`${St(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,u]=l.map(Number);for(let p=o;p<=u;p+=1){const x=a[p];if(!ts(x)){r.push({type:"missing-required",message:`${St(p)} ("${i.label}") is required but has no data configured.`});break}}return}const d=i.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(a.length<=o){r.push({type:"missing-required",message:`${St(o)} ("${i.label}") is required but has no data configured.`});return}for(let u=o;u<a.length;u+=1){const p=a[u];if(!ts(p)){r.push({type:"missing-required",message:`${St(u)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const d=Mr(s,l);if(!d||!d.expectedType)return;const o=Lr(d.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${St(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Rr={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:a})=>(a==null?void 0:a.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 _n(){var N,L,F;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=t.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),c=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=y.useMemo(()=>t.findCustomVisualConfigCard(c,r),[c,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:u}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(N=u==null?void 0:u.visuals)==null?void 0:N.find(f=>f.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),h=t.resolveMultiInputType(l||r,p)==="multiple",m=!!l&&l.id===r.id,g=(p==null?void 0:p.minInputs)??((L=l==null?void 0:l.customCardPreferences)==null?void 0:L.minInputs),v=(p==null?void 0:p.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),b=y.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:l||r,isMultiInputVisual:h}),[c,l,r,h]),C=y.useMemo(()=>t.buildSlotOrderedCards(b),[b]),E=y.useMemo(()=>C.map((f,k)=>{if(!f)return null;const T=t.getSlotIndexForCard(f,k),V=t.getEffectiveCardTypeForSlot(f,T,p==null?void 0:p.slots);return{...f,type:V??f.type}}),[C,p==null?void 0:p.slots]),B=y.useMemo(()=>Fr({slots:p==null?void 0:p.slots,cards:E,minInputs:g}),[p==null?void 0:p.slots,E,g]),S=y.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 M(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 T=f.match(/^(\d+)\+$/);return T?`Tabs ${Number(T[1])+1}+`:`Tab ${f}`}function w(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function D(f,k,T=[],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:H=>{A({key:k,value:H,settingsField:O,settingsValue:P,sourceCard:_})}},k):f==="select"?e.jsx(nt,{className:"h-8 w-full",label:"",options:T,value:String(z!==void 0?z:V??""),onValueChange:H=>{A({key:k,value:H,settingsField:O,settingsValue:P,sourceCard:_})}}):null}function I({key:f,defaultValue:k,settingsValue:T,sourceCard:V}){const O=T==null?void 0:T[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 A({key:f,value:k,settingsField:T,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||{},[T]:P})}function j({settingsSchema:f,settingsField:k,settingsValue:T,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 H;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}),((H=z.docs)==null?void 0:H.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,T,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:M(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:[w(f.expectedType)&&e.jsxs("span",{children:["Expected: ",w(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:l||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=S>=0?S:0,T=m?"Slot 0":`Slot ${k}`;return f?`${T}: ${f} Settings`:`${T} 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(nt,{icon:e.jsx(In,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(d==null?void 0:d.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:o&&e.jsx(nt,{icon:e.jsx(pa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.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),T=o==null?void 0:o.find(O=>O.name===f);i({...s,componentName:f,visualType:(k==null?void 0:k.visualType)||(T==null?void 0:T.type)||"single",minInputs:k==null?void 0:k.minInputs,maxInputs:k==null?void 0:k.maxInputs,pluginChartType:k==null?void 0:k.chartType})}})})]})})]}),((d==null?void 0:d.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:Rr,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((T,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:T})]},V))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Or({colorRanges:s,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(l,d,o){const u=[...s];u[l]={...u[l],[d]:o},a(u)}function c(l){const d=[...s];d.splice(l,1),a(d)}function i(){a([...s,n])}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((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(d,"color",o.target.value),value:l.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:()=>c(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Pr(){var p,x,h,m,g;const s=t.useEditorStore(v=>v.card.preferences),a=t.useEditorStore(v=>v.actions.setCardPreferences),n=t.useEditorStore(v=>v.card),r=t.hasValidCardConfig(n.config),c=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.decimalPlaces});const i=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.locale}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const d=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.colorRanges})||[],o=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=>{a({...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,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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:l||"none",onValueChange:v=>{var b,C,E;console.log("currency",v),c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,v==="none"?"":v,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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,C,E;return c(Number(v),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((C=s==null?void 0:s.formatNumber)==null?void 0:C.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,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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(Or,{colorRanges:d,setColorRanges:o})]})]})}const Br={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 qn(s){return Br[s]}function Vr({chartType:s,showDocsLink:a=!0}){const n=qn(s);return n?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:n.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:n.fields.map((r,c)=>e.jsxs("tr",{className:c<n.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:n.description}),a&&n.docsUrl&&e.jsxs("a",{href:n.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 zr({chartType:s}){return qn(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(Vr,{chartType:s})})]}):null}function _t({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:a}),e.jsx(zr,{chartType:s})]})}function _r(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Pr,{})})]})}function pn({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function $n(){const[s,a]=y.useState([]),n=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:c}=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}),y.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(u,p){var x,h;p?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?c({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):c({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(c({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(m=>m.columnIndex!==u)}),a(m=>{const g=[...m];return g[u]=!1,g}))}function d(u,p){var h;const x=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(m=>m.columnIndex===u?{...m,expression:p.target.value}:m);c({...n,onClickFilter:x})}function o(u){var p,x,h,m;if(s!=null&&s[u]||(x=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))!=null&&x.expression)return e.jsx(t.Input,{value:(m=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>d(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=n==null?void 0:n.onClickFilter)!=null&&x.find(m=>m.columnIndex===p)),onCheckedChange:m=>l(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=n==null?void 0:n.onClickFilter)==null?void 0:h.find(m=>m.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[p]=!m[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},u)})})}const qr=[{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"}],$r=["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"],Kr=$r.map(s=>({label:s,value:s}));function Gr(){var o,u,p,x,h,m,g,v,b,C,E,B,S,M,w,D,I,A;const s=t.useEditorStore(j=>j.card),a=(u=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=y.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:c}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(j=>({label:j,value:j}))||[],d=[{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(pn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(nt,{className:"h-9",options:d,onValueChange:j=>{console.log("value",j),c({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:j=>{r(j.target.value)},onBlur:()=>{var j;console.log("onBlur",n),c({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.mapVisualOptions,customTopoJsonUrl:n}})},value:n,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(nt,{className:"h-9",options:l,value:((m=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var R;c({...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(nt,{className:"h-9",options:qr,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:j=>{var R;c({...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(nt,{className:"h-9",options:Kr,value:((C=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(pn,{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;c({...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:((w=(M=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:w[0])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(j.target.value),((F=(L=(N=s.preferences)==null?void 0:N.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:((A=(I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:A[1])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(L=(N=s.preferences)==null?void 0:N.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($n,{})]})}function Kn({color:s,onColorChange:a,onClose:n}){const[r,c]=y.useState(0),[i,l]=y.useState(100),[d,o]=y.useState(50),[u,p]=y.useState(s);y.useEffect(()=>{const b=fn(s);if(b){const C=gn(b.r,b.g,b.b);c(C.h),l(C.s),o(C.l),p(s)}},[s]);const x=b=>{c(b),m(b,i,d)},h=b=>{const C=b.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(b.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(b.clientY-C.top)/C.height)),S=E*100,M=(1-B)*100;l(S),o(M),m(r,S,M)},m=(b,C,E)=>{const B=Hr(b,C,E),S=Ur(B.r,B.g,B.b);p(S)},g=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const C=fn(b);if(C){const E=gn(C.r,C.g,C.b);c(E.h),l(E.s),o(E.l)}}},v=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};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-d}%`,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:n,children:"Cancel"}),e.jsx(t.Button,{onClick:v,children:"OK"})]})]})}function fn(s){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Ur(s,a,n){return"#"+((1<<24)+(s<<16)+(a<<8)+n).toString(16).slice(1)}function gn(s,a,n){s/=255,a/=255,n/=255;const r=Math.max(s,a,n),c=Math.min(s,a,n);let i=0,l=0;const d=(r+c)/2;if(r!==c){const o=r-c;switch(l=d>.5?o/(2-r-c):o/(r+c),r){case s:i=((a-n)/o+(a<n?6:0))/6;break;case a:i=((n-s)/o+2)/6;break;case n:i=((s-a)/o+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(d*100)}}function Hr(s,a,n){s/=360,a/=100,n/=100;let r,c,i;if(a===0)r=c=i=n;else{const l=(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),d=n<.5?n*(1+a):n+a-n*a,o=2*n-d;r=l(o,d,s+1/3),c=l(o,d,s),i=l(o,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(c*255),b:Math.round(i*255)}}const jn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Qr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function at({value:s,onChange:a,label:n}){const[r,c]=y.useState(!1),[i,l]=y.useState(!1),d=()=>{const o=jn.find(u=>u.value===s);return o?o.color:s.startsWith("#")?s:jn[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:c,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:d()},"aria-label":`Change color for ${n}`})}),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:Qr.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),c(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),c(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),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:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Kn,{color:d(),onColorChange:o=>{a(o),l(!1)},onClose:()=>l(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function bn(s,a){if(!a||a==="auto")return{type:"auto"};const n={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?is(n,Bt(a)):n}function is(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Jr=["auto","number","currency","percent","scientific","date"],Yr=[{value:"USD",label:"USD - US Dollar"},{value:"EUR",label:"EUR - Euro"},{value:"JPY",label:"JPY - Japanese Yen"},{value:"GBP",label:"GBP - British Pound"},{value:"CNY",label:"CNY - Chinese Yuan"},{value:"CHF",label:"CHF - Swiss Franc"},{value:"CAD",label:"CAD - Canadian Dollar"},{value:"AUD",label:"AUD - Australian Dollar"},{value:"HKD",label:"HKD - Hong Kong Dollar"},{value:"SGD",label:"SGD - Singapore Dollar"},{value:"NZD",label:"NZD - New Zealand Dollar"},{value:"SEK",label:"SEK - Swedish Krona"},{value:"NOK",label:"NOK - Norwegian Krone"},{value:"DKK",label:"DKK - Danish Krone"},{value:"KRW",label:"KRW - South Korean Won"},{value:"INR",label:"INR - Indian Rupee"},{value:"RUB",label:"RUB - Russian Ruble"},{value:"BRL",label:"BRL - Brazilian Real"},{value:"MXN",label:"MXN - Mexican Peso"},{value:"TRY",label:"TRY - Turkish Lira"},{value:"ZAR",label:"ZAR - South African Rand"},{value:"SAR",label:"SAR - Saudi Riyal"},{value:"AED",label:"AED - UAE Dirham"},{value:"ARS",label:"ARS - Argentine Peso"},{value:"CLP",label:"CLP - Chilean Peso"},{value:"COP",label:"COP - Colombian Peso"},{value:"THB",label:"THB - Thai Baht"},{value:"IDR",label:"IDR - Indonesian Rupiah"},{value:"MYR",label:"MYR - Malaysian Ringgit"},{value:"PHP",label:"PHP - Philippine Peso"},{value:"PLN",label:"PLN - Polish Zloty"},{value:"NGN",label:"NGN - Nigerian Naira"},{value:"KES",label:"KES - Kenyan Shilling"},{value:"GHS",label:"GHS - Ghanaian Cedi"},{value:"ZMW",label:"ZMW - Zambian Kwacha"},{value:"ZWL",label:"ZWL - Zimbabwean Dollar"},{value:"EGP",label:"EGP - Egyptian Pound"},{value:"MAD",label:"MAD - Moroccan Dirham"},{value:"UAH",label:"UAH - Ukrainian Hryvnia"},{value:"HUF",label:"HUF - Hungarian Forint"},{value:"CZK",label:"CZK - Czech Koruna"},{value:"RON",label:"RON - Romanian Leu"},{value:"PKR",label:"PKR - Pakistani Rupee"},{value:"BDT",label:"BDT - Bangladeshi Taka"},{value:"VND",label:"VND - Vietnamese Dong"},{value:"TWD",label:"TWD - New Taiwan Dollar"},{value:"ILS",label:"ILS - Israeli New Shekel"}],Wr=[{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"}],Xr=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=s.type||"auto",i=c==="auto"?s:bn(s,c),l=m=>{m.stopPropagation()},d=(m,g)=>{a({...i,[m]:g})},[o,u]=y.useState(()=>String(i.decimalPlaces??Bt(c))),[p,x]=y.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),h=m=>{a(bn(s,m))};return y.useEffect(()=>{u(String(i.decimalPlaces??Bt(c)))},[i.decimalPlaces,c]),y.useEffect(()=>{x(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:c,onValueChange:m=>h(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Xr(m)},m))})]})]}),c!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(c)&&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:o,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");u(g),g!==""&&a(is(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const m=Bt(c);u(String(m)),a(is(i,m))},className:"h-8 text-xs"})})]}),c==="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=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(c)&&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=>d("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=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(c)&&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=>d("negativeInParentheses",m)})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");x(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function hs({value:s,onChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(jt,{formatOptions:c,onFormatOptionsChange:i,showTitle:n,title:r})}function Zr(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:c}=t.useAssignFilter();function i(d){const o=c(d,"frame");n({...a,filterId:o})}const l=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(el,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function el({columns:s,onSelect:a}){var d;const[n,r]=Pt.useState(!1),[c,i]=Pt.useState(""),l=Pt.useCallback(o=>[o.label,o.name,o.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[c?((d=s.find(o=>o.id===c))==null?void 0:d.label)||c:"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(o=>e.jsxs(t.CommandItem,{value:l(o),onSelect:()=>{const u=o.id===c?"":o.id;i(u),r(!1),u&&a(o)},children:[o.label||o.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",c===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const tl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],sl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function nl({cardType:s="table"}){var p,x,h,m,g;const a=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=((p=a.config)==null?void 0:p.metricColumns)||[],i=c.some(v=>v.comparisonType&&v.comparisonType!=="none"),l=((x=n==null?void 0:n.tableVisualOptions)==null?void 0:x.metricComparison)||{},d=v=>{r({...n,tableVisualOptions:{...n==null?void 0:n.tableVisualOptions,metricComparison:{...l,...v}}})},o={increase:((h=l.colors)==null?void 0:h.increase)||"green",decrease:((m=l.colors)==null?void 0:m.decrease)||"red",neutral:((g=l.colors)==null?void 0:g.neutral)||"neutral"},u=v=>{r({...n,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(kn,{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:l.calculatedAs||"change_difference",onValueChange:v=>d({calculatedAs:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:tl.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:l.formatOptions||{},onFormatOptionsChange:v=>d({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:l.indicatorStyle||"arrow_badge",onValueChange:v=>d({indicatorStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:sl.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(at,{value:o.increase,onChange:v=>d({colors:{...o,increase:v}}),label:"Increase"}),e.jsx(at,{value:o.decrease,onChange:v=>d({colors:{...o,decrease:v}}),label:"Decrease"}),e.jsx(at,{value:o.neutral,onChange:v=>d({colors:{...o,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:l.lowerIsBetter||!1,onCheckedChange:v=>d({lowerIsBetter:!!v})})]})]})]}),c.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:c.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 C=(((E=a.config)==null?void 0:E.metricColumns)||[]).map(B=>B.id===v.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:C})},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($n,{}),e.jsx(Zr,{})]})]})]}),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 al(){var r;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:a}=t.useEditorStore(c=>c.actions);function n(c){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:c==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,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 rl(){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(al,{})]})]})}const ll=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function ol(){var M,w,D,I,A,j,R,N,L,F;const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var k;return(k=f.card)==null?void 0:k.preferences}),n=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions(),i=y.useMemo(()=>n!==s.type?{...s,type:n}:s,[s,n]),{data:l}=t.useEditorCardQuery(i),[d,o]=y.useState({}),[u,p]=y.useState(null),[x,h]=y.useState(null),m=y.useMemo(()=>{var V,O,P,_,z,H,X;if(!(l!=null&&l.records)||l.records.length===0)return[];const f=n==="stackedBar"||n==="stackedLine",k=n==="bar"||n==="line"||n==="horizontalBar"||n==="bullet"||n==="combo"||n==="area"||n==="stackedArea",T=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||k)&&T){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&K.add(Z.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],Z=Object.keys(K),se=new Set;(O=s==null?void 0:s.config)!=null&&O.groupByColumns&&s.config.groupByColumns.forEach(te=>{se.add(te.label||te.name),se.add(te.alias||te.name)});const me=new Set;return(P=s==null?void 0:s.config)!=null&&P.metricColumns&&s.config.metricColumns.forEach(te=>{const ne=te.alias||te.name;me.add(ne),me.add(`${ne}_count`),me.add(`${ne}_sum`),me.add(`${ne}_avg`),me.add(`${ne}_min`),me.add(`${ne}_max`);const ue=te.entityName||te.qualifiedEntityName;ue&&(me.add(`${ue}_${ne}`),me.add(`${ue}_${ne}_count`))}),Z.filter(te=>!se.has(te)&&!me.has(te))}}if((k||f)&&!T&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(K=>K.alias||K.label||K.name);if((X=(H=s==null?void 0:s.config)==null?void 0:H.groupByColumns)!=null&&X.length){const K=s.config.groupByColumns[0],Z=K.label||K.name,se=new Set;return l.records.forEach(me=>{const je=me[Z];je!=null&&se.add(String(je))}),Array.from(se)}return[]},[l,(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns,(w=s==null?void 0:s.config)==null?void 0:w.pivotByColumns,(D=s==null?void 0:s.config)==null?void 0:D.metricColumns,n]),g=y.useMemo(()=>t.getDefaultChartColors(),[]);y.useEffect(()=>{const f={};m.forEach((k,T)=>{f[k]=t.getColorForValue(k,T,a==null?void 0:a.colorConfig)}),o(f)},[m,a==null?void 0:a.colorConfig,g]);const v=(f,k)=>{const T={...d,[f]:k};o(T);const V={...a||{},colorConfig:{segments:T}};r(V);const O={...s,preferences:V};c(O)},b=(f,k)=>{var z;const T=g[k%g.length],{[f]:V,...O}=((z=a==null?void 0:a.colorConfig)==null?void 0:z.segments)||{},P={...a||{},colorConfig:{segments:O}};r(P);const _={...s,preferences:P};c(_),o(H=>({...H,[f]:T}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((A=(I=s==null?void 0:s.config)==null?void 0:I.groupByColumns)==null?void 0:A.length)||((R=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:R.length):(L=(N=s==null?void 0:s.config)==null?void 0:N.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(n))return null;const B=()=>{const f={...a||{},colorConfig:{segments:{}}};r(f);const k={...s,preferences:f};c(k);const T={};m.forEach((V,O)=>{T[V]=t.getColorForValue(V,O,void 0)}),o(T)},S=Object.keys(((F=a==null?void 0:a.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(Ca,{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:S&&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 T=t.isDefaultColor(d[f],k),V=!T;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:d[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",d[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:ll.map((O,P)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[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:d[f]}),p(null)},children:"Custom color"}),!T&&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(Kn,{color:x.color,onColorChange:f=>{v(x.value,f),h(null)},onClose:()=>h(null)})})]})]})})]})}function He({value:s,onSave:a,placeholder:n="",type:r="text",className:c=""}){const[i,l]=y.useState(s??""),[d,o]=y.useState(!1);y.useEffect(()=>{l(s??"")},[s]);const u=()=>{a(i),o(!1)},p=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${c}`,children:[e.jsx(t.Input,{placeholder:n,type:r,value:d?i:s??"",onChange:x=>{l(x.target.value),o(!0)},onFocus:()=>o(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&d&&i!==s?u():x.key==="Escape"&&p()},"aria-label":n||"Edit field"}),d&&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:a,type:n,config:r,onChange:c,defaultTitle:i,hidePosition:l}){var g,v,b,C,E,B,S,M,w,D,I,A,j,R;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(N,L)=>{c({...r??{},[N]:L})},u=(N,L)=>{var T,V,O,P;const F=N==="enabled"&&L===!0,f=(T=r==null?void 0:r.name)==null?void 0:T.text,k=F&&!f&&i;c({...r??{},name:{...r==null?void 0:r.name,enabled:N==="enabled"?L:((V=r==null?void 0:r.name)==null?void 0:V.enabled)??!1,text:N==="text"?L:k?i:f,fontSize:N==="fontSize"?L:(O=r==null?void 0:r.name)==null?void 0:O.fontSize,fontWeight:N==="fontWeight"?L:(P=r==null?void 0:r.name)==null?void 0:P.fontWeight}})},p=(N,L)=>{var F,f;c({...r??{},labels:{enabled:N==="enabled"?L:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:N==="rotation"?L:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},x=(N,L)=>{c({...r??{},scale:{...r==null?void 0:r.scale,[N]: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:a})})}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:N=>o("enabled",N),onClick:N=>N.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:N=>u("enabled",N===!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:`${a} title`,value:((b=r==null?void 0:r.name)==null?void 0:b.text)||"",onSave:N=>u("text",N),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(((C=r==null?void 0:r.name)==null?void 0:C.fontSize)||12),onSave:N=>u("fontSize",Number(N)||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:N=>u("fontWeight",N),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"})]})]})]})]})]})]}),!l&&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:N=>o("position",N),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":t.titleCase(N)},N))})]})]}),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:N=>p("enabled",N)})]}),((S=r==null?void 0:r.labels)==null?void 0:S.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(((M=r==null?void 0:r.labels)==null?void 0:M.rotation)||"auto"),onValueChange:N=>p("rotation",N==="auto"?"auto":Number(N)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":`${N}°`},N))})]})]})]}),n==="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:d==="override",onCheckedChange:N=>c({...r,formatMode:N?"override":"inherit"})})]}),d==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:N=>c({...r,formatMode:"override",formatOptions:N}),showTitle:!1})]}),n==="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:((w=r==null?void 0:r.scale)==null?void 0:w.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:N=>x("min",N),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"||((A=r==null?void 0:r.scale)==null?void 0:A.max)===void 0?"":String(r.scale.max),onSave:N=>x("max",N),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:N=>x("stepSize",N),className:""})})]})]})]})]})]})}function ns(s,a,n){var i,l,d;if(s==="x"){const o=(l=(i=a==null?void 0:a.config)==null?void 0:i.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],c=(n==null?void 0:n.datasetOptions)||[];if(s==="y"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return!x||x.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function il(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),{setCardPreferences:n,updateCardInFrame:r}=t.useEditorActions(),c=De.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(c))return null;const i=t.AxisConfigurator.getAxisInfo(c,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,u)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...a||{},[p]:u};n(x);const h={...s,preferences:x};r(h)},d=i.hasY2Axis&&c==="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(c,"x"),a==null?void 0:a.xAxisConfig),onChange:o=>l("x",o),defaultTitle:ns("x",s,a)}),i.hasYAxis&&e.jsx(ss,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"y"),a==null?void 0:a.yAxisConfig),onChange:o=>l("y",o),defaultTitle:ns("y",s,a)}),d&&e.jsx(ss,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:ns("y2",s,a),hidePosition:!0})]})})]})}function cl(){const s=t.useEditorStore(x=>x.card),a=De.useEffectiveEditorCardType(),n=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(a))return null;const c=t.getDefaultLegendConfig(a),i=(c==null?void 0:c.display)??!0,l=(c==null?void 0:c.position)??"top",d=(c==null?void 0:c.align)??"center",o=(x,h)=>{const m={...n,[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(ba,{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:(n==null?void 0:n.display)??i,onCheckedChange:x=>o("display",x)})]}),((n==null?void 0:n.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:(n==null?void 0:n.position)||l,onValueChange:x=>o("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:(n==null?void 0:n.align)||d,onValueChange:x=>o("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 dl(){var L,F,f,k,T,V,O;const s=t.useEditorStore(P=>P.card),a=De.useEffectiveEditorCardType(),n=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:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(a))return null;const l=a==="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,d=l!=null?l==="horizontal":((f=r==null?void 0:r.chartOptions)==null?void 0:f.indexAxis)==="y",o=a==="stackedBar"||a==="stackedLine",u=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",p=a==="bubble"||a==="scatter",x=(T=(k=r==null?void 0:r.chartOptions)==null?void 0:k.plugins)==null?void 0:T.datalabels,h=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),m=t.getDefaultDataLabelsConfig(a,s.preferences),g=n??m,v=(m==null?void 0:m.enabled)??h??!1,b=(n==null?void 0:n.enabled)!==void 0?n.enabled:v,C=(P,_)=>{const X={...m??{},...n??{},[P]:_};P==="enabled"&&(X.display=_,_&&p&&!X.position&&(X.position="bottom")),P==="position"&&p&&(X.position="bottom"),P==="formatMode"&&_==="inherit"&&(X.format=void 0,X.formatOptions=void 0);const K={...s.preferences||{},dataLabelsConfig:X};c(K);const Z={...s,preferences:K};i(Z)},E=(P,_)=>{const z=n??{},X={...m??{},...z,font:{...z.font||{},[P]:_}},K={...s.preferences||{},dataLabelsConfig:X};c(K);const Z={...s,preferences:K};i(Z)},B=()=>{const P=a;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":d?"right":"top"},S=a!=="treemap"&&a!=="heatmap",M=a!=="treemap",w=B();let D=[];if(S)if(p)D=["bottom"];else if(o||u)D=["center"];else{const P=d?["center","left","right"]:["center","top","bottom"];D=["auto",...a==="bullet"?P:P.filter(z=>z!==w),"custom"]}const I=()=>t.titleCase(w),A=["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"),N=(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(Ma,{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=>C("enabled",P)})]}),b&&e.jsxs(e.Fragment,{children:[S&&!o&&!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=>C("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))})]})]}),o&&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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:P=>C("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=>C("anchor",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.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=>C("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=>C("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:N,onCheckedChange:P=>{const _=n??{},H={...m??{},..._,formatMode:"override",format:P?"none":void 0,formatOptions:P?void 0:_.formatOptions},X={...s.preferences||{},dataLabelsConfig:H};c(X),i({...s,preferences:X})}})]}),!N&&e.jsx(jt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:P=>{const H={...m??{},...n??{},formatMode:"override",format:P.type&&P.type!=="auto"?P.type:void 0,formatOptions:P},X={...s.preferences||{},dataLabelsConfig:H};c(X),i({...s,preferences:X})},showTitle:!1})]})]}),M&&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"&&C("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=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const vn={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%
|
|
183
|
-
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 ul(){var h,m,g,v,b,C,E,B,S,M;const s=t.useEditorStore(w=>w.card),{setCardPreferences:a}=t.useEditorActions(),n=De.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],c=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&c.length===0,l=r.some(w=>w.comparisonType&&w.comparisonType!=="none");if(!(n==="kpi"&&(i||l)))return null;const o=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},u=w=>{var I;const D={...s.preferences,kpiVisualOptions:{...(I=s.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...o,...w}}};a(D)},p=l||o.enabled,x=r.some(w=>w.comparisonType==="previous_period"||w.comparisonType==="same_period_last_year"||w.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(kn,{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:o.enabled||!1,onCheckedChange:w=>u({enabled:w,...w&&!o.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 w=o.calculationType||"difference",D=vn[w];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:o.calculationType||"difference",onValueChange:w=>u({calculationType:w}),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(vn).map(([w,D])=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:D.label},w))})]})]}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:w=>u({formatOptions:w}),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:o.position||"right",onValueChange:w=>u({position:w}),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:o.showArrow!==!1,onCheckedChange:w=>u({showArrow:w})}),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:o.showColor!==!1,onCheckedChange:w=>u({showColor:w})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(at,{value:((b=o.colorConfig)==null?void 0:b.increase)||"green",onChange:w=>u({colorConfig:{...o.colorConfig,increase:w}}),label:"Primary > Secondary"}),e.jsx(at,{value:((C=o.colorConfig)==null?void 0:C.decrease)||"red",onChange:w=>u({colorConfig:{...o.colorConfig,decrease:w}}),label:"Primary < Secondary"}),e.jsx(at,{value:((E=o.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:w=>u({colorConfig:{...o.colorConfig,noChange:w}}),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:o.conditionalLabel||!1,onCheckedChange:w=>u({conditionalLabel:w})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(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=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,increase:w.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:((S=o.conditionalLabels)==null?void 0:S.decrease)??"Decrease",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,decrease:w.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:((M=o.conditionalLabels)==null?void 0:M.noChange)??"No change",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,noChange:w.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:o.labelName??"",onChange:w=>u({labelName:w.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ml(){var i;const s=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),a=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:n}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",c=l=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};n(d)};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:l=>c(l??"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 xl=Object.keys(t.HEATMAP_PRESET_PALETTES);function hl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",c=(a==null?void 0:a.heatmapConfig)||{},i=c.colorPalette??"green",l=c.legendPosition??"bottom",d=y.useMemo(()=>c.colorRange&&c.colorRange[0]&&c.colorRange[1]?[c.colorRange[0],c.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[c.colorRange]),o=h=>{const m={...c,...h};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:m})},u=h=>{o({colorPalette:h,colorRange:h==="custom"?c.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(h,m)=>{const g=[...d];g[h]=m,o({colorPalette:"custom",colorRange:g})},x=h=>{o({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:[xl.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(at,{value:d[0],onChange:h=>p(0,h),label:"Start color"}),e.jsx(at,{value:d[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:l,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 yn=["poor","satisfactory","good"];function Nn(s){if(!s)return;const a={...s};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function pl(){var L,F;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:c}=t.useEditorActions(),i=y.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=y.useState(i.showRanges??!1),[p,x]=y.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[m,g]=y.useState(h);y.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),y.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);y.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const b=y.useMemo(()=>{var f,k;return((k=(f=a==null?void 0:a.config)==null?void 0:f.metricColumns)==null?void 0:k.map(T=>{const V=T.label||T.name||T.alias||"";return{value:V,label:V}}))||[]},[(L=a==null?void 0:a.config)==null?void 0:L.metricColumns]);y.useEffect(()=>{var z,H;if(!s||b.length===0)return;const f={};let k=!1;const T=(z=b[1])==null?void 0:z.value;!i.targetMetricKey&&T&&(f.targetMetricKey=T,k=!0);const V=(H=b[2])==null?void 0:H.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(f.comparativeMetricKey=V,k=!0);const O=b.slice(3),P={...i.rangeKeys||{}};let _=!1;if(yn.forEach((X,K)=>{!P[X]&&O[K]&&(P[X]=O[K].value,_=!0)}),_&&(f.rangeKeys=P,k=!0,i.showRanges===void 0&&(f.showRanges=!0)),k){const X=Nn({...i,...f});r({...s,bulletConfig:X})}},[b,i,s,r]);const C=f=>{const k=Nn({...i,...f});r({...s,bulletConfig:k})},E=(f,k)=>{const T={...i.rangeKeys||{},[f]:k.trim()};k.trim()||delete T[f],C({rangeKeys:Object.keys(T).length>0?T:void 0})},B=(f,k)=>{const T=k===""?void 0:Number(k),V={...i.ranges||{}};T===void 0||Number.isNaN(T)?delete V[f]:V[f]=T,C({ranges:Object.keys(V).length?V:void 0})},S=f=>{if(f===""){C({targetValue:void 0});return}const k=Number(f);C({targetValue:Number.isNaN(k)?void 0:k})},M=(f,k)=>{const T=k.trim(),V={...i.rangeLabels||{}};T?V[f]=T:delete V[f],C({rangeLabels:Object.keys(V).length>0?V:void 0})},w=f=>{u(f),C({showRanges:f})},D=f=>{x(f),C({rangesArePercentages:f})},I=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),A=f=>{C({orientation:f}),c(f==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(f=>({value:f.value,label:f.label}))],R=j,N=f=>{if(g(f),!f){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){C({disableAutoComparative:!1});return}if(i.comparativeMetricKey)C({disableAutoComparative:!1});else{const k=b.find(T=>T.value!==i.targetMetricKey);C({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=>A(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"})]})]})]}),d&&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=>C({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"}),d?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>C({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=>N(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:S,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:o,onCheckedChange:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,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"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:yn.map(f=>{var k,T,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:_=>M(f,_),className:"h-8 text-xs"})]}),d?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:((T=i.rangeKeys)==null?void 0:T[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 Cn(s){if(!s)return;const a={...s};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function fl(){var M,w,D,I,A,j,R,N,L,F,f,k;const s=t.useEditorStore(T=>T.card.preferences),a=t.useEditorStore(T=>T.card),n=De.useEffectiveEditorCardType(),r=t.useEditorStore(T=>T.isDevMode),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions(),l=n==="bubble",d=n==="scatter",o=y.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,x=y.useMemo(()=>{var T,V;return((V=(T=a==null?void 0:a.config)==null?void 0:T.metricColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(M=a==null?void 0:a.config)==null?void 0:M.metricColumns]),h=y.useMemo(()=>{var T,V;return((V=(T=a==null?void 0:a.config)==null?void 0:T.groupByColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),m=y.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&h.length>=2,[o.enableGrouping,r,h.length]),[g,v]=y.useState(m);y.useEffect(()=>{v(m)},[m]);const b=T=>{const V={...s||{},bubbleScatterConfig:T};c(V),a&&i({...a,preferences:V})},C=T=>{c(T),a&&i({...a,preferences:T})};y.useEffect(()=>{if(!s||x.length===0)return;const T={};let V=!1;if(!o.xMetricKey&&x[0]&&(T.xMetricKey=x[0].value,V=!0),!o.yMetricKey&&x[1]&&(T.yMetricKey=x[1].value,V=!0),l&&!o.radiusMetricKey&&x[2]&&(T.radiusMetricKey=x[2].value,V=!0),!o.labelKey&&h[0]&&(T.labelKey=h[0].value,V=!0),m&&!o.groupKey&&h[1]&&(T.groupKey=h[1].value,T.enableGrouping=!0,V=!0),V){const O=Cn({...o,...T});b(O)}},[x,h,o,s,c,l,m]);const E=T=>{const V=Cn({...o,...T});b(V)},B=T=>{v(T),E({enableGrouping:T,groupKey:T?o.groupKey:void 0})};if(!l&&!d)return null;const S=l?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(S,{className:"h-4 w-4"}),e.jsxs("span",{children:[l?"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:o.labelKey||"",onValueChange:T=>E({labelKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:T=>E({labelKey:T})})]}),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:o.groupKey||"",onValueChange:T=>E({groupKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:T=>E({groupKey:T})})]})]}),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:o.xMetricKey||"",onValueChange:T=>E({xMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:T=>E({xMetricKey:T})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:T=>E({yMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:T=>E({yMetricKey:T})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:T=>E({radiusMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:T=>E({radiusMetricKey:T})})]})]}),l&&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:o.radiusScale||"sqrt",onValueChange:T=>E({radiusScale:T}),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"})]})]})]}),o.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=o.minRadius)==null?void 0:D.toString())||"",onCommit:T=>E({minRadius:T?Number(T):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=o.maxRadius)==null?void 0:I.toString())||"",onCommit:T=>E({maxRadius:T?Number(T):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(t.Slider,{value:[o.fixedRadius||10],onValueChange:([T])=>E({fixedRadius:T}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&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: ",o.fixedRadius||5]}),e.jsx(t.Slider,{value:[o.fixedRadius||5],onValueChange:([T])=>E({fixedRadius:T}),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=(A=s==null?void 0:s.xAxisConfig)==null?void 0:A.name)==null?void 0:j.enabled)??!1,onCheckedChange:T=>{var P,_,z,H;const V=o.xMetricKey||"X Axis",O=o.yMetricKey||"Y Axis";C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:T,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:T,text:((H=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:H.text)||O}}})}})]}),((N=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:N.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:o.xMetricKey||"X Axis",value:((F=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:F.text)||"",onCommit:T=>{var V;C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.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:o.yMetricKey||"Y Axis",value:((k=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:k.text)||"",onCommit:T=>{var V;C({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const gl=[{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 jl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",c=(a==null?void 0:a.funnelConfig)||{},i=c.percentMode??"percentOfTotal",l=c.shrinkFraction??1,d=c.labelThreshold??0,o=h=>{const m={...c,...h};n({...a||{},funnelConfig:m})},u=h=>{o({percentMode:h})},p=h=>{o({shrinkFraction:h[0]})},x=h=>{o({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:gl.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:[l],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(l*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:[d],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:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function qt(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useEditorCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let c=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}const bl=[{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"}],vl=[{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)"}],yl=["center","start","end"],Nl=["center","start","end","top","bottom"];function $t({config:s,onChange:a,isHorizontal:n=!1,showAutoFormat:r=!0,positionOptions:c,showAppearance:i=!0}){var g,v,b,C,E,B;const l=c??(n?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(S,M)=>{const w={...s,[S]:M};a(w)},u=(S,M)=>{const w={...s,font:{...(s==null?void 0:s.font)||{},[S]:M}};a(w)},p=(S,M)=>{const w={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:M}};a(w)},x=()=>n?"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:S=>o("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?x():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),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:S=>o("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]}),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:S=>o("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Nl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]})]}),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:S=>o("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&r?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["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:S=>p("decimalPlaces",Number(S)),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:S=>p("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:S=>p("useSuffix",S)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((C=h.formatOptions)==null?void 0:C.locale)||"en-US",onValueChange:S=>p("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:S=>u("size",Number(S)),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:S=>u("weight",S),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:S=>{S==="auto"&&o("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:S=>o("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Cl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],Sl=[0,1,2,3,4,5,6,8,10],wl=[{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 │"}],Tl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function El(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(Il,{})})]})}function Il(){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((a,n)=>e.jsx(Dl,{metricKey:a,idx:n},a))})}function Dl({metricKey:s,idx:a}){var C;const[n,r]=y.useState(!1),c=t.useEditorStore(E=>{var B;return(B=E.card)==null?void 0:B.preferences}),i=t.useEditorStore(E=>{var B,S;return(S=(B=E.card)==null?void 0:B.preferences)==null?void 0:S.datasetOptions}),l=i==null?void 0:i.find(E=>E.idx===a),{setCardPreferences:d}=t.useEditorStore(E=>E.actions),o=(l==null?void 0:l.type)||"bar",u=(l==null?void 0:l.yAxisId)||"y",p=((C=l==null?void 0:l.dataLabels)==null?void 0:C.enabled)??!1,x=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const B={idx:a,type:o,yAxisId:u,dataLabels:l==null?void 0:l.dataLabels,...E};if(!l)d({...c||{},datasetOptions:[...i||[],B]});else{const S=i==null?void 0:i.map(M=>M.idx===a?{...M,...B}:M);d({...c||{},datasetOptions:S})}}function m(E){h({type:E})}function g(E){h({yAxisId:E})}function v(E){h({dataLabels:{...l==null?void 0:l.dataLabels,enabled:E}})}function b(E){h({dataLabels:E})}return e.jsx(t.Collapsible,{open:n,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",n&&"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"}),o==="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:Cl.map(({type:E,icon:B,label:S})=>{const M=o===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",M?"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:S})]},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)"})]})]})]})]}),o==="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:(l==null?void 0:l.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:Tl.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((l==null?void 0:l.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:Sl.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:(l==null?void 0:l.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:wl.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:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const as=[{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"}],kl=[0,1,2,3,4,5,6,8,10],Al=[{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 │"}],Ml=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Ll(s){return s==null?"origin":s===!1?"false":s}function Fl(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(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((a,n)=>e.jsx(Ol,{metricKey:a,idx:n},a))})}function Ol({metricKey:s,idx:a}){var v;const[n,r]=y.useState(!1),c=t.useEditorStore(b=>{var C;return(C=b.card)==null?void 0:C.preferences}),i=t.useEditorStore(b=>{var C,E;return(E=(C=b.card)==null?void 0:C.preferences)==null?void 0:E.datasetOptions}),l=i==null?void 0:i.find(b=>b.idx===a),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),o=Ll(l==null?void 0:l.fill),u=((v=l==null?void 0:l.dataLabels)==null?void 0:v.enabled)??!1,p=as.find(b=>b.value===o)||as[0];function x(b){const C={idx:a,fill:o,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)d({...c||{},datasetOptions:[...i||[],C]});else{const E=i==null?void 0:i.map(B=>B.idx===a?{...B,...C}:B);d({...c||{},datasetOptions:E})}}function h(b){x({fill:b==="false"?!1:b})}function m(b){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function g(b){x({dataLabels:b})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:o,onValueChange:b=>h(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:as.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:(l==null?void 0:l.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:Ml.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},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((l==null?void 0:l.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:kl.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:(l==null?void 0:l.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:Al.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},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:l==null?void 0:l.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Pl=[0,1,2,3,4,5,6,8,10],Bl=[{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 Vl(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(zl,{})})]})}function zl(){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((a,n)=>e.jsx(_l,{metricKey:a,idx:n},a))})}function _l({metricKey:s,idx:a}){var b;const[n,r]=y.useState(!1),c=t.useEditorStore(C=>{var E;return(E=C.card)==null?void 0:E.preferences}),i=t.useEditorStore(C=>{var E,B;return(B=(E=C.card)==null?void 0:E.preferences)==null?void 0:B.datasetOptions}),l=i==null?void 0:i.find(C=>C.idx===a),{setCardPreferences:d}=t.useEditorStore(C=>C.actions),o=(l==null?void 0:l.lineStyle)||"solid",u=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",x=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,h=rs.find(C=>C.value===o)||rs[0];function m(C){const E={idx:a,lineStyle:o,pointRadius:u,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...c||{},datasetOptions:[...i||[],E]});else{const B=i==null?void 0:i.map(S=>S.idx===a?{...S,...E}:S);d({...c||{},datasetOptions:B})}}function g(C){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function v(C){m({dataLabels:C})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:o,onValueChange:C=>m({lineStyle:C}),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:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},C))})]})]}),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:C=>m({pointRadius:Number(C)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Pl.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 text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:C=>m({pointStyle:C}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.map(({value:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},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 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:l==null?void 0:l.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ql=[0,2,4,6,8,10,12,16,20];function $l(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(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((a,n)=>e.jsx(Gl,{metricKey:a,idx:n},a))})}function Gl({metricKey:s,idx:a}){var g;const[n,r]=y.useState(!1),c=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}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card)==null?void 0:b.preferences)==null?void 0:C.datasetOptions}),d=l==null?void 0:l.find(v=>v.idx===a),{setCardPreferences:o}=t.useEditorStore(v=>v.actions),u=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const b={idx:a,borderRadius:u,dataLabels:d==null?void 0:d.dataLabels,...v};if(!d)o({...i||{},datasetOptions:[...l||[],b]});else{const C=l==null?void 0:l.map(E=>E.idx===a?{...E,...b}:E);o({...i||{},datasetOptions:C})}}function h(v){x({dataLabels:{...d==null?void 0:d.dataLabels,enabled:v}})}function m(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:ql.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:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:c==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ul=[0,1,2,3,4,5,6,8,10],Hl=[{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 │"}],Ql=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Jl(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=De.useEffectiveEditorCardType(),r=a==null?void 0:a.lineStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(n))return null;const l=(d,o)=>{const u={...a||{},lineStyleConfig:{...r,[d]:o}};c(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(Da,{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:d=>l("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),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:d=>l("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Yl=[0,2,4,6,8,10,12,16,20],Wl=[{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%"}],Xl=[{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 Zl(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=De.useEffectiveEditorCardType(),r=a==null?void 0:a.barStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(n))return null;const l=(d,o)=>{const u={...a||{},barStyleConfig:{...r,[d]:o}};c(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:d=>l("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),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:d=>l("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function eo(){const s=t.useEditorStore(n=>{var r,c;return(c=(r=n==null?void 0:n.card)==null?void 0:r.preferences)==null?void 0:c.sortChart}),{setSortChart:a}=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(nt,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:n=>{a(n)}})]})})]})}const to=["kpi"],Sn={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 so(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const a=t.getDataType(s.dataType);return["date","string","boolean"].includes(a)}function no(s){return{...s,role:"groupby"}}function ao(){var E,B;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),n=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),c=((E=s.config)==null?void 0:E.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},l=i.breakdownDimensions||[],d=to.includes(n),o=c.length>0,u=i.enabled===!0,p=d&&o,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,n),h=Sn[x]||Sn.none,m=Array.from(new Map(r.filter(so).map(S=>[lt(S),no(S)])).values()),g=new Set(m.map(S=>lt(S))),v=new Set(l.map(S=>lt(S)).filter(S=>S&&g.has(S)));if(!d)return null;const b=S=>{a(s.id,{summary:{...i,...S}})},C=(S,M)=>{const w=lt(S),D=m.filter(A=>v.has(lt(A))),I=M?v.has(w)?D:[...D,S].slice(0,ls):D.filter(A=>lt(A)!==w);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"}),!o&&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:S=>{if(!S){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:S=>b({showOnCard:S})})]}),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:S=>b({includeInDashboardSummary: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 font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.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(S=>{const M=lt(S),w=v.has(M),D=v.size>=ls,I=!u||!w&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${M}`,checked:w,disabled:I,onCheckedChange:A=>C(S,A===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${M}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},M)})})]}),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:S=>b({anomalyEnabled:S})})]})]})]})}const ro=[];function lo(){var c;const s=t.useEditorStore(i=>i.card),a=((c=s==null?void 0:s.config)==null?void 0:c.metricColumns)??ro,{updateMetricColumn:n,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||a.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(ua.Braces,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:a.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:l=>{var d;n(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const oo=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function io(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions();if(!s||!oo.has(n||""))return null;const i=a==null?void 0:a.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",d=o=>{const u={...a||{},tooltipConfig:{...i||{},...o}};r(u),c({...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:l==="override",onCheckedChange:o=>d({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>d({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function Gn({mode:s}){const a=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(El,{}),(a==="area"||a==="stackedArea")&&e.jsx(Fl,{}),a==="line"&&e.jsx(Vl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx($l,{}),e.jsx(Jl,{}),e.jsx(Zl,{}),e.jsx(ml,{}),s==="config"&&e.jsx(ul,{}),s==="config"&&e.jsx(ao,{}),e.jsx(hl,{}),a==="bullet"&&e.jsx(pl,{}),a==="funnel"&&e.jsx(jl,{}),(a==="bubble"||a==="scatter")&&e.jsx(fl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(eo,{}),e.jsx(lo,{}),e.jsx(ol,{}),e.jsx(il,{}),e.jsx(cl,{}),e.jsx(dl,{}),e.jsx(io,{})]})}function co(){const s=t.useEditorStore(n=>n.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:a}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Gn,{mode:"dev"})})]}):null}function uo(){const s=t.useEditorStore(c=>c.card),a=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(a){case"kpi":return e.jsx(_r,{});case"table":return e.jsx(nl,{});case"map":return e.jsx(Gr,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(_n,{})});case"text":return e.jsx(rl,{});default:return e.jsx(co,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function mo(){const s=y.useRef(null),a=y.useRef(null),n=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),c=t.useEditorStore(x=>x.showAIDialog),[i,l]=y.useState(!1),d=n&&!c,o=d&&(!r||i),u=r&&d,p=()=>l(x=>!x);return y.useEffect(()=>{var x,h,m,g;c?((x=s.current)==null||x.resize(0),(h=a.current)==null||h.resize(0)):((m=s.current)==null||m.resize(25),(g=a.current)==null||g.resize(25))},[c]),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(ar,{})}),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:o?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(uo,{})})}),!c&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(hn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(hn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function xo(s){var Ee;t.useAIInteractionStore($=>$.currentAIContext);const[a,n]=y.useState(""),[r,c]=y.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),d=t.useEditorStore($=>$.card.id),o=t.useEditorStore($=>{var le;return(le=$==null?void 0:$.card)==null?void 0:le.sql}),u=t.useEditorStore($=>$.isDevMode),p=t.useEditorStore($=>{var le;return(le=$==null?void 0:$.card)==null?void 0:le.python}),{setCardPython:x,setCardSql:h,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore($=>$.currentAssitantScope)||[],C=t.useEditorStore($=>$.userInputForAI),E=t.useEditorStore($=>$.triggerAIRun),B=t.useEditorStore($=>$.card),S=t.useEditorStore($=>$.selectedDatabaseName),M=t.useEditorStore($=>$.selectedTableName),w=t.useEditorStore($=>$.selectedConnectionId),D=t.useEditorStore($=>$.selectedSchemaName),I=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:A,refetch:j,data:R}=t.useEditorCardQuery(B),{setTriggerAIRun:N,setCurrentAssitantScope:L,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:k,selectedDatamodelId:T}=t.useEditorAside(),V=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,O=y.useRef(t.createAssistantConversationId()),P=y.useRef(null),_=y.useRef(d),z=y.useRef(!1),H=()=>{const $=P.current;$&&(P.current=null,O.current=t.createAssistantConversationId(),$==="clear"&&K([]))},{messages:X,setMessages:K,regenerate:Z,error:se,sendMessage:me,status:je,addToolResult:te,stop:ne,clearError:ue}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:O.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var le;if(z.current=!1,$.name==="AbortError"||(le=$.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),H();return}console.error("[Editor Assistant] Stream error:",$),H()},onToolCall:G,onFinish({isAbort:$,isDisconnect:le,isError:ge}){z.current=!1,n(""),console.log($?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":ge?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),H()}}),be=y.useCallback($=>{z.current=!0;try{const le=me($);return t.isPromiseLike(le)?le.catch(ge=>{throw z.current=!1,ge}):le}catch(le){throw z.current=!1,le}},[me]),fe=y.useCallback(()=>{z.current=!0;try{const $=Z();return t.isPromiseLike($)?$.catch(le=>{throw z.current=!1,le}):$}catch($){throw z.current=!1,$}},[Z]),ve=$=>{let le=!1;K(ge=>{const ee=typeof $=="function"?$(ge):$;if(ee.length===0){if(z.current)return P.current="clear",le=!0,ge;P.current=null,O.current=t.createAssistantConversationId()}return ee}),le&&ne()};y.useEffect(()=>{if(_.current!==d){if(_.current=d,z.current){P.current!=="clear"&&(P.current="rotate"),ne();return}P.current=null,O.current=t.createAssistantConversationId()}},[d,ne]),y.useEffect(()=>{E&&C&&(be({role:"user",parts:[{type:"text",text:C}]}),N(!1))},[E,C,be,N]);async function G({toolCall:$}){var le,ge,ee,Q,re,ce,Se,ye,Fe,Be,We,Je,Ye,ae,Ie,Pe;if(["createChartFromSql","createForecast"].includes($.toolName)){const Ne=((le=$.input)==null?void 0:le.sql)??((ge=$.args)==null?void 0:ge.sql),Ge=((ee=$.input)==null?void 0:ee.python)??((Q=$.args)==null?void 0:Q.python),we=((re=$.input)==null?void 0:re.chartType)??((ce=$.args)==null?void 0:ce.chartType);g(we),h(Ne),x(Ge),m(!0),te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!o){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:o,python:p||""}})}else if($.toolName==="generateQueryConfig"){n("Generating query config...");const Ne=((Se=$.input)==null?void 0:Se.chartType)??((ye=$.args)==null?void 0:ye.chartType),Ge=((Fe=$.input)==null?void 0:Fe.queryConfig)??((Be=$.args)==null?void 0:Be.queryConfig);((We=$.input)==null?void 0:We.cardConfig)??((Je=$.args)==null||Je.cardConfig),g(Ne),F(Ge),h(void 0),x(void 0);const we=await j();if((Ye=we==null?void 0:we.data)!=null&&Ye.error){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:Ge,message:(ae=we==null?void 0:we.data)==null?void 0:ae.error.message}});return}if((Ie=we==null?void 0:we.data)!=null&&Ie.records){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Pe=we==null?void 0:we.data)==null?void 0:Pe.records}})}else n("Analyzing...")}function pe($){const le=t.removeFromScopeArray(b,$);Ce(le)}function Ce($){const le=t.sanitizeAIScope($);L(le),K(ge=>[...ge,{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 Oe(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelId:T||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:k||""},le=t.dedup([...b,$]);Ce(le)}function Ve(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:k||"",datamodelId:T||""};if(!t.isInAiScopeArray([...I||[],...b],$)||b.length===0){const ge=t.dedup([...I||[],...b,$]).filter(ee=>ee.connectionId===$.connectionId);Ce(ge)}}const Ae=!["ready","error"].includes(je),Te=t.getErrorMessage(se);return{messages:X,setMessages:ve,sendMessage:be,regenerate:fe,isLoading:Ae,handleSetAIScope:Ve,handleAddCurrentTableToScope:Oe,removeFromCurrentSelections:pe,currentAssitantScope:b,setCurrentAssitantScope:L,stop:ne,status:je,toolStatus:a,llmUsage:r,onFinish:s,errorMessage:Te,clearError:ue}}const ho=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function wn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:n}){const r=y.useRef(null),c=y.useRef(!1),[i,l]=y.useState(!1),[d,o]=y.useState(t.isDevEnv),[u,p]=y.useState(!1),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:C,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:S}=t.useFileActions(),M=t.useFileAttachments("editor"),{selectedEntities:w}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),A=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),N=t.useEditorStore(ae=>ae.showAIDialog),L=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:k}=t.useEditorActions(),{assistantProfile:T}=t.useAssistantProfile(),{messages:V,setMessages:O,sendMessage:P,isLoading:_,stop:z,status:H,llmUsage:X,errorMessage:K,clearError:Z}=xo(),[se,me]=y.useState(""),je=ae=>{me(ae.target.value)},te=ae=>{ae.preventDefault();const Ie=se.trim();if(!Ie&&M.length===0)return;const Pe=[];Ie&&Pe.push({type:"text",text:Ie}),M.forEach(Ne=>{Ne.data&&Pe.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),P({role:"user",parts:Pe}),me(""),S("editor"),Ae({force:!0})},{visibleMessages:ne,hasMoreMessages:ue,totalMessageCount:be,loadMoreMessages:fe,resetMessageWindow:ve}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:G,contentRef:pe,isAtBottom:Ce,hasNewMessages:Oe,newMessageCount:Ve,scrollToBottom:Ae,handleScroll:Te,resetNewMessageCount:Ee}=t.useAutoScroll(ne,{threshold:40,behavior:"smooth",isStreaming:_});y.useEffect(()=>{var ae;N&&!c.current&&((ae=r.current)==null||ae.focus()),c.current=N},[N]),y.useEffect(()=>{N&&(E(!1),C({selectedEntities:A||[]}))},[D,A,C,E,N]),t.useAutoSubmitQueue({assistantType:"editor",status:H,isLoading:_,sendMessage:P});const{hasActiveTools:$,activeToolText:le}=t.useActiveToolStatus(V),ge=y.useCallback(ae=>{a==null||a(ae),s===void 0&&g(ae)},[s,a]);y.useEffect(()=>{if(!v)return;function ae(Ie){Ie.key==="Escape"&&ge(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[v,ge]);const ee=y.useCallback(ae=>{P({role:"user",parts:[{type:"text",text:ae}]}),Ae({force:!0})},[P,Ae]),Q=y.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]),re=y.useCallback(()=>{ge(!v)},[v,ge]);function ce(ae,Ie){Ie==="sql"?(j(ae),R(!0)):Ie==="python"&&(f(ae),R(!0))}function Se(){b.selectedEntities.length===0&&C({selectedEntities:w})}function ye(ae){Se();const Ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};P(Ie)}function Fe(ae){Se(),P({role:"user",parts:[{type:"text",text:ae}]})}function Be(){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:l,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function We(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Je=(se==null?void 0:se.length)===0&&(V==null?void 0:V.filter(ae=>ae.role==="user").length)===0,Ye=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:[We(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Be(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Q,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:re,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"),Z(),ve()},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:G,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Te,children:e.jsxs("div",{ref:pe,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[ue&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:fe,className:"text-xs",children:["Load ",Math.min(5,be-ne.length)," ","more messages (",be-ne.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:ne,showTools:d,handleRun:ce,showSystemMessage:u,onQuickReply:ee,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:H,errorMessage:K,activeToolText:_&&$?le:void 0})]})}),N&&!Ce&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{Ae({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"}),Oe&&Ve>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:Ve>9?"9+":Ve})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Je&&!T&&e.jsx(t.Placeholders,{onClick:ye,placeholders:ho}),e.jsx("div",{children:Je&&T&&e.jsx(t.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:Fe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:me,stop:z,input:se,handleInputChange:je,handleSubmit:ae=>{Se(),te(ae),Ae({force:!0})},isLoading:_,status:H,assistantType:"editor",onFocus:()=>{}})]}),X&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",X.inputTokens," prompt tokens, ",X.outputTokens," ","completion tokens, ",X.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:w,open:x,onOpenChange:h,dataSource:I||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{E(!0),C({...b,selectedEntities:ae})}})]});return v&&n?da.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:Ye})}),n):Ye}function po(s,a,n){if(!a)return!1;const r=a.qualifiedFieldName,c=a.qualifiedEntityName,i=c&&a.name?`${c}.${a.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,n),u=o.split("."),p=u[u.length-1]||o,x=u.length>1?u.slice(0,-1).join("."):void 0,h=l.qualifiedTableName||x,m=h?`${h}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===a.name:m?m===i:p===a.name})}function fo({aliasTemplate:s,onAliasTemplateChange:a}){var o;const[n,r]=y.useState(s),[c,i]=y.useState(!1),l=(o=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.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:d,value:c?n: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"&&c&&n!==s?(a(n),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),c&&n!==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:()=>{a(n),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 go({valueAliases:s,onValueAliasesChange:a}){const[n,r]=y.useState(null),[c,i]=y.useState(""),[l,d]=y.useState(""),o=()=>{a({...s,"":""})},u=x=>{const h={...s};delete h[x],a(h)},p=x=>{const h={...s};delete h[x],h[c]=l,a(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:n===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:c,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:l,onChange:g=>d(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),d(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),d(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:o,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function jo({idx:s}){var d;const a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=t.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(o=>o.actions.setCardPreferences),c=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(o=>o.idx===s);function l(o,u){(o==="end"||o==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:p}]});else{const x={...i};x.datalabels=p;const h=n==null?void 0:n.map(m=>m.idx===u?x:m);r({...a,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:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(va,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Na,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ya,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})})]})})]})}function ps({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function bo(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function vo({col:s,idx:a,className:n,iconClassName:r,children:c}){const i=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),l=t.useEditorStore(p=>{var x,h;return(h=(x=p.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===a),{setCardPreferences:o}=t.useEditorStore(p=>p.actions);function u(p){if(!d)o({...i,datasetOptions:[...l||[],{idx:a,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...d};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const h=l==null?void 0:l.map(m=>m.idx===a?x:m);o({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[c||e.jsx(ps,{className:"max-w-[100px]",title:s,children:bo(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(jo,{idx:a})]})]})}function yo(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function c(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(p=n==null?void 0:n.chartOptions)==null?void 0:p.plugins,...o}}};r(u)}function i(){var d,o,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=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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 l(){var d,o,u;return e.jsx("div",{children:e.jsxs(t.Select,{value:((u=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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:a?i():l()})}function No({column:s}){const a=t.useEditorStore(o=>o.card.type),n=t.useEditorStore(o=>{var u,p;return(p=(u=o.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],c=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=c?r.indexOf(c):-1;function l(){return e.jsx("div",{className:"pr-1",children:c&&e.jsx(vo,{idx:i,col:c,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){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(yo,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&d()]})}function Co({field:s,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:c}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),l=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,a,n],o=t.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},p={connection_id:l.connectionId,cardConfig:u,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const x=await t.postRequestRegular(`${c.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&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function Un({open:s,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:c,onSave:i}){var B,S;const l=!!c,[d,o]=y.useState(l?"values":"fields"),[u,p]=y.useState(""),[x,h]=y.useState({id:(c==null?void 0:c.id)||t.v4(),field:(c==null?void 0:c.field)||null,selectedValues:c?Array.isArray(c.value)?c.value:[c.value]:[]}),m=n.filter(M=>{var D;return l?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(I=>I.field.id===M.id))&&M.label.toLowerCase().includes(u.toLowerCase())}),g=M=>{h({...x,field:M}),o("values")},v=()=>{if(x.field&&x.selectedValues.length>0){const M={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let w;if(l){const D=((r==null?void 0:r.conditions)||[]).map(I=>I.id===c.id?M:I);w={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,M],groups:[]}}i(w),a(!1)}},b=()=>{if(!l||!c)return;const M=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==c.id);if(M.length>0){const w={...r,conditions:M};i(w)}else i(void 0);a(!1)},C=M=>{h({...x,selectedValues:M})},E=()=>{l&&c?(h({id:c.id,field:c.field,selectedValues:Array.isArray(c.value)?c.value:[c.value]}),o("values")):(h({id:t.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return y.useEffect(()=>{s&&E()},[s,l,c]),e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:l?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(S=x.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="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(M=>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:[M.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(M.value)?`${M.value.length} values`:String(M.value)})]},M.id))})]}),d==="fields"&&!l?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:M=>p(M.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(M=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(M),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(M.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:M.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[M.entityName,".",M.name]})]})]},M.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&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(So,{field:x.field,selectedValues:x.selectedValues,onValuesChange:C,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?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:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function So({field:s,selectedValues:a,onValuesChange:n,onBack:r}){const[c,i]=y.useState(""),{values:l,isLoading:d,isFetching:o}=Co({field:s,searchQuery:c,limit:500}),u=c?l.filter(h=>String(h.value).toLowerCase().includes(c.toLowerCase())):l,p=h=>{const m=a.includes(h);n(m?a.filter(g=>g!==h):[...a,h])},x=()=>{a.length===u.length&&u.length>0?n([]):n(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:c,onChange:h=>i(h.target.value),className:"pl-10"})]}),d||o?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:a.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:a.includes(h.value),onCheckedChange:()=>p(h.value)}),e.jsx(ps,{className:"text-sm",children:h.label})]},h.id))})]})]})}function wo({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:c,hasPivotColumns:i=!1,cardType:l}){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,en;const{attributes:d,listeners:o,setNodeRef:u,transform:p,transition:x,isDragging:h}=t.useSortable({id:s.id}),m=t.useEditorStore(U=>U.card),g=t.useEditorStore(U=>U.frame),v=t.useDashboardStore(U=>U.isVisualEditing),b=t.useDashboardStore(U=>U.selectedSheetId),C=t.useDashboardStore(U=>U.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:B,isLoading:S}=t.useFilterableFields(),{userContext:M}=t.useCurrentUserInfo(),w=(M==null?void 0:M.type)==="organization",{updateLabel:D,handleAggregationChange:I,handleDateFormatChange:A,handleGranularityChange:j,handleAliasTemplateChange:R,handleValueAliasesChange:N,handleMetricFormatChange:L,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:k,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:V,handleMetricWindowPartitionToggle:O,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:H,handleMetricPercentOfTotalOutputChange:X,handleKpiShowTrendlineChange:K,handleKpiTrendlineWindowChange:Z,handleKpiTrendlineGranularityChange:se,handleMetricTargetValueChange:me}=t.useFieldManagement(m),[je,te]=y.useState(!1),[ne,ue]=y.useState(()=>{var U;return!!((U=s.parameters)!=null&&U.windowTransform)}),[be,fe]=y.useState(!1),[ve,G]=y.useState(!1),[pe,Ce]=y.useState(null),Oe=y.useMemo(()=>{const U=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Y=U(s.id),de=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 ke=U(oe.id);return!!(Y&&ke&&Y===ke)});return{dataType:(de==null?void 0:de.dataType)||s.dataType,resolvedFromScopedField:!!de}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),Ve=t.getGranularityOptionsForFieldType(Oe.dataType),[Ae,Te]=y.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,$]=y.useState(s.customFormat||""),[le,ge]=y.useState(!!s.customFormat),ee=y.useRef(null),[Q,re]=y.useState(s.aliasTemplate||""),[ce,Se]=y.useState(s.valueAliases||{}),[ye,Fe]=y.useState((Ns=s.parameters)==null?void 0:Ns.filters),Be=U=>{U==="custom"?ge(!0):(ge(!1),Te(U),(a==="groupBy"||mt)&&A(n,U,"",a))},We=U=>{$(U),(a==="groupBy"||mt)&&A(n,"custom",U,a)},Je=U=>{var oe;const de=(oe=t.getDateFormatOptionsForGranularity(U)[0])==null?void 0:oe.value;de&&!le&&(Te(de),a==="groupBy"&&A(n,de,"",a)),a==="groupBy"&&j(n,U)},Ye=U=>{re(U),a==="metrics"&&R(n,U)},ae=U=>{Se(U),a==="metrics"&&N(n,U)},Ie=U=>{D(a,n,U)},Pe=t.getExpressionFieldKind(s),Ne=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),we=s.role==="metric"&&Ge,bt=Ge&&(Pe==="user_calculated"||Pe==="inline_expression"&&s.fieldScope!=="domain"),Xe=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(U=>t.matchesCalculatedField(U,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Xe),Ue=Pe==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=Ue?"domain":Tt?"dashboard":"card",Ze=Ue?Et||s:Tt&&Xe?Xe:s,It=U=>{var Y;if(Fe(U),a==="metrics"){const de={...s,parameters:{...s.parameters,filters:U}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}fe(!1)},vt=()=>{F(a,n)},Kt={transform:t.CSS.Transform.toString(p),transition:x},Dt=t.getDataType(Oe.dataType||s.dataType),dt=Dt==="date",ut=l==="kpi",mt=a==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,et=t.useDashboardStore(U=>{var Y;return(Y=U.dashboard)==null?void 0:Y.filters}),Gt=t.useDashboardStore(U=>U.filterValues),tt=s.granularity||"day",kt=Ve.includes(tt)?tt:"day",yt=a==="groupBy"&&!Ve.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=le?"custom":ht.some(U=>U.value===Ae)?Ae:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";y.useEffect(()=>{var de;if(S||!yt){ee.current=null;return}const U=`${s.id}:${tt}:${Oe.dataType||s.dataType||""}:${n}`;if(ee.current===U)return;ee.current=U;const Y="day";if(j(n,Y),!le){const oe=(de=t.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:de.value;oe&&(Te(oe),A(n,oe,"",a))}},[s.dataType,s.id,A,j,yt,n,le,S,tt,Oe.dataType,a]);const Ht=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Ke=y.useMemo(()=>$e==null?void 0:$e.find(U=>t.getDataType(U.dataType||"")==="date"),[$e]),At=y.useMemo(()=>($e||[]).some(U=>t.getDataType(U.dataType||"")==="date"),[$e]),pt=y.useMemo(()=>{var oe;if(!Ke)return!1;const U=(oe=m.config)==null?void 0:oe.filters;if(!U)return!1;const Y=ke=>{const Le=ke.field;return Le?Ke.id&&Le.id===Ke.id||Ke.qualifiedFieldName&&Le.qualifiedFieldName===Ke.qualifiedFieldName?!0:Le.name===Ke.name:!1},de=ke=>ke.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&Y(_e))?!0:ke.groups.some(_e=>de(_e));return de(U)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=y.useMemo(()=>po(et||[],Ke,Gt),[et,Gt,Ke]),Nt=pt||Mt,q=s,W=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",J=t.isMetricTransformEnabled(q),ie=J?W:null,xe=t.supportsMetricTransformForMetric({cardType:l||"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)||"",Qe=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Me.find(U=>U.id===Re),st=ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta",ze=J&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"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=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),gs=[...($e||[]).filter(U=>U.id&&(!st||U.id!==Re)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(U=>U.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Qn=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Jn=((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",Yn=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Wn=y.useMemo(()=>(xt||[]).some(U=>U.comparisonType==="start_vs_end"),[xt]);y.useEffect(()=>{J&&ue(!0)},[J]);const Xn=a!=="pivotBy"&&a!=="sortBy",Zn=dt&&a==="groupBy"&&(!ut||Wn),ea=!ut&&dt&&(a==="groupBy"||mt),ta=l==="kpi"&&dt&&a==="groupBy",sa=a==="metrics",vs=Ht&&a==="metrics",na=()=>{const U=s,Y=a==="metrics"&&we;return e.jsxs("div",{className:"space-y-1",children:[!Y&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:de=>{de.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}`}),Y&&U.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(U.calculatedFormula),onPointerDown:de=>{de.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(U.calculatedFormula)]})]})},aa=()=>Xn?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,ra=()=>a!=="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:U=>c(U),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=()=>Zn?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:Je,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:Ve.map(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U,children:t.toTitleCase(U)},U))})]})]}):null,la=()=>ea?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:Be,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(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.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:U=>{U.stopPropagation(),We(U.target.value)},onClick:U=>U.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,oa=()=>{var Y,de,oe,ke;const U=ta;return U?e.jsx(e.Fragment,{children:U&&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:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:K})]})}),((de=m.config)==null?void 0:de.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;Z(_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:((ke=m.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:se,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},ia=()=>{if(!sa)return null;const U=we;return e.jsxs(e.Fragment,{children:[U&&w&&!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:()=>G(!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:Y=>{I(n,Y)},disabled:U,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:Y=>L(n,Y),showTitle:!1})]}),e.jsx(t.Collapsible,{open:ne,onOpenChange:ue,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:[!ne&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(W.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",ne?"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:J?W:"none",onValueChange:Y=>k(n,Y),disabled:!xe.supported&&!J,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&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xe.reason}),he&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&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:Y=>T(n,Y),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(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),ze&&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:Qe,onValueChange:Y=>V(n,Y),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:Y=>P(n,Number(Y.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:Qn,onChange:Y=>_(n,Number(Y.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:Jn,onValueChange:Y=>z(n,Y),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:Y=>H(n,Y),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:Yn,onValueChange:Y=>X(n,Y),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(Y=>{const de=!!Y.id&&Jt.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&O(n,Y.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",de?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Y.label||Y.name}),de?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.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:J,onValueChange:Y=>f(n,Y),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 Y=!At||!Nt,de=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(ke,Le)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:ke,disabled:Y,title:de,children:Le})}),Y&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});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:Y=>{const de=Y.target.value;if(de===""){me(n,void 0);return}const oe=Number(de);me(n,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"}),(ye==null?void 0:ye.conditions)&&ye.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:ye.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{Ce(Y),fe(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.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(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(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 (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((de,oe)=>e.jsx("div",{children:String(de)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var ke;de.stopPropagation();const oe=ye.conditions.filter(Le=>Le.id!==Y.id);if(oe.length>0){const Le={...ye,conditions:oe};It(Le)}else if(Fe(void 0),a==="metrics"){const Le={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((ke=m.config)==null?void 0:ke.metricColumns)||[]];_e[n]=Le,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{Ce(null),fe(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(No,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{aliasTemplate:Q,onAliasTemplateChange:Ye}),e.jsx(go,{valueAliases:ce,onValueAliasesChange:ae})]})]})},ca=(ye==null?void 0:ye.conditions)&&ye.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",je&&"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",...d,...o,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:U=>{U.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}),Ne&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,Ne.badgeClassName),children:Ne.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",ca&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),a==="metrics"&&((en=ye==null?void 0:ye.conditions)==null?void 0:en.length)&&!je&&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:ye.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:ye.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a==="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:U=>{U.stopPropagation(),c(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:U=>{U.stopPropagation(),te(!je)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${je?"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:U=>{U.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),je&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[na(),ra(),aa(),l==="kpi"&&ys(),la(),oa(),ia()]})]}),be&&e.jsx(Un,{open:be,onOpenChange:U=>{fe(U),U||Ce(null)},availableFields:B,existingFilters:ye,editingCondition:pe,onSave:U=>{var Y;if(U)It(U);else if(Fe(void 0),a==="metrics"){const de={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}Ce(null)}}),ve&&a==="metrics"&&we&&e.jsx(t.CalculatedFieldEditor,{open:ve,onOpenChange:G,availableFields:E,existingField:Ze,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:U=>{var Ft;if(U.role!=="metric")return;const{card:Y,frame:de,actions:oe}=t.useEditorStore.getState(),ke=((Ft=Y.config)==null?void 0:Ft.metricColumns)||[],Le=de.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:ke,storedFields:Y.calculatedFields||[],sharedFields:Le,updatedField:U,editingField:Ze,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:C})},onSaveToDashboard:U=>{var tn;if(U.role!=="metric")return;const{card:Y,frame:de,actions:oe}=t.useEditorStore.getState(),ke=s,Le=((tn=Y.config)==null?void 0:tn.metricColumns)||[],_e=de.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Le,storedFields:Y.calculatedFields||[],sharedFields:_e,updatedField:{...U,id:ke.id,aliasTemplate:ke.aliasTemplate,valueAliases:ke.valueAliases,parameters:ke.parameters,customFormat:ke.customFormat},editingField:Ze,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:C}),Ct&&oe.updateCardConfig(m.id,{metricColumns:Ct}),oe.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function To({concept:s}){const a=()=>{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:a()})]})})}const Eo={groupBy:zt,pivotBy:cs,metrics:Ia,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:a,label:n,placeholder:r,shouldShow:c,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(C=>C.card),x=t.useEditorStore(C=>C.card.type),h=a.length>0,m=y.useMemo(()=>!l||!d?!0:t.validateFieldForChartType(l,s,x).isValid,[l,d,s,x]),g=(C,E)=>{var S;!((S=p.config)!=null&&S.sortByColumns)||p.config.sortByColumns.findIndex(M=>M.id===C)===-1||u(p.id,C,{direction:E})};if(s==="sortBy"&&c===!1)return null;const v=s!=="sortBy"&&x!=="kpi",b=Eo[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:n})}),e.jsx("div",{ref:o,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":d&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!m,"border-solid border-border/55 bg-background":!d&&h,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!h}),children:a.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(To,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:a.map(C=>C.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map((C,E)=>{const S=C.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(wo,{field:C,zone:s,index:E,sortDirection:S,onSortDirectionChange:M=>g(C.id,M),hasPivotColumns:i,cardType:x})})},C.id)})})})})]})}function Io({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,detailFields:c,activeField:i}){var z,H,X;const[l,d]=y.useState(!1),o=t.useEditorStore(K=>{var Z;return!!((Z=K.card.customCardPreferences)!=null&&Z.url)}),u=t.useEditorStore(K=>K.card),p=t.useEditorStore(K=>K.frame),x=t.findCustomVisualConfigCard(p,u),{manifest:h}=t.useCustomVisual(((z=x==null?void 0:x.customCardPreferences)==null?void 0:z.url)||""),m=(H=h==null?void 0:h.visuals)==null?void 0:H.find(K=>{var Z;return K.name===((Z=x==null?void 0:x.customCardPreferences)==null?void 0:Z.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((X=x==null?void 0:x.customCardPreferences)!=null&&X.url),b=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore(K=>K.actions.updateCardConfig);const C=t.useEditorStore(K=>K.actions.updateCard),E=t.useEditorStore(K=>K.actions.updateFrame),B=t.useDashboardStore(K=>K.isVisualEditing),S=t.useDashboardStore(K=>K.selectedSheetId),M=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),{scopedFields:w}=t.useScopedFields(),{userContext:D}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===u.id&&b?b:u==null?void 0:u.type,A=I==="detailTable",j=s.length>0||n.length>0||c.length>0,R=!A&&(I!=="kpi"||n.length<=2),N=!A,L=!A&&I!=="kpi",F=I!=="kpi"&&j,f=A,k="Drop sort fields here",T=(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:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),N&&e.jsx(wt,{zone:"metrics",fields:n,label:_().label,placeholder:_().placeholder,hasPivotColumns:a.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:c,label:"Columns",placeholder:"Drop columns here"}),n.length>=1&&T&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!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})]})]}),(!o||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(Gn,{mode:"config"})})})]}),(o||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(In,{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(_n,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:w,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{if(K.role!=="metric")return;const{nextStoredFields:Z}=t.saveCalculatedFieldToCardScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:K,previousScope:"card"});C(u.id,{calculatedFields:Z})},onSaveToDashboard:K=>{if(K.role!=="metric")return;const Z=p.calculatedFields||[],{nextSharedFields:se}=t.saveCalculatedFieldToSharedScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:Z,updatedField:K,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:se,currentSharedFields:Z,isVisualEditing:B,selectedSheetId:S,updateFrame:E,updateSheetCalculatedFields:M})},cardId:u.id})]})}function Do({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:n}=t.useEditorCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,c=(r==null?void 0:r.joins)||[];if(c.length===0)return null;const i=d=>!d||d.length===0?"No conditions":d.map(o=>{var h,m,g,v;const u=`${(h=o.source)==null?void 0:h.entityName}.${(m=o.source)==null?void 0:m.name}`,p=`${(g=o.target)==null?void 0:g.entityName}.${(v=o.target)==null?void 0:v.name}`,x=o.operator||"=";return`${u} ${x} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?i(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:i(o.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(La,{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:c.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:c.map((d,o)=>{const u=l(d),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:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.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:d.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})})})]},d.id||o)})})})]})})]}),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 Tn={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(a){return console.warn(`Failed to read from localStorage (${s}):`,a),null}},setItem(s,a){if(!(typeof window>"u"))try{localStorage.setItem(s,a)}catch(n){console.warn(`Failed to write to localStorage (${s}):`,n)}}};function ko({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d}){var A,j;const[o,u]=y.useState(()=>Tn.getItem("chart-selector-expanded")==="true"),[p,x]=y.useState(!1),h=t.useEditorStore(R=>R.card),m=t.useEditorStore(R=>R.actions.updateCardConfig),g=n.length>0||r.length>0||c.length>0||l.length>0,{data:v,autoJoinMetadata:b}=t.useEditorCardQuery(h),C=g||!!v,E=((A=h==null?void 0:h.config)==null?void 0:A.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)||[],S=R=>{m(h.id,{...h==null?void 0:h.config,joinPlan:R}),x(!1)},M=()=>{m(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},w=()=>{x(!1)},D=()=>{x(!0)};y.useEffect(()=>{Tn.setItem("chart-selector-expanded",String(o))},[o]);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",o?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(us,{selectedChart:s,onChartChange:a,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":o,"mt-2":!o}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:I})})]})}),C&&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",C?"pt-1":"pt-4"),children:[e.jsx(Do,{onEditJoins:D}),e.jsx(Io,{groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d})]})}),e.jsx(Mn,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:B,onSave:S,onCancel:w,onRemove:M,children:e.jsx("div",{})})]})}function Ao({initialFilters:s,availableFields:a}={}){const[n,r]=y.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:c,isLoading:i}=t.useFilterableFields(),l=a||c||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}]}}return{...w,groups:w.groups.map(M)}};r(M(n))},u=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(M)}};r(M(n))},p=(S,M)=>{const w=D=>D.id===S?{...D,conditions:D.conditions.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(n))},x=(S,M)=>{const w=D=>D.id===S?{...D,groups:D.groups.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(n))},h=(S,M,w,D)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=A=>A.id===S?{...A,conditions:A.conditions.map(j=>j.id===M?{...j,[w]:D}:j)}:{...A,groups:A.groups.map(I)};r(I(n))},m=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:I.conditions.map(A=>A.id===M?{...A,...w}:A)}:{...I,groups:I.groups.map(D)};r(D(n))},g=(S,M)=>{const w=D=>D.id===S?{...D,logicalOperator:M}:{...D,groups:D.groups.map(w)};r(w(n))},v=(S,M)=>{const w=D=>D.id===S?{...D,negate:M}:{...D,groups:D.groups.map(w)};r(w(n))},b=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:t.arrayMove(I.conditions,M,w)}:{...I,groups:I.groups.map(D)};r(D(n))},C=(S,M,w)=>{const D=I=>I.id===S?{...I,groups:t.arrayMove(I.groups,M,w)}:{...I,groups:I.groups.map(D)};r(D(n))},E=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const M=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 A=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",N=j[1]?`'${j[1]}'`:"NULL";return`${I} BETWEEN ${R} AND ${N}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(j)){const R=j.map(N=>N?`'${N}'`:"NULL").join(", ");return`${I} ${A} (${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(N=>typeof N=="string"?`'${N}'`:String(N)):typeof j=="string"?R=j.split(",").map(N=>{const L=N.trim();return D.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(R=[String(j)]),j=`(${R.join(", ")})`}switch(A){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} ${A} ${j}`}},w=D=>{const I=D.conditions.map(M),A=D.groups.map(L=>w(L)),j=[...I,...A].filter(Boolean);if(j.length===0)return"";const R=j.join(` ${D.logicalOperator} `),N=j.length>1?`(${R})`:R;return D.negate?`NOT ${N}`:N};return w(S)},B=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B}}function Mo({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Lo=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Fo({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:c="w-64"}){const[i,l]=y.useState(!1),d=y.useMemo(()=>{const o={};return n.forEach(u=>{const p=Lo(u);o[p]||(o[p]={}),o[p][u.entityId]||(o[p][u.entityId]=[]),o[p][u.entityId].push(u)}),o},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,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",c),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Mo,{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(d).map(([o,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"}),o]}),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:()=>{a(h),l(!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))]},`${o}-${p}`))},o))})]})})]})}function fs(s){var v;const a=t.useEditorStore(b=>b.card),{authToken:n,tokenProps:r}=t.useSemaphorContext(),c=t.useEditorStore(b=>b.card.config),i=c==null?void 0:c.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((v=a.dataSource)==null?void 0:v.connectionId)||a.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`,(n==null?void 0:n.accessToken)||"",{connection_id:p,cardConfig:u,cardDataSource:a.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 Ro({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:c}){const[i,l]=Pt.useState(!1),{filterValues:d}=fs(s),o=p=>{n(a.filter(x=>x!==p))},u=p=>{a.includes(p)?n(a.filter(x=>x!==p)):n([...a,p])};return e.jsx("div",{className:t.cn("w-full",c),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,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:a.length>0?a.map(p=>{const x=d.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"&&o(p)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),o(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:d.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",a.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 Oo({field:s,value:a,onChange:n,placeholder:r="Select value...",className:c}){const{filterValues:i,isPending:l,error:d}=fs(s);return l?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..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:c||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((o,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function Po({value:s,operator:a,onChange:n,className:r}){var m,g,v;const{tokenProps:c}=t.useSemaphorContext(),i=((g=(m=c==null?void 0:c.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=c==null?void 0:c.params)==null?void 0:v.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",o=y.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,C=s[1]?new Date(s[1]):void 0;if(b&&C)return{from:b,to:C}}},[s,d]),u=y.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const C=new Date(b);if(!isNaN(C.getTime()))return C},[s,d]),p=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,l):t.startOfDayInTimezone(b,l),x=b=>{if(!b){n([]);return}if(b.from&&b.to){n([b.from.toISOString(),b.to.toISOString()]);return}n([])},h=b=>{if(!b){n("");return}const C=p(b);n(C.toISOString())};return e.jsx(t.DateRangePicker,{value:d?o:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:u,onChange:x,onSingleChange:h,timezone:i,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Bo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Vo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],zo=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],_o=["=","!=","isNull","isNotNull"],qo=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],$o={"=":"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 En(s){return $o[s]||t.titleCase(s)}function Ko(s){switch(s){case"string":return Vo;case"number":return zo;case"boolean":return _o;case"date":return qo;default:return Bo}}function Hn({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:c,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){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),C={transform:t.CSS.Transform.toString(h),transition:m};return e.jsxs("div",{ref:x,style:C,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"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:E=>l(n,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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Fo,{value:s.field,onValueChange:E=>{const B=E,S=t.getDataType(B.dataType)==="date";o(n,s.id,{field:B,value:"",operator:S?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?o(n,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?o(n,s.id,{operator:E,value:null}):E==="between"||E==="not between"?o(n,s.id,{operator:E,value:[]}):o(n,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?En(s.operator):""})}),e.jsx(t.SelectContent,{children:Ko(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:En(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(Ro,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>o(n,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=>o(n,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Oo,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>o(n,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=>o(n,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(Po,{value:s.value,operator:s.operator,onChange:E=>o(n,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>c(n,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(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Go({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:c,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:p,onAddCondition:x,onAddGroup:h,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:C,setNodeRef:E,transform:B,transition:S,isDragging:M}=t.useSortable({id:s.id}),w={transform:t.CSS.Transform.toString(B),transition:S},D=A=>{const{active:j,over:R}=A;if(R&&j.id!==R.id){const N=s.conditions.findIndex(F=>F.id===j.id),L=s.conditions.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&u(s.id,N,L)}},I=A=>{const{active:j,over:R}=A;if(R&&j.id!==R.id&&n){const N=s.groups.findIndex(F=>F.id===j.id),L=s.groups.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&p(n,N,L)}};return e.jsxs("div",{ref:E,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${M?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...C,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:()=>c(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:A=>r(s.id,A),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:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((A,j)=>e.jsx(Hn,{condition:A,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},A.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(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(A=>g(A,a+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 Uo({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:c}){const{currentFilters:i,availableFields:l,isLoading:d,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B,setCurrentFilters:S}=Ao({initialFilters:s,availableFields:a}),M=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[w,D]=y.useState(!1),I=(R,N,L)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(k=>k.id===N?{...k,field:L,dataType:L.dataType}:k)}:{...f,groups:f.groups.map(F)};S(F(i))},A=(R,N=0,L)=>N===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const T=R.conditions.findIndex(O=>O.id===f.id),V=R.conditions.findIndex(O=>O.id===k.id);T!==-1&&V!==-1&&b(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Hn,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const T=R.groups.findIndex(O=>O.id===f.id),V=R.groups.findIndex(O=>O.id===k.id);T!==-1&&V!==-1&&C(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>A(F,N+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:()=>o(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&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(Go,{group:R,depth:N,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:l,renderFilterGroup:A,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:[d?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..."})]}):A(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:w,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:c,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(B?i:null),children:"Apply Filters"})]})]})}function Ho({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:c,isOpen:i,onOpenChange:l}){const d=u=>{n(s,u),l(!1)},o=()=>{r(s),l(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:l,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(Uo,{filters:a,availableFields:c,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function Qo({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var E,B;const[c,i]=y.useState(null),l=t.useEditorStore(S=>S.card),d=t.useEditorStore(S=>S.actions.updateCardConfig),o=t.useEditorStore(S=>S.actions.setCardPreferences),u=(E=l==null?void 0:l.config)==null?void 0:E.joinPlan,p=y.useCallback(S=>S.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),x=(B=l==null?void 0:l.dataSource)==null?void 0:B.semanticDomainId,{data:h}=t.useJoinabilityMap(x),m=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],g=y.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(M=>M.id===S)?"source":n("groupBy").find(M=>M.id===S)?"groupBy":n("metrics").find(M=>M.id===S)?"metrics":n("pivotBy").find(M=>M.id===S)?"pivotBy":n("sortBy").find(M=>M.id===S)?"sortBy":n("detailColumns").find(M=>M.id===S)?"detailColumns":null,[a,n]),v=y.useCallback(S=>{i(S.active.id)},[]),b=y.useCallback(S=>{var R;const{active:M,over:w}=S;if(!w||!s){i(null);return}const D=M.id,I=w.id,A=g(D),j=g(I)||I;if(j==="sortBy"){if(A==="source"){const N=a.find(F=>F.id===D);if(!N){i(null);return}if(!(n("groupBy").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||n("metrics").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||n("detailColumns").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName))){i(null);return}}else if(A==="pivotBy"){i(null);return}else if(A!=="groupBy"&&A!=="metrics"&&A!=="sortBy"&&A!=="detailColumns"){i(null);return}}if(A==="source"&&j==="sortBy"){const N=[...a].find(k=>k.id===D);if(!N){i(null);return}const L=n("sortBy");if(t.fieldAlreadyExists(N,L)){i(null);return}const F=t.validateFieldForChartType(N,"sortBy",l.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(N,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(A==="source"&&j!=="source"&&j!=="sortBy"){const N=[...a].find(O=>O.id===D);if(!N){i(null);return}const L=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],F=L.filter(O=>!p(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){i(null);return}if(O!==N.qualifiedEntityName&&!p(N)&&N.qualifiedEntityName)if(x&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(N,{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,N.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=n(j);if(t.fieldAlreadyExists(N,f)){i(null);return}const k=t.validateFieldForChartType(N,j,l.type);if(!k.isValid){t.ue.error("Invalid Field Type",{description:k.reason,position:"top-center",duration:3e3}),i(null);return}const T=t.getNewField(N,j,f),V=[...f,T];if(i(null),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,T,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(A&&j&&A!=="source"&&j!=="source"&&A!==j){const N=n(A),L=n(j),F=N.find(O=>O.id===D);if(!F){i(null);return}const f=t.validateFieldForChartType(F,j,l.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 T=N.filter(O=>O.id!==D),V=[...L,k];if(r(A,T),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,k,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(A&&j&&A===j&&A!=="source"){const N=n(A),L=N.findIndex(f=>f.id===D),F=N.findIndex(f=>f.id===I);if(L!==F){const f=t.arrayMove(N,L,F);r(A,f)}}i(null)},[s,a,n,r,g,u,x,h,p,l,d,o]),C=c?m.find(S=>S.id===c):null;return{activeId:c,activeField:C,handleDragStart:v,handleDragEnd:b}}function Jo({activeView:s,onViewChange:a,splitViewEnabled:n}){const r=t.useEditorStore(d=>d.card),{config:c}=y.useContext(t.SemaphorContext).tokenProps,i=(c==null?void 0:c.showInfoTab)!==!1,l=()=>n?!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:d=>a(d),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"}),l()&&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 Yo=[{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 Wo(){var o,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=y.useState(!1),[c,i]=y.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),a(s.id,parseInt(p))},d=p=>{const x=p.target.value;i(x),x&&!isNaN(parseInt(x))&&a(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:c,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(o=s.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:l,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:Yo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Xo({card:s,queryData:a,isLoading:n,isFetching:r,pagination:c,onPaginationChange:i,onSortChange:l,sortState:d,splitViewEnabled:o,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const x=y.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),h=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Vn,{fallbackPreview:e.jsx(ot,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return h?o?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:[(n||r)&&(a==null?void 0:a.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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]}):m:!o||["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:[(n||r)&&(a==null?void 0:a.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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]})}const Zo="semaphor-split-view-enabled";function ei(){return Ln(Zo,!0)}function ti({activeView:s,onViewChange:a,onFiltersClick:n,activeCard:r,columns:c}){var be,fe,ve;const i=t.useEditorStore(G=>G.card),l=t.useEditorStore(G=>G.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),d=t.useEditorStore(G=>G.actions.removeCardInlineFilterValue),o=t.useDashboardStore(G=>G.filterValues),u=t.useDashboardStore(G=>G.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:h,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(G=>G.showAIDialog),v=t.useEditorStore(G=>G.isDevMode),b=t.useDashboardStore(G=>G.isVisualEditing),[C,E]=y.useState(!1),[B,S]=y.useState(!1),[M,w]=y.useState(!1),[D,I]=y.useState(null),{config:A}=y.useContext(t.SemaphorContext).tokenProps,j=(A==null?void 0:A.showInfoTab)!==!1,R=(A==null?void 0:A.showQueryDebugTools)!==!1,[N,L]=ei();t.useEditorStore(G=>{var pe;return!!((pe=G.card.customCardPreferences)!=null&&pe.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:k,errorMessage:T,isLoading:V,isFetching:O,errorSql:P,pagination:_,refetch:z,comparisonMetadata:H,queryRequestPayload:X,resolvedPrimaryDateField:K}=t.useEditorCardQuery(r),Z=y.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[se,me]=y.useState(!1);y.useEffect(()=>{O||me(!1)},[O]);const je=()=>{const G=!N;G&&s==="table"&&a("chart"),L(G)},te=(G,pe)=>{const Ce={...r,paginationConfig:{page:G+1,pageSize:pe}};x(Ce),h(Ce)},ne=G=>{if(!i.config)return;const pe=t.sortStateToSortByColumns(G,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);p(i.id,{...i.config,sortByColumns:pe})},ue=y.useMemo(()=>{var G;return t.sortByColumnsToSortState((G=i.config)==null?void 0:G.sortByColumns)},[(be=i.config)==null?void 0:be.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(Jo,{activeView:s,onViewChange:a,splitViewEnabled:N}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(fe=r.config)==null?void 0:fe.filters,cardFilterCount:t.getFilterCount(((ve=r.config)==null?void 0:ve.filters)||null),onFiltersClick:n,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:u||"",removeInlineFilterValue:G=>d(r.id,G),resolvedPrimaryDateField:K}),H&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Wo,{})}),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:()=>{me(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":se})})}),s==="chart"&&!f&&e.jsx(Bn,{showInlineFilters:!1,showDisplayOptions:!1}),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:je,children:[N?e.jsx(ga,{className:"mr-2 h-4 w-4"}):e.jsx(Aa,{className:"mr-2 h-4 w-4"}),N?"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(zn,{onCustomize:()=>w(!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":N&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Xo,{card:r,queryData:k,isLoading:V,isFetching:O,pagination:_,onPaginationChange:te,onSortChange:ne,sortState:ue,splitViewEnabled:N,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:w})}),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:Z,comparisonMetadata:H,paginationMetadata:_,onPaginationChange:te,isLoading:V||O,onSortChange:ne,sortState:ue})]}),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:T?e.jsx(ds,{error:T,errorSql:P,onSendFeedback:()=>{const G=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:T,errorSql:P,generatedSql:k==null?void 0:k.sql});I(G),S(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const G=t.useEditorStore.getState().actions;G.setIsDevMode(!0),G.setCardSql(P||""),setTimeout(()=>{G.setRunSql(!0)},100)},100)}}):(k==null?void 0:k.sql)&&e.jsx(Rn,{sql:k.sql,showCardDetails:!0,debugPayloads:R?{queryRequest:X,queryResponse:k,columns:c,dashboardFilters:o}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:B,onOpenChange:S,feedbackData:D})]})})}function si({activeField:s}){const[a,n]=y.useState(!0);return y.useEffect(()=>{s&&n(!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 ${a?"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 ni=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var c;if((c=r.reason)!=null&&c.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function ai({column:s,isSelected:a,onSelect:n,availableFields:r,width:c,onWidthChange:i}){var O,P,_;const l=t.useEditorStore(z=>z.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=y.useRef(null),b=y.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:c||150};const H=K=>{if(!v.current)return;const Z=K.clientX-v.current.startX,se=Math.max(80,v.current.startWidth+Z);i==null||i(s.id,se)},X=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",X)};document.addEventListener("mousemove",H),document.addEventListener("mouseup",X)},[c,s.id,i]),C=(O=l==null?void 0:l.config)==null?void 0:O.filters,E=(P=C==null?void 0:C.conditions)==null?void 0:P.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),B=z=>{z?p(l.id,z):d(l.id,{filters:void 0})},{attributes:S,listeners:M,setNodeRef:w,transform:D,transition:I,isDragging:A}=t.useSortable({id:s.id}),j={transform:t.CSS.Transform.toString(D),transition:I},R=t.getDataType(s.dataType),N=ri(R),L=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.sortByColumns)||[],H=z.findIndex(K=>K.name===s.name);if(H!==-1){const K=[...z];K[H]={...K[H],direction:"asc"},d(l.id,{sortByColumns:K})}else d(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.sortByColumns)||[],H=z.findIndex(K=>K.name===s.name);if(H!==-1){const K=[...z];K[H]={...K[H],direction:"desc"},d(l.id,{sortByColumns:K})}else d(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.groupByColumns)||[];if(!z.some(K=>K.name===s.name)){const K={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...z,K]})}},k=z=>{var K;const H=((K=l==null?void 0:l.config)==null?void 0:K.metricColumns)||[];if(!H.some(Z=>Z.name===s.name&&Z.aggregate===z)){const Z={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};d(l.id,{metricColumns:[...H,Z]})}},T=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&u(l.id,s.id)},V={...j,width:c?`${c}px`:void 0,minWidth:c?`${c}px`:"120px"};return e.jsxs("th",{ref:w,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",A&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...M,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:n,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",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(N,{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(ha,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(xa,{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:T,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(Un,{open:x,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:C,editingCondition:E?(_=C==null?void 0:C.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function ri(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function li({selectedColumn:s,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[],filterableFields:c=r}){var A,j,R,N;const i=t.useEditorStore(L=>L.card),{updateCardConfig:l}=t.useEditorActions(),[d,o]=y.useState(null),[u,p]=y.useState({}),[x,h]=y.useState(!1),m=y.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]},[(A=i==null?void 0:i.config)==null?void 0:A.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),g=y.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.useEditorCardQuery(i),C=(v==null?void 0:v.records)||[],E=y.useCallback((L,F)=>{p(f=>({...f,[L]:F}))},[]),B=y.useCallback(L=>{var T,V;const F=t.getDataType(L.dataType),f=((T=i==null?void 0:i.config)==null?void 0:T.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"};l(i.id,{metricColumns:[...k,O]})}else{const O={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...f,O]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(N=i==null?void 0:i.config)==null?void 0:N.metricColumns,i.id,l]),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),M=L=>{o(L.active.id)},w=L=>{const{active:F,over:f}=L;if(o(null),!f||F.id===f.id)return;const k=m.findIndex(V=>V.id===F.id),T=m.findIndex(V=>V.id===f.id);if(k!==-1&&T!==-1){const V=t.arrayMove(m,k,T),O=V.filter(_=>_.role==="groupby"),P=V.filter(_=>_.role==="metric");l(i.id,{groupByColumns:O,metricColumns:P})}},D=d?m.find(L=>L.id===d):null,I=L=>{let F="";for(;L>=0;)F=String.fromCharCode(L%26+65)+F,L=Math.floor(L/26)-1;return F};return n?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:S,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:w,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(ai,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>a(L),availableFields:c,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"})})}):C.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"})}):C.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:oi(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(C.length,100)," of ",C.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function oi(s,a){if(s==null)return"—";if(typeof s=="number")return a.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 n=new Date(s);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function ii({entityGroups:s,isLoading:a=!1}){var B,S;const n=t.useEditorStore(M=>M.card),{updateCardConfig:r,removeGroupByColumn:c,removeMetricColumn:i}=t.useEditorActions(),[l,d]=y.useState(!0),[o,u]=y.useState(""),[p,x]=y.useState(new Set),h=((B=n==null?void 0:n.config)==null?void 0:B.groupByColumns)||[],m=((S=n==null?void 0:n.config)==null?void 0:S.metricColumns)||[],g=M=>{const w=new Set(p);w.has(M)?w.delete(M):w.add(M),x(w)},v=M=>h.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName)||m.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName),b=(M,w)=>{if(w)if(t.getDataType(M.dataType)==="number"){const I={...M,id:`metric-${M.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...m,I]})}else{const I={...M,id:`groupby-${M.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...h,I]})}else{const D=h.findIndex(A=>A.name===M.name&&A.qualifiedEntityName===M.qualifiedEntityName),I=m.findIndex(A=>A.name===M.name&&A.qualifiedEntityName===M.qualifiedEntityName);D!==-1&&c(n.id,h[D].id),I!==-1&&i(n.id,m[I].id)}},C=M=>{if(!o)return M;const w=o.toLowerCase();return M.filter(D=>D.name.toLowerCase().includes(w)||D.label&&D.label.toLowerCase().includes(w))},E=M=>{switch(t.getDataType(M)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return l?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:()=>d(!1),title:"Close panel",children:e.jsx(Sa,{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:o,onChange:M=>u(M.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(M=>{const w=E(M.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.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:()=>c(n.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.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(M=>{const w=E(M.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.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(n.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?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(M=>{const w=C(M.columns);if(w.length===0)return null;const D=p.has(M.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:D,onOpenChange:()=>g(M.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:M.label||M.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(I=>{const A=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(A,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.id)})})})]},M.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:()=>d(!0),title:"Open panel",children:e.jsx(wa,{className:"h-4 w-4"})})})}const ci=[{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 di({value:s,onChange:a,onSubmit:n,onCancel:r,selectedColumn:c,availableColumns:i}){const[l,d]=y.useState(!1),[o,u]=y.useState("column"),p=y.useRef(null);y.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!l&&n(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,n,l]);const x=g=>{const v=`[${g.label||g.name}]`,b=p.current;if(b){const C=b.selectionStart||0,E=b.selectionEnd||0,B=s.slice(0,C)+v+s.slice(E);a(B),setTimeout(()=>{b.setSelectionRange(C+v.length,C+v.length),b.focus()},0)}else a(s+v);d(!1)},h=g=>{const v=p.current;if(v){const b=v.selectionStart||0,C=v.selectionEnd||0,E=s.slice(0,b)+g.syntax+s.slice(C);a(E),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else a(s+g.syntax);d(!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:c?e.jsx("span",{className:"truncate",children:c.label||c.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:g=>{d(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(ka,{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:ci.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:l&&o==="column",onOpenChange:g=>{d(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=>a(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:()=>n(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function ui({className:s}){var m,g,v,b;const a=t.useEditorStore(C=>C.card),[n,r]=y.useState(null),[c,i]=y.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(v=a==null?void 0:a.config)!=null&&v.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const p=C=>{r(C),i(C?`[${C.label||C.name}]`:"")},x=C=>{console.log("Formula submitted:",C),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(di,{value:c,onChange:i,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(li,{selectedColumn:n,onColumnSelect:p,isLoading:o,sourceFields:l,filterableFields:u})}),e.jsx(ii,{entityGroups:d,isLoading:o})]})]})}function mi(){var T,V;const[s,a]=y.useState("chart"),[n,r]=y.useState(!1),[c,i]=y.useState(!0),l=t.useEditorStore(O=>O.showAIDialog),d=t.useDashboardStore(O=>O.isVisualEditing),{setCardType:o}=t.useEditorActions(),u=t.useEditorStore(O=>O.card.type);y.useEffect(()=>ni(),[]);const p=O=>{o(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:C}=t.useEditorActions(),{columnFields:E=[],scopedFields:B=[],filterableFields:S=[]}=t.useFilterableFields(),M=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),w=h,{getFieldsForContainer:D,setFieldsForContainer:I}=t.useFieldManagement(w),{activeField:A,handleDragStart:j,handleDragEnd:R}=Qo({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:D,setFieldsForContainer:I}),N=(O,P)=>{P&&C(O,P)},L=O=>{var P;v(O,{config:{...(P=x.cards.find(_=>_.id===O))==null?void 0:P.config,filters:void 0}})},F=S,f=O=>{if(!O)return 0;let P=O.conditions.length;return O.groups.forEach(_=>{P+=f(_)}),P},k=f(((T=w==null?void 0:w.config)==null?void 0:T.filters)||null);return e.jsxs(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Fn,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(ui,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(ko,{selectedChart:u,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:A}),e.jsx(ti,{selectedChart:u,activeView:s,onViewChange:a,onFiltersClick:()=>r(!0),filterCount:k,activeCard:w,columns:E,getFieldsForContainer:D,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:b})]})}),!c&&d&&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"})})})]}),w&&e.jsx(Ho,{cardId:w.id,filters:((V=w.config)==null?void 0:V.filters)||null,onFiltersChange:N,onClearFilters:L,availableFields:F,isOpen:n,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(si,{activeField:A||null})})]})}function xi({authToken:s,onSave:a,onClose:n}){const r=y.useRef(null),c=t.useEditorStore(w=>w.showAIDialog),i=t.useEditorStore(w=>w.isDevMode),l=t.useAssistantLayoutStore(w=>w.setFullscreen),d=t.useAssistantLayoutStore(w=>w.setPanelOpen),o=t.useAssistantLayoutStore(w=>w.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),h=p==="editor",m=y.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:C}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();y.useEffect(()=>{a&&b(a),n&&C(n)},[a,b,n,C]),y.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),y.useEffect(()=>{var w,D;c?((w=r.current)==null||w.resize(40),d("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),d("editor",!1),p==="editor"&&l(null),E(null))},[c,d,E,l,p]);function B(w){var D;w<1?(v(!1),d("editor",!1),p==="editor"&&l(null),E(null),(D=r.current)==null||D.resize(0)):(c||(v(!0),E("editor")),u.isOpen||d("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Fn,{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(mo,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),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(wn,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function M(){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(mi,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),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(wn,{isFullscreen:h,onFullscreenChange:w=>l(w?"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:S()}):M()})}function hi(){t.useDashboardStore(u=>u.selectedCardId);const s=t.useDashboardStore(u=>u.selectedSheetId),a=t.useDashboardStore(u=>u.dashboard),{setIsVisualEditing:n,setSelectedSheetId:r}=t.useDashboardStore(u=>u.actions),c=t.useDashboardStore(u=>u.isVisualEditing),i=t.useDashboardStore(u=>u.actions.updateFrame),l=t.useResolveExistingFrameSemanticExecutionPayload();async function d(u){var g,v,b;const p=s?(g=a==null?void 0:a.sheets)==null?void 0:g.some(C=>{var E;return C.id===s&&((E=C.frames)==null?void 0:E.some(B=>B.id===u.id))}):!1,x=(b=(v=a==null?void 0:a.sheets)==null?void 0:v.find(C=>{var E;return(E=C.frames)==null?void 0:E.some(B=>B.id===u.id)}))==null?void 0:b.id,h=p?s:x||null;if(!h)return;const m=t.findDashboardFrameById(a,u.id);try{const C=await l(u,{previousFrame:m});i(h,u,{semanticExecutionPayload:C}),s!==h&&r(h),n(!1)}catch(C){console.error("Failed to resolve semantic metadata on save:",C),t.ue.error(C instanceof Error?C.message:"Failed to resolve semantic metadata for this visual")}}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),children:e.jsx(xi,{onSave:d,onClose:o})})}exports.default=hi;
|
|
182
|
+
`),ue=new Blob([ne],{type:"text/csv"}),be=URL.createObjectURL(ue),fe=document.createElement("a");fe.href=be,fe.download=`${c.title}.csv`,fe.click()}return c?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:[d&&e.jsx("div",{className:"flex grow items-center",children:e.jsxs("div",{className:"flex items-center gap-3",children:[(a==null?void 0:a.show)&&e.jsx(t.IconButton,{tooltip:a.isOpen?"Hide Visual Aside":"Show Visual Aside",className:"h-7 w-7 px-0",buttonProps:{variant:"outline"},onClick:a.onToggle,children:a.isOpen?e.jsx(t.ChevronLeft,{className:"h-3.5 w-3.5"}):e.jsx(t.ChevronRight,{className:"h-3.5 w-3.5"})}),!v&&e.jsx("div",{className:"w-[200px]",children:e.jsx(us,{variant:l?"secondary":"ghost"})})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(t.IconButton,{tooltip:"Refresh",disabled:N||L,className:"h-7 w-7 px-0",onClick:()=>{if(H(!0),l){it.flushPendingEditorDrafts(),setTimeout(()=>{n.removeQueries({queryKey:O.current,exact:!0}),h(!0)},0);return}k()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-3.5 w-3.5",{"animate-spin":z})})}),!v&&e.jsx(Bn,{showInlineFilters:!1,showDisplayOptions:!1}),(l||p)&&e.jsxs(e.Fragment,{children:[e.jsx(Mr,{}),i&&e.jsxs(e.Fragment,{children:[e.jsx(kr,{}),e.jsx(Ar,{})]})]}),e.jsxs(t.DropdownMenu,{modal:!1,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(t.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),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(c.type)&&u&&e.jsx(xr,{triggerVariant:"menu",className:"w-full"}),e.jsx(xs,{triggerVariant:"menu",className:"w-full"}),e.jsx(ms,{triggerVariant:"menu",className:"w-full"}),e.jsx(zn,{onCustomize:()=>C(!0)}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:me,children:[e.jsx(t.Download,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download CSV"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:se,children:[e.jsx(fa,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Download JSON"})]}),e.jsxs(t.Button,{variant:"ghost",className:"h-7 w-full justify-start gap-2 px-2 text-[13px]",onClick:Z,children:[e.jsx(t.Copy,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Copy JSON"})]})]})]})]})]})]}),d?v?e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Vn,{fallbackPreview:e.jsx(ot,{}),records:_,title:c.title,isInspectorOpen:b,onInspectorOpenChange:C})}):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(Dr,{})}),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&&(l?e.jsx(or,{data:R.records,card:j,paginationMetadata:V,onPaginationChange:X,onPageSizePreferenceChange:A,onSortChange:K,isLoading:N||L}):R.records.length>0?e.jsx(t.TableVisual,{card:c,data:_,comparisonMetadata:(je=R==null?void 0:R.metadata)==null?void 0:je.comparisonMetadata,paginationMetadata:V,onPaginationChange:X,onSortChange:K,isLoading:N||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||c.sql||c.python,onDebugWithAssistant:P,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Dr(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=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:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function kr(){var n,r;const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.actions.setCardPreferences);return s.type!=="table"&&s.type!=="detailTable"?null:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Label,{htmlFor:"table-density",className:"text-[13px]",children:"Density"}),e.jsxs(t.Select,{value:((r=(n=s.preferences)==null?void 0:n.tablePrefs)==null?void 0:r.density)??"compact",onValueChange:c=>{var i;a({...s.preferences,tablePrefs:{...(i=s.preferences)==null?void 0:i.tablePrefs,density:c}})},children:[e.jsx(t.SelectTrigger,{id:"table-density",className:"h-7 w-[116px] rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"compact",children:"Compact"}),e.jsx(t.SelectItem,{value:"comfortable",children:"Comfortable"}),e.jsx(t.SelectItem,{value:"spacious",children:"Spacious"})]})]})]})}function Ar(){var d,o,u,p,x,h,m,g;const s=t.useEditorStore(v=>v.card),a=t.useEditorStore(v=>v.actions.setCard),n=t.useEditorStore(v=>v.actions.setRunSql),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=t.useEditorStore(v=>v.actions.updateCardInFrame),i=y.useMemo(()=>{var v,b;return t.getTablePageSizeOptions((b=(v=s.preferences)==null?void 0:v.tablePrefs)==null?void 0:b.pageSize)},[(o=(d=s.preferences)==null?void 0:d.tablePrefs)==null?void 0:o.pageSize]),l=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-[13px]",children:"Paginate"}),((g=(m=s.preferences)==null?void 0:m.tablePrefs)==null?void 0:g.enableDevModePagination)&&e.jsxs(t.Select,{value:String(l),onValueChange:v=>{var E,B,S;const b=Number(v),C={...s,preferences:{...s.preferences,tablePrefs:{...(E=s.preferences)==null?void 0:E.tablePrefs,pageSize:b}},paginationConfig:{page:1,pageSize:b}};a(C),c(C),s.sql&&((S=(B=s.preferences)==null?void 0:B.tablePrefs)!=null&&S.enableDevModePagination)&&n(!0)},children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20 rounded-[5px] px-2 text-[12px]",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(v=>e.jsx(t.SelectItem,{value:String(v),children:v},v))})]})]})}function Mr(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs(t.Toggle,{pressed:!s,onPressedChange:n=>{a(!n)},variant:"default",size:"sm",className:"h-7 gap-1.5 rounded-[5px] border border-transparent px-2.5 text-[12px] 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-3.5 w-3.5"}),e.jsx("span",{children:"Query Output"})]})}function qe({value:s,onCommit:a,type:n="text",placeholder:r,className:c}){const[i,l]=y.useState(s),d=y.useRef(!1);y.useEffect(()=>{l(s)},[s]);const o=()=>{if(d.current){d.current=!1;return}i!==s&&a(i)},u=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(s),p.currentTarget.blur())};return e.jsx(t.Input,{type:n,placeholder:r,value:i,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:u,className:c})}function nt({defaultValue:s,label:a,options:n,value:r,onValueChange:c,className:i,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:c,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:[l&&e.jsx("span",{children:l}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(o=>e.jsx(t.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function Lr(s,a){return t.getSlotDefinitionForIndex(s,a)||null}function St(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,r,c]=a;return`Tabs ${Number(r)+1}-${Number(c)+1}`}const n=s.match(/^(\d+)\+$/);return n?`Tabs ${Number(n[1])+1}+`:`Tab ${s}`}function Fr(s){return s?Array.isArray(s)?s:[s]:[]}function ts(s){var r,c;if(!s)return!1;if(s.type==="text")return!!((r=s.description)!=null&&r.trim());const a=!!((c=s.sql)!=null&&c.trim()),n=t.hasValidCardConfig(s.config);return a||n}function Rr({slots:s,cards:a,minInputs:n}){const r=[],c=a.filter(Boolean).length;return n&&c<n&&r.push({type:"too-few-inputs",message:`This visual requires at least ${n} tab${n===1?"":"s"}.`}),!s||s.length===0||(s.forEach(i=>{if(!i.required)return;if(typeof i.position=="number"){const o=a[i.position];ts(o)||r.push({type:"missing-required",message:`${St(i.position)} ("${i.label}") is required but has no data configured.`});return}const l=i.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,u]=l.map(Number);for(let p=o;p<=u;p+=1){const x=a[p];if(!ts(x)){r.push({type:"missing-required",message:`${St(p)} ("${i.label}") is required but has no data configured.`});break}}return}const d=i.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(a.length<=o){r.push({type:"missing-required",message:`${St(o)} ("${i.label}") is required but has no data configured.`});return}for(let u=o;u<a.length;u+=1){const p=a[u];if(!ts(p)){r.push({type:"missing-required",message:`${St(u)} ("${i.label}") is required but has no data configured.`});break}}}}),a.forEach((i,l)=>{if(!i)return;const d=Lr(s,l);if(!d||!d.expectedType)return;const o=Fr(d.expectedType);o.length!==0&&(o.includes(i.type)||r.push({type:"wrong-type",message:`${St(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${i.type}.`}))})),r}const Or={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:a})=>(a==null?void 0:a.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 _n(){var N,L,F;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=t.usePluginQuery(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),c=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:i}=t.useEditorActions(),l=y.useMemo(()=>t.findCustomVisualConfigCard(c,r),[c,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:u}=t.useCustomVisual((d==null?void 0:d.url)||(s==null?void 0:s.url)||""),p=(N=u==null?void 0:u.visuals)==null?void 0:N.find(f=>f.name===((d==null?void 0:d.componentName)||(s==null?void 0:s.componentName))),h=t.resolveMultiInputType(l||r,p)==="multiple",m=!!l&&l.id===r.id,g=(p==null?void 0:p.minInputs)??((L=l==null?void 0:l.customCardPreferences)==null?void 0:L.minInputs),v=(p==null?void 0:p.maxInputs)??((F=l==null?void 0:l.customCardPreferences)==null?void 0:F.maxInputs),b=y.useMemo(()=>t.getCustomVisualInputCards({frame:c,configCard:l||r,isMultiInputVisual:h}),[c,l,r,h]),C=y.useMemo(()=>t.buildSlotOrderedCards(b),[b]),E=y.useMemo(()=>C.map((f,k)=>{if(!f)return null;const T=t.getSlotIndexForCard(f,k),V=t.getEffectiveCardTypeForSlot(f,T,p==null?void 0:p.slots);return{...f,type:V??f.type}}),[C,p==null?void 0:p.slots]),B=y.useMemo(()=>Rr({slots:p==null?void 0:p.slots,cards:E,minInputs:g}),[p==null?void 0:p.slots,E,g]),S=y.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 M(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 T=f.match(/^(\d+)\+$/);return T?`Tabs ${Number(T[1])+1}+`:`Tab ${f}`}function w(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function D(f,k,T=[],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:H=>{A({key:k,value:H,settingsField:O,settingsValue:P,sourceCard:_})}},k):f==="select"?e.jsx(nt,{className:"h-8 w-full",label:"",options:T,value:String(z!==void 0?z:V??""),onValueChange:H=>{A({key:k,value:H,settingsField:O,settingsValue:P,sourceCard:_})}}):null}function I({key:f,defaultValue:k,settingsValue:T,sourceCard:V}){const O=T==null?void 0:T[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 A({key:f,value:k,settingsField:T,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||{},[T]:P})}function j({settingsSchema:f,settingsField:k,settingsValue:T,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 H;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}),((H=z.docs)==null?void 0:H.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,T,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:M(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:[w(f.expectedType)&&e.jsxs("span",{children:["Expected: ",w(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:l||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=S>=0?S:0,T=m?"Slot 0":`Slot ${k}`;return f?`${T}: ${f} Settings`:`${T} 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(nt,{icon:e.jsx(In,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(d==null?void 0:d.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:o&&e.jsx(nt,{icon:e.jsx(pa,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.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),T=o==null?void 0:o.find(O=>O.name===f);i({...s,componentName:f,visualType:(k==null?void 0:k.visualType)||(T==null?void 0:T.type)||"single",minInputs:k==null?void 0:k.minInputs,maxInputs:k==null?void 0:k.maxInputs,pluginChartType:k==null?void 0:k.chartType})}})})]})})]}),((d==null?void 0:d.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:Or,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((T,V)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:T})]},V))})]})})()]})})]})]})}),e.jsx(t.AccordionContent,{children:R()})]})]})}function Pr({colorRanges:s,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(l,d,o){const u=[...s];u[l]={...u[l],[d]:o},a(u)}function c(l){const d=[...s];d.splice(l,1),a(d)}function i(){a([...s,n])}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((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:o=>r(d,"color",o.target.value),value:l.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:()=>c(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(t.X,{className:"size-3"})})]},d))]})}function Br(){var p,x,h,m,g;const s=t.useEditorStore(v=>v.card.preferences),a=t.useEditorStore(v=>v.actions.setCardPreferences),n=t.useEditorStore(v=>v.card),r=t.hasValidCardConfig(n.config),c=t.useEditorStore(v=>v.actions.setNumberFormat);t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.decimalPlaces});const i=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.locale}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.currency});t.useEditorStore(v=>v.actions.setFilterOnClickField);const d=t.useEditorStore(v=>{var b,C;return(C=(b=v.card.preferences)==null?void 0:b.formatNumber)==null?void 0:C.colorRanges})||[],o=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=>{a({...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,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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:l||"none",onValueChange:v=>{var b,C,E;console.log("currency",v),c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,v==="none"?"":v,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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,C,E;return c(Number(v),((b=s==null?void 0:s.formatNumber)==null?void 0:b.currency)||"",((C=s==null?void 0:s.formatNumber)==null?void 0:C.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,C,E;return c(((b=s==null?void 0:s.formatNumber)==null?void 0:b.decimalPlaces)||0,((C=s==null?void 0:s.formatNumber)==null?void 0:C.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(Pr,{colorRanges:d,setColorRanges:o})]})]})}const Vr={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 qn(s){return Vr[s]}function zr({chartType:s,showDocsLink:a=!0}){const n=qn(s);return n?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:n.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:n.fields.map((r,c)=>e.jsxs("tr",{className:c<n.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:n.description}),a&&n.docsUrl&&e.jsxs("a",{href:n.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 _r({chartType:s}){return qn(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(zr,{chartType:s})})]}):null}function _t({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:a}),e.jsx(_r,{chartType:s})]})}function qr(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(_t,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Br,{})})]})}function pn({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function $n(){const[s,a]=y.useState([]),n=t.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:c}=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}),y.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function l(u,p){var x,h;p?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?c({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):c({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(c({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(m=>m.columnIndex!==u)}),a(m=>{const g=[...m];return g[u]=!1,g}))}function d(u,p){var h;const x=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(m=>m.columnIndex===u?{...m,expression:p.target.value}:m);c({...n,onClickFilter:x})}function o(u){var p,x,h,m;if(s!=null&&s[u]||(x=(p=n==null?void 0:n.onClickFilter)==null?void 0:p.find(g=>g.columnIndex===u))!=null&&x.expression)return e.jsx(t.Input,{value:(m=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(g=>g.columnIndex===u))==null?void 0:m.expression,onChange:g=>d(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=n==null?void 0:n.onClickFilter)!=null&&x.find(m=>m.columnIndex===p)),onCheckedChange:m=>l(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=n==null?void 0:n.onClickFilter)==null?void 0:h.find(m=>m.columnIndex===p))&&e.jsx(t.Pencil,{onClick:()=>{a(m=>{const g=[...m];return g[p]=!m[p],g})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},u)})})}const $r=[{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"}],Kr=["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"],Gr=Kr.map(s=>({label:s,value:s}));function Ur(){var o,u,p,x,h,m,g,v,b,C,E,B,S,M,w,D,I,A;const s=t.useEditorStore(j=>j.card),a=(u=(o=s==null?void 0:s.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=y.useState(((x=(p=s==null?void 0:s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:c}=t.useEditorActions(),{data:i}=t.useTopoJson(s),l=Object.keys((i==null?void 0:i.objects)||{}).map(j=>({label:j,value:j}))||[],d=[{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(pn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(nt,{className:"h-9",options:d,onValueChange:j=>{console.log("value",j),c({...s.preferences,mapVisualOptions:{topoJsonUrl:j}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:j=>{r(j.target.value)},onBlur:()=>{var j;console.log("onBlur",n),c({...s.preferences,mapVisualOptions:{...(j=s.preferences)==null?void 0:j.mapVisualOptions,customTopoJsonUrl:n}})},value:n,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(nt,{className:"h-9",options:l,value:((m=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:m.objectKey)||"",label:"Map Object",onValueChange:j=>{var R;c({...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(nt,{className:"h-9",options:$r,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projection)||"",label:"Projection",onValueChange:j=>{var R;c({...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(nt,{className:"h-9",options:Gr,value:((C=(b=s.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:C.colorScale)||"",label:"Select Color Scale",onValueChange:j=>{var R;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,colorScale:j}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(pn,{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;c({...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:((w=(M=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:w[0])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[Number(j.target.value),((F=(L=(N=s.preferences)==null?void 0:N.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:((A=(I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:A[1])||0,onChange:j=>{var R,N,L,F;c({...s.preferences,mapVisualOptions:{...(R=s.preferences)==null?void 0:R.mapVisualOptions,projectionOffset:[((F=(L=(N=s.preferences)==null?void 0:N.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($n,{})]})}function Kn({color:s,onColorChange:a,onClose:n}){const[r,c]=y.useState(0),[i,l]=y.useState(100),[d,o]=y.useState(50),[u,p]=y.useState(s);y.useEffect(()=>{const b=fn(s);if(b){const C=gn(b.r,b.g,b.b);c(C.h),l(C.s),o(C.l),p(s)}},[s]);const x=b=>{c(b),m(b,i,d)},h=b=>{const C=b.currentTarget.getBoundingClientRect(),E=Math.max(0,Math.min(1,(b.clientX-C.left)/C.width)),B=Math.max(0,Math.min(1,(b.clientY-C.top)/C.height)),S=E*100,M=(1-B)*100;l(S),o(M),m(r,S,M)},m=(b,C,E)=>{const B=Qr(b,C,E),S=Hr(B.r,B.g,B.b);p(S)},g=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const C=fn(b);if(C){const E=gn(C.r,C.g,C.b);c(E.h),l(E.s),o(E.l)}}},v=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};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-d}%`,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:n,children:"Cancel"}),e.jsx(t.Button,{onClick:v,children:"OK"})]})]})}function fn(s){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Hr(s,a,n){return"#"+((1<<24)+(s<<16)+(a<<8)+n).toString(16).slice(1)}function gn(s,a,n){s/=255,a/=255,n/=255;const r=Math.max(s,a,n),c=Math.min(s,a,n);let i=0,l=0;const d=(r+c)/2;if(r!==c){const o=r-c;switch(l=d>.5?o/(2-r-c):o/(r+c),r){case s:i=((a-n)/o+(a<n?6:0))/6;break;case a:i=((n-s)/o+2)/6;break;case n:i=((s-a)/o+4)/6;break}}return{h:Math.round(i*360),s:Math.round(l*100),l:Math.round(d*100)}}function Qr(s,a,n){s/=360,a/=100,n/=100;let r,c,i;if(a===0)r=c=i=n;else{const l=(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),d=n<.5?n*(1+a):n+a-n*a,o=2*n-d;r=l(o,d,s+1/3),c=l(o,d,s),i=l(o,d,s-1/3)}return{r:Math.round(r*255),g:Math.round(c*255),b:Math.round(i*255)}}const jn=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],Jr=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function at({value:s,onChange:a,label:n}){const[r,c]=y.useState(!1),[i,l]=y.useState(!1),d=()=>{const o=jn.find(u=>u.value===s);return o?o.color:s.startsWith("#")?s:jn[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:c,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:d()},"aria-label":`Change color for ${n}`})}),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:Jr.map(o=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{a(o),c(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),c(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),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:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Kn,{color:d(),onColorChange:o=>{a(o),l(!1)},onClose:()=>l(!1)})})]})]})}function Bt(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function bn(s,a){if(!a||a==="auto")return{type:"auto"};const n={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0?is(n,Bt(a)):n}function is(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Yr=["auto","number","currency","percent","scientific","date"],Wr=[{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"}],Xr=[{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"}],Zr=s=>s.charAt(0).toUpperCase()+s.slice(1);function jt({formatOptions:s={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=s.type||"auto",i=c==="auto"?s:bn(s,c),l=m=>{m.stopPropagation()},d=(m,g)=>{a({...i,[m]:g})},[o,u]=y.useState(()=>String(i.decimalPlaces??Bt(c))),[p,x]=y.useState(()=>i.multiplyBy!==void 0?String(i.multiplyBy):""),h=m=>{a(bn(s,m))};return y.useEffect(()=>{u(String(i.decimalPlaces??Bt(c)))},[i.decimalPlaces,c]),y.useEffect(()=>{x(i.multiplyBy!==void 0?String(i.multiplyBy):"")},[i.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(t.Select,{value:c,onValueChange:m=>h(m),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Yr.map(m=>e.jsx(t.SelectItem,{value:m,className:"text-xs",children:m==="auto"?"Auto (Default)":Zr(m)},m))})]})]}),c!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(c)&&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:o,onClick:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^\d]/g,"");u(g),g!==""&&a(is(i,Math.max(0,Math.min(10,parseInt(g,10)))))},onBlur:()=>{if(o!=="")return;const m=Bt(c);u(String(m)),a(is(i,m))},className:"h-8 text-xs"})})]}),c==="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=>d("currency",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),["number","currency"].includes(c)&&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=>d("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=>d("locale",m),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:l,onPointerDown:l,onKeyDown:l,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xr.map(m=>e.jsx(t.SelectItem,{value:m.value,className:"text-xs",children:m.label},m.value))})]})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("prefix",m.target.value),className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("suffix",m.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(c)&&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=>d("negativeInParentheses",m)})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>{const g=m.target.value.replace(/[^0-9.]/g,"");x(g),d("multiplyBy",g?parseFloat(g):void 0)},className:"h-8 text-xs"})})]}),c==="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:l,onPointerDown:l,onKeyDown:l,onChange:m=>d("dateFormat",m.target.value),className:"h-8 text-xs"})})]})]})]})}function hs({value:s,onChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const c=t.toTFormatOptions(t.fromSemanticFormat(s))||{},i=l=>{a(t.fromTFormatOptions(l))};return e.jsx(jt,{formatOptions:c,onFormatOptionsChange:i,showTitle:n,title:r})}function el(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{dashboardFilterableFields:r}=t.useFilterableFields(),{assignFilter:c}=t.useAssignFilter();function i(d){const o=c(d,"frame");n({...a,filterId:o})}const l=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(tl,{onSelect:i,columns:r}),l&&e.jsx(t.FilterHeader,{filter:l})]})}function tl({columns:s,onSelect:a}){var d;const[n,r]=Pt.useState(!1),[c,i]=Pt.useState(""),l=Pt.useCallback(o=>[o.label,o.name,o.qualifiedEntityName].filter(Boolean).join(" "),[]);return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[c?((d=s.find(o=>o.id===c))==null?void 0:d.label)||c:"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(o=>e.jsxs(t.CommandItem,{value:l(o),onSelect:()=>{const u=o.id===c?"":o.id;i(u),r(!1),u&&a(o)},children:[o.label||o.name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",c===o.id?"opacity-100":"opacity-0")})]},o.id))})]})]})})]})}const sl=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],nl=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function al({cardType:s="table"}){var p,x,h,m,g;const a=t.useEditorStore(v=>v.card),n=t.useEditorStore(v=>{var b;return(b=v.card)==null?void 0:b.preferences}),r=t.useEditorStore(v=>v.actions.setCardPreferences),c=((p=a.config)==null?void 0:p.metricColumns)||[],i=c.some(v=>v.comparisonType&&v.comparisonType!=="none"),l=((x=n==null?void 0:n.tableVisualOptions)==null?void 0:x.metricComparison)||{},d=v=>{r({...n,tableVisualOptions:{...n==null?void 0:n.tableVisualOptions,metricComparison:{...l,...v}}})},o={increase:((h=l.colors)==null?void 0:h.increase)||"green",decrease:((m=l.colors)==null?void 0:m.decrease)||"red",neutral:((g=l.colors)==null?void 0:g.neutral)||"neutral"},u=v=>{r({...n,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(kn,{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:l.calculatedAs||"change_difference",onValueChange:v=>d({calculatedAs:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:sl.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:l.formatOptions||{},onFormatOptionsChange:v=>d({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:l.indicatorStyle||"arrow_badge",onValueChange:v=>d({indicatorStyle:v}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:nl.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(at,{value:o.increase,onChange:v=>d({colors:{...o,increase:v}}),label:"Increase"}),e.jsx(at,{value:o.decrease,onChange:v=>d({colors:{...o,decrease:v}}),label:"Decrease"}),e.jsx(at,{value:o.neutral,onChange:v=>d({colors:{...o,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:l.lowerIsBetter||!1,onCheckedChange:v=>d({lowerIsBetter:!!v})})]})]})]}),c.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:c.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 C=(((E=a.config)==null?void 0:E.metricColumns)||[]).map(B=>B.id===v.id?{...B,format:b}:B);t.useEditorStore.getState().actions.updateCardConfig(a.id,{metricColumns:C})},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($n,{}),e.jsx(el,{})]})]})]}),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 rl(){var r;const s=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:a}=t.useEditorStore(c=>c.actions);function n(c){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:c==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,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 ll(){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(rl,{})]})]})}const ol=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function il(){var M,w,D,I,A,j,R,N,L,F;const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var k;return(k=f.card)==null?void 0:k.preferences}),n=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions(),i=y.useMemo(()=>n!==s.type?{...s,type:n}:s,[s,n]),{data:l}=t.useEditorCardQuery(i),[d,o]=y.useState({}),[u,p]=y.useState(null),[x,h]=y.useState(null),m=y.useMemo(()=>{var V,O,P,_,z,H,X;if(!(l!=null&&l.records)||l.records.length===0)return[];const f=n==="stackedBar"||n==="stackedLine",k=n==="bar"||n==="line"||n==="horizontalBar"||n==="bullet"||n==="combo"||n==="area"||n==="stackedArea",T=((V=s==null?void 0:s.config)==null?void 0:V.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||k)&&T){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const K=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&K.add(Z.alias)}),Array.from(K)}if(l.records.length>0){const K=l.records[0],Z=Object.keys(K),se=new Set;(O=s==null?void 0:s.config)!=null&&O.groupByColumns&&s.config.groupByColumns.forEach(te=>{se.add(te.label||te.name),se.add(te.alias||te.name)});const me=new Set;return(P=s==null?void 0:s.config)!=null&&P.metricColumns&&s.config.metricColumns.forEach(te=>{const ne=te.alias||te.name;me.add(ne),me.add(`${ne}_count`),me.add(`${ne}_sum`),me.add(`${ne}_avg`),me.add(`${ne}_min`),me.add(`${ne}_max`);const ue=te.entityName||te.qualifiedEntityName;ue&&(me.add(`${ue}_${ne}`),me.add(`${ue}_${ne}_count`))}),Z.filter(te=>!se.has(te)&&!me.has(te))}}if((k||f)&&!T&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(K=>K.alias||K.label||K.name);if((X=(H=s==null?void 0:s.config)==null?void 0:H.groupByColumns)!=null&&X.length){const K=s.config.groupByColumns[0],Z=K.label||K.name,se=new Set;return l.records.forEach(me=>{const je=me[Z];je!=null&&se.add(String(je))}),Array.from(se)}return[]},[l,(M=s==null?void 0:s.config)==null?void 0:M.groupByColumns,(w=s==null?void 0:s.config)==null?void 0:w.pivotByColumns,(D=s==null?void 0:s.config)==null?void 0:D.metricColumns,n]),g=y.useMemo(()=>t.getDefaultChartColors(),[]);y.useEffect(()=>{const f={};m.forEach((k,T)=>{f[k]=t.getColorForValue(k,T,a==null?void 0:a.colorConfig)}),o(f)},[m,a==null?void 0:a.colorConfig,g]);const v=(f,k)=>{const T={...d,[f]:k};o(T);const V={...a||{},colorConfig:{segments:T}};r(V);const O={...s,preferences:V};c(O)},b=(f,k)=>{var z;const T=g[k%g.length],{[f]:V,...O}=((z=a==null?void 0:a.colorConfig)==null?void 0:z.segments)||{},P={...a||{},colorConfig:{segments:O}};r(P);const _={...s,preferences:P};c(_),o(H=>({...H,[f]:T}))};if(!m.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((A=(I=s==null?void 0:s.config)==null?void 0:I.groupByColumns)==null?void 0:A.length)||((R=(j=s==null?void 0:s.config)==null?void 0:j.pivotByColumns)==null?void 0:R.length):(L=(N=s==null?void 0:s.config)==null?void 0:N.groupByColumns)==null?void 0:L.length)||["table","kpi","text","custom","heatmap"].includes(n))return null;const B=()=>{const f={...a||{},colorConfig:{segments:{}}};r(f);const k={...s,preferences:f};c(k);const T={};m.forEach((V,O)=>{T[V]=t.getColorForValue(V,O,void 0)}),o(T)},S=Object.keys(((F=a==null?void 0:a.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(Ca,{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:S&&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 T=t.isDefaultColor(d[f],k),V=!T;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:d[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",d[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:ol.map((O,P)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[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:d[f]}),p(null)},children:"Custom color"}),!T&&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(Kn,{color:x.color,onColorChange:f=>{v(x.value,f),h(null)},onClose:()=>h(null)})})]})]})})]})}function He({value:s,onSave:a,placeholder:n="",type:r="text",className:c=""}){const[i,l]=y.useState(s??""),[d,o]=y.useState(!1);y.useEffect(()=>{l(s??"")},[s]);const u=()=>{a(i),o(!1)},p=()=>{l(s??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${c}`,children:[e.jsx(t.Input,{placeholder:n,type:r,value:d?i:s??"",onChange:x=>{l(x.target.value),o(!0)},onFocus:()=>o(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&d&&i!==s?u():x.key==="Escape"&&p()},"aria-label":n||"Edit field"}),d&&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:a,type:n,config:r,onChange:c,defaultTitle:i,hidePosition:l}){var g,v,b,C,E,B,S,M,w,D,I,A,j,R;const d=t.normalizeContextFormatMode({formatMode:r==null?void 0:r.formatMode,formatOptions:r==null?void 0:r.formatOptions}),o=(N,L)=>{c({...r??{},[N]:L})},u=(N,L)=>{var T,V,O,P;const F=N==="enabled"&&L===!0,f=(T=r==null?void 0:r.name)==null?void 0:T.text,k=F&&!f&&i;c({...r??{},name:{...r==null?void 0:r.name,enabled:N==="enabled"?L:((V=r==null?void 0:r.name)==null?void 0:V.enabled)??!1,text:N==="text"?L:k?i:f,fontSize:N==="fontSize"?L:(O=r==null?void 0:r.name)==null?void 0:O.fontSize,fontWeight:N==="fontWeight"?L:(P=r==null?void 0:r.name)==null?void 0:P.fontWeight}})},p=(N,L)=>{var F,f;c({...r??{},labels:{enabled:N==="enabled"?L:((F=r==null?void 0:r.labels)==null?void 0:F.enabled)??!0,rotation:N==="rotation"?L:(f=r==null?void 0:r.labels)==null?void 0:f.rotation}})},x=(N,L)=>{c({...r??{},scale:{...r==null?void 0:r.scale,[N]: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:a})})}),e.jsx(t.Switch,{size:"sm",checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:N=>o("enabled",N),onClick:N=>N.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:N=>u("enabled",N===!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:`${a} title`,value:((b=r==null?void 0:r.name)==null?void 0:b.text)||"",onSave:N=>u("text",N),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(((C=r==null?void 0:r.name)==null?void 0:C.fontSize)||12),onSave:N=>u("fontSize",Number(N)||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:N=>u("fontWeight",N),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"})]})]})]})]})]})]}),!l&&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:N=>o("position",N),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":t.titleCase(N)},N))})]})]}),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:N=>p("enabled",N)})]}),((S=r==null?void 0:r.labels)==null?void 0:S.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(((M=r==null?void 0:r.labels)==null?void 0:M.rotation)||"auto"),onValueChange:N=>p("rotation",N==="auto"?"auto":Number(N)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(N=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:N==="auto"?"Auto (Default)":`${N}°`},N))})]})]})]}),n==="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:d==="override",onCheckedChange:N=>c({...r,formatMode:N?"override":"inherit"})})]}),d==="override"&&e.jsx(jt,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:N=>c({...r,formatMode:"override",formatOptions:N}),showTitle:!1})]}),n==="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:((w=r==null?void 0:r.scale)==null?void 0:w.min)==="auto"||((D=r==null?void 0:r.scale)==null?void 0:D.min)===void 0?"":String(r.scale.min),onSave:N=>x("min",N),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"||((A=r==null?void 0:r.scale)==null?void 0:A.max)===void 0?"":String(r.scale.max),onSave:N=>x("max",N),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:N=>x("stepSize",N),className:""})})]})]})]})]})]})}function ns(s,a,n){var i,l,d;if(s==="x"){const o=(l=(i=a==null?void 0:a.config)==null?void 0:i.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=a==null?void 0:a.config)==null?void 0:d.metricColumns)||[],c=(n==null?void 0:n.datasetOptions)||[];if(s==="y"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return!x||x.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(s==="y2"){const o=r.filter((u,p)=>{const x=c.find(h=>h.idx===p);return(x==null?void 0:x.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function cl(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),{setCardPreferences:n,updateCardInFrame:r}=t.useEditorActions(),c=De.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(c))return null;const i=t.AxisConfigurator.getAxisInfo(c,a);if(!i.hasXAxis&&!i.hasYAxis)return null;const l=(o,u)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const x={...a||{},[p]:u};n(x);const h={...s,preferences:x};r(h)},d=i.hasY2Axis&&c==="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(c,"x"),a==null?void 0:a.xAxisConfig),onChange:o=>l("x",o),defaultTitle:ns("x",s,a)}),i.hasYAxis&&e.jsx(ss,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:i.yAxisType,config:t.mergeAxisConfig(t.getDefaultAxisConfig(c,"y"),a==null?void 0:a.yAxisConfig),onChange:o=>l("y",o),defaultTitle:ns("y",s,a)}),d&&e.jsx(ss,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:t.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:ns("y2",s,a),hidePosition:!0})]})})]})}function dl(){const s=t.useEditorStore(x=>x.card),a=De.useEffectiveEditorCardType(),n=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(a))return null;const c=t.getDefaultLegendConfig(a),i=(c==null?void 0:c.display)??!0,l=(c==null?void 0:c.position)??"top",d=(c==null?void 0:c.align)??"center",o=(x,h)=>{const m={...n,[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(ba,{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:(n==null?void 0:n.display)??i,onCheckedChange:x=>o("display",x)})]}),((n==null?void 0:n.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:(n==null?void 0:n.position)||l,onValueChange:x=>o("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:(n==null?void 0:n.align)||d,onValueChange:x=>o("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 ul(){var L,F,f,k,T,V,O;const s=t.useEditorStore(P=>P.card),a=De.useEffectiveEditorCardType(),n=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:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!t.chartSupportsDataLabels(a))return null;const l=a==="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,d=l!=null?l==="horizontal":((f=r==null?void 0:r.chartOptions)==null?void 0:f.indexAxis)==="y",o=a==="stackedBar"||a==="stackedLine",u=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",p=a==="bubble"||a==="scatter",x=(T=(k=r==null?void 0:r.chartOptions)==null?void 0:k.plugins)==null?void 0:T.datalabels,h=(x==null?void 0:x.display)!==!1&&((x==null?void 0:x.anchor)||(x==null?void 0:x.align)),m=t.getDefaultDataLabelsConfig(a,s.preferences),g=n??m,v=(m==null?void 0:m.enabled)??h??!1,b=(n==null?void 0:n.enabled)!==void 0?n.enabled:v,C=(P,_)=>{const X={...m??{},...n??{},[P]:_};P==="enabled"&&(X.display=_,_&&p&&!X.position&&(X.position="bottom")),P==="position"&&p&&(X.position="bottom"),P==="formatMode"&&_==="inherit"&&(X.format=void 0,X.formatOptions=void 0);const K={...s.preferences||{},dataLabelsConfig:X};c(K);const Z={...s,preferences:K};i(Z)},E=(P,_)=>{const z=n??{},X={...m??{},...z,font:{...z.font||{},[P]:_}},K={...s.preferences||{},dataLabelsConfig:X};c(K);const Z={...s,preferences:K};i(Z)},B=()=>{const P=a;return P==="stackedBar"||P==="stackedLine"||P==="pie"||P==="doughnut"?"center":d?"right":"top"},S=a!=="treemap"&&a!=="heatmap",M=a!=="treemap",w=B();let D=[];if(S)if(p)D=["bottom"];else if(o||u)D=["center"];else{const P=d?["center","left","right"]:["center","top","bottom"];D=["auto",...a==="bullet"?P:P.filter(z=>z!==w),"custom"]}const I=()=>t.titleCase(w),A=["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"),N=(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(Ma,{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=>C("enabled",P)})]}),b&&e.jsxs(e.Fragment,{children:[S&&!o&&!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=>C("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))})]})]}),o&&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:(n==null?void 0:n.showTotal)??!1,onCheckedChange:P=>C("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=>C("anchor",P),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.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=>C("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=>C("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:N,onCheckedChange:P=>{const _=n??{},H={...m??{},..._,formatMode:"override",format:P?"none":void 0,formatOptions:P?void 0:_.formatOptions},X={...s.preferences||{},dataLabelsConfig:H};c(X),i({...s,preferences:X})}})]}),!N&&e.jsx(jt,{formatOptions:(g==null?void 0:g.formatOptions)||{},onFormatOptionsChange:P=>{const H={...m??{},...n??{},formatMode:"override",format:P.type&&P.type!=="auto"?P.type:void 0,formatOptions:P},X={...s.preferences||{},dataLabelsConfig:H};c(X),i({...s,preferences:X})},showTitle:!1})]})]}),M&&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"&&C("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=>C("rotation",Number(P)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const vn={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%
|
|
183
|
+
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 ml(){var h,m,g,v,b,C,E,B,S,M;const s=t.useEditorStore(w=>w.card),{setCardPreferences:a}=t.useEditorActions(),n=De.useEffectiveEditorCardType(),r=((h=s.config)==null?void 0:h.metricColumns)||[],c=((m=s.config)==null?void 0:m.groupByColumns)||[],i=r.length===2&&c.length===0,l=r.some(w=>w.comparisonType&&w.comparisonType!=="none");if(!(n==="kpi"&&(i||l)))return null;const o=((v=(g=s.preferences)==null?void 0:g.kpiVisualOptions)==null?void 0:v.metricComparison)||{},u=w=>{var I;const D={...s.preferences,kpiVisualOptions:{...(I=s.preferences)==null?void 0:I.kpiVisualOptions,metricComparison:{...o,...w}}};a(D)},p=l||o.enabled,x=r.some(w=>w.comparisonType==="previous_period"||w.comparisonType==="same_period_last_year"||w.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(kn,{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:o.enabled||!1,onCheckedChange:w=>u({enabled:w,...w&&!o.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 w=o.calculationType||"difference",D=vn[w];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:o.calculationType||"difference",onValueChange:w=>u({calculationType:w}),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(vn).map(([w,D])=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:D.label},w))})]})]}),e.jsx(jt,{formatOptions:o.formatOptions||{},onFormatOptionsChange:w=>u({formatOptions:w}),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:o.position||"right",onValueChange:w=>u({position:w}),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:o.showArrow!==!1,onCheckedChange:w=>u({showArrow:w})}),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:o.showColor!==!1,onCheckedChange:w=>u({showColor:w})}),e.jsx(t.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(at,{value:((b=o.colorConfig)==null?void 0:b.increase)||"green",onChange:w=>u({colorConfig:{...o.colorConfig,increase:w}}),label:"Primary > Secondary"}),e.jsx(at,{value:((C=o.colorConfig)==null?void 0:C.decrease)||"red",onChange:w=>u({colorConfig:{...o.colorConfig,decrease:w}}),label:"Primary < Secondary"}),e.jsx(at,{value:((E=o.colorConfig)==null?void 0:E.noChange)||"neutral",onChange:w=>u({colorConfig:{...o.colorConfig,noChange:w}}),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:o.conditionalLabel||!1,onCheckedChange:w=>u({conditionalLabel:w})}),e.jsx(t.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(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=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,increase:w.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:((S=o.conditionalLabels)==null?void 0:S.decrease)??"Decrease",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,decrease:w.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:((M=o.conditionalLabels)==null?void 0:M.noChange)??"No change",onChange:w=>u({conditionalLabels:{...o.conditionalLabels,noChange:w.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:o.labelName??"",onChange:w=>u({labelName:w.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function xl(){var i;const s=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),a=t.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:n}=t.useEditorActions();if(s!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",c=l=>{const d={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:l}};n(d)};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:l=>c(l??"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 hl=Object.keys(t.HEATMAP_PRESET_PALETTES);function pl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="heatmap",c=(a==null?void 0:a.heatmapConfig)||{},i=c.colorPalette??"green",l=c.legendPosition??"bottom",d=y.useMemo(()=>c.colorRange&&c.colorRange[0]&&c.colorRange[1]?[c.colorRange[0],c.colorRange[1]]:[...t.DEFAULT_HEATMAP_CUSTOM_RANGE],[c.colorRange]),o=h=>{const m={...c,...h};m.colorPalette!=="custom"?delete m.colorRange:(!m.colorRange||!m.colorRange[0]||!m.colorRange[1])&&(m.colorRange=[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:m})},u=h=>{o({colorPalette:h,colorRange:h==="custom"?c.colorRange??[...t.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(h,m)=>{const g=[...d];g[h]=m,o({colorPalette:"custom",colorRange:g})},x=h=>{o({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:[hl.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(at,{value:d[0],onChange:h=>p(0,h),label:"Start color"}),e.jsx(at,{value:d[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:l,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 yn=["poor","satisfactory","good"];function Nn(s){if(!s)return;const a={...s};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function fl(){var L,F;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:r,setChartOrientation:c}=t.useEditorActions(),i=y.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),d=t.hasValidCardConfig(a==null?void 0:a.config)&&!n,[o,u]=y.useState(i.showRanges??!1),[p,x]=y.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d,[m,g]=y.useState(h);y.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),y.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const v=i.targetValue===void 0?"":String(i.targetValue);y.useEffect(()=>{const f=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!d;g(f)},[i.disableAutoComparative,i.comparativeMetricKey,d]);const b=y.useMemo(()=>{var f,k;return((k=(f=a==null?void 0:a.config)==null?void 0:f.metricColumns)==null?void 0:k.map(T=>{const V=T.label||T.name||T.alias||"";return{value:V,label:V}}))||[]},[(L=a==null?void 0:a.config)==null?void 0:L.metricColumns]);y.useEffect(()=>{var z,H;if(!s||b.length===0)return;const f={};let k=!1;const T=(z=b[1])==null?void 0:z.value;!i.targetMetricKey&&T&&(f.targetMetricKey=T,k=!0);const V=(H=b[2])==null?void 0:H.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&V&&(f.comparativeMetricKey=V,k=!0);const O=b.slice(3),P={...i.rangeKeys||{}};let _=!1;if(yn.forEach((X,K)=>{!P[X]&&O[K]&&(P[X]=O[K].value,_=!0)}),_&&(f.rangeKeys=P,k=!0,i.showRanges===void 0&&(f.showRanges=!0)),k){const X=Nn({...i,...f});r({...s,bulletConfig:X})}},[b,i,s,r]);const C=f=>{const k=Nn({...i,...f});r({...s,bulletConfig:k})},E=(f,k)=>{const T={...i.rangeKeys||{},[f]:k.trim()};k.trim()||delete T[f],C({rangeKeys:Object.keys(T).length>0?T:void 0})},B=(f,k)=>{const T=k===""?void 0:Number(k),V={...i.ranges||{}};T===void 0||Number.isNaN(T)?delete V[f]:V[f]=T,C({ranges:Object.keys(V).length?V:void 0})},S=f=>{if(f===""){C({targetValue:void 0});return}const k=Number(f);C({targetValue:Number.isNaN(k)?void 0:k})},M=(f,k)=>{const T=k.trim(),V={...i.rangeLabels||{}};T?V[f]=T:delete V[f],C({rangeLabels:Object.keys(V).length>0?V:void 0})},w=f=>{u(f),C({showRanges:f})},D=f=>{x(f),C({rangesArePercentages:f})},I=i.orientation||(((F=s==null?void 0:s.chartOptions)==null?void 0:F.indexAxis)==="y"?"horizontal":"vertical"),A=f=>{C({orientation:f}),c(f==="horizontal"?"y":"x")},j=[{value:"__none",label:"None"},...b.map(f=>({value:f.value,label:f.label}))],R=j,N=f=>{if(g(f),!f){C({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){C({disableAutoComparative:!1});return}if(i.comparativeMetricKey)C({disableAutoComparative:!1});else{const k=b.find(T=>T.value!==i.targetMetricKey);C({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=>A(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"})]})]})]}),d&&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=>C({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"}),d?e.jsxs(t.Select,{value:i.comparativeMetricKey||"__none",onValueChange:f=>C({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=>N(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:S,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:o,onCheckedChange:w})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,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"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:yn.map(f=>{var k,T,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:_=>M(f,_),className:"h-8 text-xs"})]}),d?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:((T=i.rangeKeys)==null?void 0:T[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 Cn(s){if(!s)return;const a={...s};if(a.xMetricKey||delete a.xMetricKey,a.yMetricKey||delete a.yMetricKey,a.radiusMetricKey||delete a.radiusMetricKey,a.labelKey||delete a.labelKey,a.groupKey||delete a.groupKey,a.enableGrouping===void 0&&delete a.enableGrouping,a.radiusScale||delete a.radiusScale,a.fixedRadius===void 0&&delete a.fixedRadius,a.minRadius===void 0&&delete a.minRadius,a.maxRadius===void 0&&delete a.maxRadius,Object.keys(a).length!==0)return a}function gl(){var M,w,D,I,A,j,R,N,L,F,f,k;const s=t.useEditorStore(T=>T.card.preferences),a=t.useEditorStore(T=>T.card),n=De.useEffectiveEditorCardType(),r=t.useEditorStore(T=>T.isDevMode),{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions(),l=n==="bubble",d=n==="scatter",o=y.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),p=t.hasValidCardConfig(a==null?void 0:a.config)&&!r,x=y.useMemo(()=>{var T,V;return((V=(T=a==null?void 0:a.config)==null?void 0:T.metricColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(M=a==null?void 0:a.config)==null?void 0:M.metricColumns]),h=y.useMemo(()=>{var T,V;return((V=(T=a==null?void 0:a.config)==null?void 0:T.groupByColumns)==null?void 0:V.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(w=a==null?void 0:a.config)==null?void 0:w.groupByColumns]),m=y.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&h.length>=2,[o.enableGrouping,r,h.length]),[g,v]=y.useState(m);y.useEffect(()=>{v(m)},[m]);const b=T=>{const V={...s||{},bubbleScatterConfig:T};c(V),a&&i({...a,preferences:V})},C=T=>{c(T),a&&i({...a,preferences:T})};y.useEffect(()=>{if(!s||x.length===0)return;const T={};let V=!1;if(!o.xMetricKey&&x[0]&&(T.xMetricKey=x[0].value,V=!0),!o.yMetricKey&&x[1]&&(T.yMetricKey=x[1].value,V=!0),l&&!o.radiusMetricKey&&x[2]&&(T.radiusMetricKey=x[2].value,V=!0),!o.labelKey&&h[0]&&(T.labelKey=h[0].value,V=!0),m&&!o.groupKey&&h[1]&&(T.groupKey=h[1].value,T.enableGrouping=!0,V=!0),V){const O=Cn({...o,...T});b(O)}},[x,h,o,s,c,l,m]);const E=T=>{const V=Cn({...o,...T});b(V)},B=T=>{v(T),E({enableGrouping:T,groupKey:T?o.groupKey:void 0})};if(!l&&!d)return null;const S=l?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(S,{className:"h-4 w-4"}),e.jsxs("span",{children:[l?"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:o.labelKey||"",onValueChange:T=>E({labelKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:T=>E({labelKey:T})})]}),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:o.groupKey||"",onValueChange:T=>E({groupKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:T=>E({groupKey:T})})]})]}),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:o.xMetricKey||"",onValueChange:T=>E({xMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:T=>E({xMetricKey:T})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(t.Select,{value:o.yMetricKey||"",onValueChange:T=>E({yMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:T=>E({yMetricKey:T})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(t.Select,{value:o.radiusMetricKey||"",onValueChange:T=>E({radiusMetricKey:T}),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(T=>e.jsx(t.SelectItem,{value:T.value,children:T.label},T.value))})]}):e.jsx(qe,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:T=>E({radiusMetricKey:T})})]})]}),l&&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:o.radiusScale||"sqrt",onValueChange:T=>E({radiusScale:T}),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"})]})]})]}),o.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=o.minRadius)==null?void 0:D.toString())||"",onCommit:T=>E({minRadius:T?Number(T):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=o.maxRadius)==null?void 0:I.toString())||"",onCommit:T=>E({maxRadius:T?Number(T):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(t.Slider,{value:[o.fixedRadius||10],onValueChange:([T])=>E({fixedRadius:T}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&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: ",o.fixedRadius||5]}),e.jsx(t.Slider,{value:[o.fixedRadius||5],onValueChange:([T])=>E({fixedRadius:T}),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=(A=s==null?void 0:s.xAxisConfig)==null?void 0:A.name)==null?void 0:j.enabled)??!1,onCheckedChange:T=>{var P,_,z,H;const V=o.xMetricKey||"X Axis",O=o.yMetricKey||"Y Axis";C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:T,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:T,text:((H=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:H.text)||O}}})}})]}),((N=(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name)==null?void 0:N.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:o.xMetricKey||"X Axis",value:((F=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:F.text)||"",onCommit:T=>{var V;C({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(V=s==null?void 0:s.xAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.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:o.yMetricKey||"Y Axis",value:((k=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:k.text)||"",onCommit:T=>{var V;C({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(V=s==null?void 0:s.yAxisConfig)==null?void 0:V.name,enabled:!0,text:T||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const jl=[{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 bl(){const s=t.useEditorStore(h=>h.card),a=t.useEditorStore(h=>{var m;return(m=h.card)==null?void 0:m.preferences}),{setCardPreferences:n}=t.useEditorActions(),r=(s==null?void 0:s.type)==="funnel",c=(a==null?void 0:a.funnelConfig)||{},i=c.percentMode??"percentOfTotal",l=c.shrinkFraction??1,d=c.labelThreshold??0,o=h=>{const m={...c,...h};n({...a||{},funnelConfig:m})},u=h=>{o({percentMode:h})},p=h=>{o({shrinkFraction:h[0]})},x=h=>{o({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:jl.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:[l],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(l*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:[d],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:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function qt(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useEditorCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let c=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:l}=t.getKeys(i);c=l.slice(1)}return{transformedMetricKeys:c,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}const vl=[{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"}],yl=[{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)"}],Nl=["center","start","end"],Cl=["center","start","end","top","bottom"];function $t({config:s,onChange:a,isHorizontal:n=!1,showAutoFormat:r=!0,positionOptions:c,showAppearance:i=!0}){var g,v,b,C,E,B;const l=c??(n?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(S,M)=>{const w={...s,[S]:M};a(w)},u=(S,M)=>{const w={...s,font:{...(s==null?void 0:s.font)||{},[S]:M}};a(w)},p=(S,M)=>{const w={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:M}};a(w)},x=()=>n?"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:S=>o("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?x():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),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:S=>o("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Nl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]}),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:S=>o("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cl.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:t.titleCase(S)},S))})]})]})]}),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:S=>o("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:d.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&r?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["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:S=>p("decimalPlaces",Number(S)),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:S=>p("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:S=>p("useSuffix",S)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((C=h.formatOptions)==null?void 0:C.locale)||"en-US",onValueChange:S=>p("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:yl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.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:S=>u("size",Number(S)),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:S=>u("weight",S),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:S=>{S==="auto"&&o("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:S=>o("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Sl=[{type:"bar",icon:t.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:t.ChartLine,label:"Line"}],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(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(Dl,{})})]})}function Dl(){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((a,n)=>e.jsx(kl,{metricKey:a,idx:n},a))})}function kl({metricKey:s,idx:a}){var C;const[n,r]=y.useState(!1),c=t.useEditorStore(E=>{var B;return(B=E.card)==null?void 0:B.preferences}),i=t.useEditorStore(E=>{var B,S;return(S=(B=E.card)==null?void 0:B.preferences)==null?void 0:S.datasetOptions}),l=i==null?void 0:i.find(E=>E.idx===a),{setCardPreferences:d}=t.useEditorStore(E=>E.actions),o=(l==null?void 0:l.type)||"bar",u=(l==null?void 0:l.yAxisId)||"y",p=((C=l==null?void 0:l.dataLabels)==null?void 0:C.enabled)??!1,x=o==="line"?t.ChartLine:t.ChartColumnIncreasing;function h(E){const B={idx:a,type:o,yAxisId:u,dataLabels:l==null?void 0:l.dataLabels,...E};if(!l)d({...c||{},datasetOptions:[...i||[],B]});else{const S=i==null?void 0:i.map(M=>M.idx===a?{...M,...B}:M);d({...c||{},datasetOptions:S})}}function m(E){h({type:E})}function g(E){h({yAxisId:E})}function v(E){h({dataLabels:{...l==null?void 0:l.dataLabels,enabled:E}})}function b(E){h({dataLabels:E})}return e.jsx(t.Collapsible,{open:n,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",n&&"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"}),o==="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:Sl.map(({type:E,icon:B,label:S})=>{const M=o===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",M?"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:S})]},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)"})]})]})]})]}),o==="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:(l==null?void 0:l.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:El.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((l==null?void 0:l.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:wl.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:(l==null?void 0:l.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:Tl.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:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const as=[{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"}],Al=[0,1,2,3,4,5,6,8,10],Ml=[{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 │"}],Ll=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Fl(s){return s==null?"origin":s===!1?"false":s}function Rl(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(Ol,{})})]})}function Ol(){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((a,n)=>e.jsx(Pl,{metricKey:a,idx:n},a))})}function Pl({metricKey:s,idx:a}){var v;const[n,r]=y.useState(!1),c=t.useEditorStore(b=>{var C;return(C=b.card)==null?void 0:C.preferences}),i=t.useEditorStore(b=>{var C,E;return(E=(C=b.card)==null?void 0:C.preferences)==null?void 0:E.datasetOptions}),l=i==null?void 0:i.find(b=>b.idx===a),{setCardPreferences:d}=t.useEditorStore(b=>b.actions),o=Fl(l==null?void 0:l.fill),u=((v=l==null?void 0:l.dataLabels)==null?void 0:v.enabled)??!1,p=as.find(b=>b.value===o)||as[0];function x(b){const C={idx:a,fill:o,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)d({...c||{},datasetOptions:[...i||[],C]});else{const E=i==null?void 0:i.map(B=>B.idx===a?{...B,...C}:B);d({...c||{},datasetOptions:E})}}function h(b){x({fill:b==="false"?!1:b})}function m(b){x({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function g(b){x({dataLabels:b})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:o,onValueChange:b=>h(b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:as.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:(l==null?void 0:l.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:Ll.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},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((l==null?void 0:l.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:Al.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:(l==null?void 0:l.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:Ml.map(({value:b,label:C})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:C},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:l==null?void 0:l.dataLabels,onChange:g,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const 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 │"}],rs=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function zl(){return t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(_l,{})})]})}function _l(){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((a,n)=>e.jsx(ql,{metricKey:a,idx:n},a))})}function ql({metricKey:s,idx:a}){var b;const[n,r]=y.useState(!1),c=t.useEditorStore(C=>{var E;return(E=C.card)==null?void 0:E.preferences}),i=t.useEditorStore(C=>{var E,B;return(B=(E=C.card)==null?void 0:E.preferences)==null?void 0:B.datasetOptions}),l=i==null?void 0:i.find(C=>C.idx===a),{setCardPreferences:d}=t.useEditorStore(C=>C.actions),o=(l==null?void 0:l.lineStyle)||"solid",u=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",x=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,h=rs.find(C=>C.value===o)||rs[0];function m(C){const E={idx:a,lineStyle:o,pointRadius:u,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...c||{},datasetOptions:[...i||[],E]});else{const B=i==null?void 0:i.map(S=>S.idx===a?{...S,...E}:S);d({...c||{},datasetOptions:B})}}function g(C){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function v(C){m({dataLabels:C})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:o,onValueChange:C=>m({lineStyle:C}),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:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},C))})]})]}),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:C=>m({pointRadius:Number(C)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Bl.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 text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:p,onValueChange:C=>m({pointStyle:C}),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:C,label:E})=>e.jsx(t.SelectItem,{value:C,className:"text-xs",children:E},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 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:l==null?void 0:l.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const $l=[0,2,4,6,8,10,12,16,20];function Kl(){const s=t.useEditorStore(a=>{var n;return(n=a.card)==null?void 0:n.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(Gl,{})})]})}function Gl(){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((a,n)=>e.jsx(Ul,{metricKey:a,idx:n},a))})}function Ul({metricKey:s,idx:a}){var g;const[n,r]=y.useState(!1),c=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}),l=t.useEditorStore(v=>{var b,C;return(C=(b=v.card)==null?void 0:b.preferences)==null?void 0:C.datasetOptions}),d=l==null?void 0:l.find(v=>v.idx===a),{setCardPreferences:o}=t.useEditorStore(v=>v.actions),u=(d==null?void 0:d.borderRadius)??0,p=((g=d==null?void 0:d.dataLabels)==null?void 0:g.enabled)??!1;function x(v){const b={idx:a,borderRadius:u,dataLabels:d==null?void 0:d.dataLabels,...v};if(!d)o({...i||{},datasetOptions:[...l||[],b]});else{const C=l==null?void 0:l.map(E=>E.idx===a?{...E,...b}:E);o({...i||{},datasetOptions:C})}}function h(v){x({dataLabels:{...d==null?void 0:d.dataLabels,enabled:v}})}function m(v){x({dataLabels:v})}return e.jsx(t.Collapsible,{open:n,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",n&&"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:$l.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:d==null?void 0:d.dataLabels,onChange:m,isHorizontal:c==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Hl=[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 │"}],Jl=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yl(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=De.useEffectiveEditorCardType(),r=a==null?void 0:a.lineStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(n))return null;const l=(d,o)=>{const u={...a||{},lineStyleConfig:{...r,[d]:o}};c(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(Da,{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:d=>l("lineStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("pointRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),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:d=>l("pointStyle",d),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Wl=[0,2,4,6,8,10,12,16,20],Xl=[{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%"}],Zl=[{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 eo(){const s=t.useEditorStore(d=>d.card),a=t.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),n=De.useEffectiveEditorCardType(),r=a==null?void 0:a.barStyleConfig,{setCardPreferences:c,updateCardInFrame:i}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(n))return null;const l=(d,o)=>{const u={...a||{},barStyleConfig:{...r,[d]:o}};c(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:d=>l("borderRadius",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(d=>e.jsx(t.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),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:d=>l("barPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),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:d=>l("categoryPercentage",Number(d)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Zl.map(({value:d,label:o})=>e.jsx(t.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function to(){const s=t.useEditorStore(n=>{var r,c;return(c=(r=n==null?void 0:n.card)==null?void 0:r.preferences)==null?void 0:c.sortChart}),{setSortChart:a}=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(nt,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:n=>{a(n)}})]})})]})}const so=["kpi"],Sn={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 no(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const a=t.getDataType(s.dataType);return["date","string","boolean"].includes(a)}function ao(s){return{...s,role:"groupby"}}function ro(){var E,B;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),n=De.useEffectiveEditorCardType(),{scopedFields:r}=t.useScopedFields(),c=((E=s.config)==null?void 0:E.metricColumns)||[],i=((B=s.config)==null?void 0:B.summary)||{},l=i.breakdownDimensions||[],d=so.includes(n),o=c.length>0,u=i.enabled===!0,p=d&&o,{comparisonType:x}=t.getEffectiveComparisonSettings(s.config,n),h=Sn[x]||Sn.none,m=Array.from(new Map(r.filter(no).map(S=>[lt(S),ao(S)])).values()),g=new Set(m.map(S=>lt(S))),v=new Set(l.map(S=>lt(S)).filter(S=>S&&g.has(S)));if(!d)return null;const b=S=>{a(s.id,{summary:{...i,...S}})},C=(S,M)=>{const w=lt(S),D=m.filter(A=>v.has(lt(A))),I=M?v.has(w)?D:[...D,S].slice(0,ls):D.filter(A=>lt(A)!==w);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"}),!o&&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:S=>{if(!S){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:S=>b({showOnCard:S})})]}),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:S=>b({includeInDashboardSummary: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 font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.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(S=>{const M=lt(S),w=v.has(M),D=v.size>=ls,I=!u||!w&&D;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(t.Checkbox,{id:`summary-breakdown-${M}`,checked:w,disabled:I,onCheckedChange:A=>C(S,A===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${M}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},M)})})]}),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:S=>b({anomalyEnabled:S})})]})]})]})}const lo=[];function oo(){var c;const s=t.useEditorStore(i=>i.card),a=((c=s==null?void 0:s.config)==null?void 0:c.metricColumns)??lo,{updateMetricColumn:n,updateCardInFrame:r}=t.useEditorActions();return!s||s.type==="kpi"||a.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(ua.Braces,{className:"h-4 w-4"}),e.jsx("span",{children:"Metric Formats"})]})}),e.jsx(t.AccordionContent,{className:"space-y-4 pt-2",children:a.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:l=>{var d;n(s.id,i.id,{format:l}),r({...s,config:{...s.config,metricColumns:(((d=s.config)==null?void 0:d.metricColumns)||[]).map(o=>o.id===i.id?{...o,format:l}:o)}})}})]},i.id))})]})}const io=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function co(){const s=t.useEditorStore(o=>o.card),a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=De.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:c}=t.useEditorActions();if(!s||!io.has(n||""))return null;const i=a==null?void 0:a.tooltipConfig,l=(i==null?void 0:i.formatMode)||(i==null?void 0:i.mode)||"inherit",d=o=>{const u={...a||{},tooltipConfig:{...i||{},...o}};r(u),c({...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:l==="override",onCheckedChange:o=>d({formatMode:o?"override":"inherit",mode:o?"override":"inherit"})})]}),l==="override"&&e.jsx(jt,{formatOptions:(i==null?void 0:i.formatOptions)||{},onFormatOptionsChange:o=>d({formatMode:"override",mode:"override",formatOptions:o}),showTitle:!1})]})]})}function Gn({mode:s}){const a=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Il,{}),(a==="area"||a==="stackedArea")&&e.jsx(Rl,{}),a==="line"&&e.jsx(zl,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(Kl,{}),e.jsx(Yl,{}),e.jsx(eo,{}),e.jsx(xl,{}),s==="config"&&e.jsx(ml,{}),s==="config"&&e.jsx(ro,{}),e.jsx(pl,{}),a==="bullet"&&e.jsx(fl,{}),a==="funnel"&&e.jsx(bl,{}),(a==="bubble"||a==="scatter")&&e.jsx(gl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(to,{}),e.jsx(oo,{}),e.jsx(il,{}),e.jsx(cl,{}),e.jsx(dl,{}),e.jsx(ul,{}),e.jsx(co,{})]})}function uo(){const s=t.useEditorStore(n=>n.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(_t,{chartType:a}),e.jsx(t.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Gn,{mode:"dev"})})]}):null}function mo(){const s=t.useEditorStore(c=>c.card),a=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(a){case"kpi":return e.jsx(qr,{});case"table":return e.jsx(al,{});case"map":return e.jsx(Ur,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(_n,{})});case"text":return e.jsx(ll,{});default:return e.jsx(uo,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[r(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function xo(){const s=y.useRef(null),a=y.useRef(null),n=t.useEditorStore(x=>x.isShowingVisual),r=t.useEditorStore(x=>x.isDevMode),c=t.useEditorStore(x=>x.showAIDialog),[i,l]=y.useState(!1),d=n&&!c,o=d&&(!r||i),u=r&&d,p=()=>l(x=>!x);return y.useEffect(()=>{var x,h,m,g;c?((x=s.current)==null||x.resize(0),(h=a.current)==null||h.resize(0)):((m=s.current)==null||m.resize(25),(g=a.current)==null||g.resize(25))},[c]),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(ar,{})}),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:o?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(mo,{})})}),!c&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(hn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]}):e.jsx(hn,{visualAsideControl:u?{show:!0,isOpen:i,onToggle:p}:void 0})})]})}function ho(s){var Ee;t.useAIInteractionStore($=>$.currentAIContext);const[a,n]=y.useState(""),[r,c]=y.useState(null),{authToken:i,tokenProps:l}=t.useSemaphorContext(),d=t.useEditorStore($=>$.card.id),o=t.useEditorStore($=>{var le;return(le=$==null?void 0:$.card)==null?void 0:le.sql}),u=t.useEditorStore($=>$.isDevMode),p=t.useEditorStore($=>{var le;return(le=$==null?void 0:$.card)==null?void 0:le.python}),{setCardPython:x,setCardSql:h,setRunSql:m,switchCardType:g,setQueryConfig:v}=t.useEditorActions(),b=t.useEditorStore($=>$.currentAssitantScope)||[],C=t.useEditorStore($=>$.userInputForAI),E=t.useEditorStore($=>$.triggerAIRun),B=t.useEditorStore($=>$.card),S=t.useEditorStore($=>$.selectedDatabaseName),M=t.useEditorStore($=>$.selectedTableName),w=t.useEditorStore($=>$.selectedConnectionId),D=t.useEditorStore($=>$.selectedSchemaName),I=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:A,refetch:j,data:R}=t.useEditorCardQuery(B),{setTriggerAIRun:N,setCurrentAssitantScope:L,setCardConfig:F}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:k,selectedDatamodelId:T}=t.useEditorAside(),V=(Ee=t.useDashboardQuery().data)==null?void 0:Ee.assistantProfileId,O=y.useRef(t.createAssistantConversationId()),P=y.useRef(null),_=y.useRef(d),z=y.useRef(!1),H=()=>{const $=P.current;$&&(P.current=null,O.current=t.createAssistantConversationId(),$==="clear"&&K([]))},{messages:X,setMessages:K,regenerate:Z,error:se,sendMessage:me,status:je,addToolResult:te,stop:ne,clearError:ue}=t.useChat({transport:new t.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:V,conversationId:O.current,assistantRequestId:t.createAssistantRequestId(),isDevMode:u,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:le})=>({body:{...le,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var le;if(z.current=!1,$.name==="AbortError"||(le=$.message)!=null&&le.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),H();return}console.error("[Editor Assistant] Stream error:",$),H()},onToolCall:G,onFinish({isAbort:$,isDisconnect:le,isError:ge}){z.current=!1,n(""),console.log($?"[Editor Assistant] Stream aborted by user":le?"[Editor Assistant] Stream disconnected (network error)":ge?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),H()}}),be=y.useCallback($=>{z.current=!0;try{const le=me($);return t.isPromiseLike(le)?le.catch(ge=>{throw z.current=!1,ge}):le}catch(le){throw z.current=!1,le}},[me]),fe=y.useCallback(()=>{z.current=!0;try{const $=Z();return t.isPromiseLike($)?$.catch(le=>{throw z.current=!1,le}):$}catch($){throw z.current=!1,$}},[Z]),ve=$=>{let le=!1;K(ge=>{const ee=typeof $=="function"?$(ge):$;if(ee.length===0){if(z.current)return P.current="clear",le=!0,ge;P.current=null,O.current=t.createAssistantConversationId()}return ee}),le&&ne()};y.useEffect(()=>{if(_.current!==d){if(_.current=d,z.current){P.current!=="clear"&&(P.current="rotate"),ne();return}P.current=null,O.current=t.createAssistantConversationId()}},[d,ne]),y.useEffect(()=>{E&&C&&(be({role:"user",parts:[{type:"text",text:C}]}),N(!1))},[E,C,be,N]);async function G({toolCall:$}){var le,ge,ee,Q,re,ce,Se,ye,Fe,Be,We,Je,Ye,ae,Ie,Pe;if(["createChartFromSql","createForecast"].includes($.toolName)){const Ne=((le=$.input)==null?void 0:le.sql)??((ge=$.args)==null?void 0:ge.sql),Ge=((ee=$.input)==null?void 0:ee.python)??((Q=$.args)==null?void 0:Q.python),we=((re=$.input)==null?void 0:re.chartType)??((ce=$.args)==null?void 0:ce.chartType);g(we),h(Ne),x(Ge),m(!0),te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!o){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:o,python:p||""}})}else if($.toolName==="generateQueryConfig"){n("Generating query config...");const Ne=((Se=$.input)==null?void 0:Se.chartType)??((ye=$.args)==null?void 0:ye.chartType),Ge=((Fe=$.input)==null?void 0:Fe.queryConfig)??((Be=$.args)==null?void 0:Be.queryConfig);((We=$.input)==null?void 0:We.cardConfig)??((Je=$.args)==null||Je.cardConfig),g(Ne),F(Ge),h(void 0),x(void 0);const we=await j();if((Ye=we==null?void 0:we.data)!=null&&Ye.error){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:Ge,message:(ae=we==null?void 0:we.data)==null?void 0:ae.error.message}});return}if((Ie=we==null?void 0:we.data)!=null&&Ie.records){te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized"}});return}te({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:Ge,message:"The data has been visualized",records:(Pe=we==null?void 0:we.data)==null?void 0:Pe.records}})}else n("Analyzing...")}function pe($){const le=t.removeFromScopeArray(b,$);Ce(le)}function Ce($){const le=t.sanitizeAIScope($);L(le),K(ge=>[...ge,{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 Oe(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelId:T||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:k||""},le=t.dedup([...b,$]);Ce(le)}function Ve(){const $={databaseName:S||"",schemaName:D||"",tableName:M||"",datamodelName:t.resolveDatamodelName(f),connectionId:w||"",connectionType:k||"",datamodelId:T||""};if(!t.isInAiScopeArray([...I||[],...b],$)||b.length===0){const ge=t.dedup([...I||[],...b,$]).filter(ee=>ee.connectionId===$.connectionId);Ce(ge)}}const Ae=!["ready","error"].includes(je),Te=t.getErrorMessage(se);return{messages:X,setMessages:ve,sendMessage:be,regenerate:fe,isLoading:Ae,handleSetAIScope:Ve,handleAddCurrentTableToScope:Oe,removeFromCurrentSelections:pe,currentAssitantScope:b,setCurrentAssitantScope:L,stop:ne,status:je,toolStatus:a,llmUsage:r,onFinish:s,errorMessage:Te,clearError:ue}}const po=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function wn({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:n}){const r=y.useRef(null),c=y.useRef(!1),[i,l]=y.useState(!1),[d,o]=y.useState(t.isDevEnv),[u,p]=y.useState(!1),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=s??m,b=t.useCurrentAIContext(),{setCurrentAIContext:C,setHasEditorEntitySelectionOverride:E}=t.useAIActions(),{clearQueue:B}=t.useQueueActions(),{clearFileAttachments:S}=t.useFileActions(),M=t.useFileAttachments("editor"),{selectedEntities:w}=t.useAssistantContextEntities("editor"),D=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),A=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),N=t.useEditorStore(ae=>ae.showAIDialog),L=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:F,setCardPython:f}=t.useEditorActions(),{setDataSource:k}=t.useEditorActions(),{assistantProfile:T}=t.useAssistantProfile(),{messages:V,setMessages:O,sendMessage:P,isLoading:_,stop:z,status:H,llmUsage:X,errorMessage:K,clearError:Z}=ho(),[se,me]=y.useState(""),je=ae=>{me(ae.target.value)},te=ae=>{ae.preventDefault();const Ie=se.trim();if(!Ie&&M.length===0)return;const Pe=[];Ie&&Pe.push({type:"text",text:Ie}),M.forEach(Ne=>{Ne.data&&Pe.push({type:"file",mediaType:Ne.type,filename:Ne.name,url:`data:${Ne.type};base64,${Ne.data}`})}),P({role:"user",parts:Pe}),me(""),S("editor"),Ae({force:!0})},{visibleMessages:ne,hasMoreMessages:ue,totalMessageCount:be,loadMoreMessages:fe,resetMessageWindow:ve}=t.useMessageWindow(V,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:G,contentRef:pe,isAtBottom:Ce,hasNewMessages:Oe,newMessageCount:Ve,scrollToBottom:Ae,handleScroll:Te,resetNewMessageCount:Ee}=t.useAutoScroll(ne,{threshold:40,behavior:"smooth",isStreaming:_});y.useEffect(()=>{var ae;N&&!c.current&&((ae=r.current)==null||ae.focus()),c.current=N},[N]),y.useEffect(()=>{N&&(E(!1),C({selectedEntities:A||[]}))},[D,A,C,E,N]),t.useAutoSubmitQueue({assistantType:"editor",status:H,isLoading:_,sendMessage:P});const{hasActiveTools:$,activeToolText:le}=t.useActiveToolStatus(V),ge=y.useCallback(ae=>{a==null||a(ae),s===void 0&&g(ae)},[s,a]);y.useEffect(()=>{if(!v)return;function ae(Ie){Ie.key==="Escape"&&ge(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[v,ge]);const ee=y.useCallback(ae=>{P({role:"user",parts:[{type:"text",text:ae}]}),Ae({force:!0})},[P,Ae]),Q=y.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]),re=y.useCallback(()=>{ge(!v)},[v,ge]);function ce(ae,Ie){Ie==="sql"?(j(ae),R(!0)):Ie==="python"&&(f(ae),R(!0))}function Se(){b.selectedEntities.length===0&&C({selectedEntities:w})}function ye(ae){Se();const Ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};P(Ie)}function Fe(ae){Se(),P({role:"user",parts:[{type:"text",text:ae}]})}function Be(){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:l,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:p,children:"System Message"})]})]})}function We(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Je=(se==null?void 0:se.length)===0&&(V==null?void 0:V.filter(ae=>ae.role==="user").length)===0,Ye=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:[We(),L&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:L,children:(T==null?void 0:T.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[Be(),d&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Q,children:"Copy Conversation"}),e.jsx(t.IconButton,{tooltip:v?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:re,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"),Z(),ve()},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:G,className:"mt-2 flex min-w-0 w-full grow basis-0",onScroll:Te,children:e.jsxs("div",{ref:pe,className:"min-w-0 space-y-4 py-2 pr-3","data-role":"messages",children:[ue&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:fe,className:"text-xs",children:["Load ",Math.min(5,be-ne.length)," ","more messages (",be-ne.length," ","hidden)"]})}),e.jsx(t.PrintMessages,{messages:ne,showTools:d,handleRun:ce,showSystemMessage:u,onQuickReply:ee,disableQuickReplies:_}),e.jsx(t.AssistantStatus,{status:H,errorMessage:K,activeToolText:_&&$?le:void 0})]})}),N&&!Ce&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(t.Button,{onClick:()=>{Ae({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"}),Oe&&Ve>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:Ve>9?"9+":Ve})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Je&&!T&&e.jsx(t.Placeholders,{onClick:ye,placeholders:po}),e.jsx("div",{children:Je&&T&&e.jsx(t.SeedQuestions,{seedQuestions:T.seedQuestions||[],handleSeedQuestionClick:Fe})})]}),e.jsx(t.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(t.ChatInputWithContext,{ref:r,setInput:me,stop:z,input:se,handleInputChange:je,handleSubmit:ae=>{Se(),te(ae),Ae({force:!0})},isLoading:_,status:H,assistantType:"editor",onFocus:()=>{}})]}),X&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",X.inputTokens," prompt tokens, ",X.outputTokens," ","completion tokens, ",X.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:w,open:x,onOpenChange:h,dataSource:I||t.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{E(!0),C({...b,selectedEntities:ae})}})]});return v&&n?da.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:Ye})}),n):Ye}function fo(s,a,n){if(!a)return!1;const r=a.qualifiedFieldName,c=a.qualifiedEntityName,i=c&&a.name?`${c}.${a.name}`:r;return s.some(l=>{if(!(t.getDataType(l.dataType||"")==="date"))return!1;const o=t.getSelectedDateFilterColumn(l,n),u=o.split("."),p=u[u.length-1]||o,x=u.length>1?u.slice(0,-1).join("."):void 0,h=l.qualifiedTableName||x,m=h?`${h}.${p}`:void 0;return r?m?m===i||m.endsWith(`.${r}`):p===a.name:m?m===i:p===a.name})}function go({aliasTemplate:s,onAliasTemplateChange:a}){var o;const[n,r]=y.useState(s),[c,i]=y.useState(!1),l=(o=t.useEditorStore(u=>{var p;return(p=u.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.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:d,value:c?n: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"&&c&&n!==s?(a(n),i(!1)):u.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),c&&n!==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:()=>{a(n),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 jo({valueAliases:s,onValueAliasesChange:a}){const[n,r]=y.useState(null),[c,i]=y.useState(""),[l,d]=y.useState(""),o=()=>{a({...s,"":""})},u=x=>{const h={...s};delete h[x],a(h)},p=x=>{const h={...s};delete h[x],h[c]=l,a(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:n===x?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:c,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:l,onChange:g=>d(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),d(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),d(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:o,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function bo({idx:s}){var d;const a=t.useEditorStore(o=>{var u;return(u=o.card)==null?void 0:u.preferences}),n=t.useEditorStore(o=>{var u;return(u=o.card.preferences)==null?void 0:u.datasetOptions}),r=t.useEditorStore(o=>o.actions.setCardPreferences),c=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(o=>o.idx===s);function l(o,u){(o==="end"||o==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:p}]});else{const x={...i};x.datalabels=p;const h=n==null?void 0:n.map(m=>m.idx===u?x:m);r({...a,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:()=>l("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(va,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Na,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})}),e.jsx("button",{onClick:()=>l("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(ya,{className:t.cn("h-4 w-4",{"rotate-90":c==="y"})})})]})})]})}function ps({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function vo(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function yo({col:s,idx:a,className:n,iconClassName:r,children:c}){const i=t.useEditorStore(p=>{var x;return(x=p.card)==null?void 0:x.preferences}),l=t.useEditorStore(p=>{var x,h;return(h=(x=p.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===a),{setCardPreferences:o}=t.useEditorStore(p=>p.actions);function u(p){if(!d)o({...i,datasetOptions:[...l||[],{idx:a,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const x={...d};x.type=p==="area"?"line":p,x.fill=p==="area"?"origin":"";const h=l==null?void 0:l.map(m=>m.idx===a?x:m);o({...i,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[c||e.jsx(ps,{className:"max-w-[100px]",title:s,children:vo(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(bo,{idx:a})]})]})}function No(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function c(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(p=n==null?void 0:n.chartOptions)==null?void 0:p.plugins,...o}}};r(u)}function i(){var d,o,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=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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 l(){var d,o,u;return e.jsx("div",{children:e.jsxs(t.Select,{value:((u=(o=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:u.anchor)||"none",onValueChange:c,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:a?i():l()})}function Co({column:s}){const a=t.useEditorStore(o=>o.card.type),n=t.useEditorStore(o=>{var u,p;return(p=(u=o.card)==null?void 0:u.config)==null?void 0:p.metricColumns}),r=(n==null?void 0:n.map(o=>o.label))||[],c=r==null?void 0:r.find(o=>o===s.label||o===s.name),i=c?r.indexOf(c):-1;function l(){return e.jsx("div",{className:"pr-1",children:c&&e.jsx(yo,{idx:i,col:c,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){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(No,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&l(),["pie","doughnut"].includes(a)&&d()]})}function So({field:s,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:c}=t.useSemaphorContext(),i=t.useEditorStore(u=>u.card),l=i==null?void 0:i.dataSource,d=["attribute-values",s.entityName,s.name,a,n],o=t.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},p={connection_id:l.connectionId,cardConfig:u,cardDataSource:l,cache_config:t.getCacheConfig({card:i})};console.log("requestBody",p);const x=await t.postRequestRegular(`${c.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&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function Un({open:s,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:c,onSave:i}){var B,S;const l=!!c,[d,o]=y.useState(l?"values":"fields"),[u,p]=y.useState(""),[x,h]=y.useState({id:(c==null?void 0:c.id)||t.v4(),field:(c==null?void 0:c.field)||null,selectedValues:c?Array.isArray(c.value)?c.value:[c.value]:[]}),m=n.filter(M=>{var D;return l?!1:!((D=r==null?void 0:r.conditions)==null?void 0:D.some(I=>I.field.id===M.id))&&M.label.toLowerCase().includes(u.toLowerCase())}),g=M=>{h({...x,field:M}),o("values")},v=()=>{if(x.field&&x.selectedValues.length>0){const M={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let w;if(l){const D=((r==null?void 0:r.conditions)||[]).map(I=>I.id===c.id?M:I);w={...r,conditions:D}}else{const D=(r==null?void 0:r.conditions)||[];w={id:(r==null?void 0:r.id)||t.v4(),logicalOperator:"AND",negate:!1,conditions:[...D,M],groups:[]}}i(w),a(!1)}},b=()=>{if(!l||!c)return;const M=((r==null?void 0:r.conditions)||[]).filter(w=>w.id!==c.id);if(M.length>0){const w={...r,conditions:M};i(w)}else i(void 0);a(!1)},C=M=>{h({...x,selectedValues:M})},E=()=>{l&&c?(h({id:c.id,field:c.field,selectedValues:Array.isArray(c.value)?c.value:[c.value]}),o("values")):(h({id:t.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return y.useEffect(()=>{s&&E()},[s,l,c]),e.jsx(t.Dialog,{open:s,onOpenChange:a,children:e.jsxs(t.DialogContent,{className:"max-w-2xl",children:[e.jsx(t.DialogHeader,{children:e.jsx(t.DialogTitle,{children:l?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(S=x.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="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(M=>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:[M.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(M.value)?`${M.value.length} values`:String(M.value)})]},M.id))})]}),d==="fields"&&!l?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:M=>p(M.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:m.map(M=>e.jsxs(t.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>g(M),children:[e.jsx(t.IconForFieldType,{dataType:t.getDataType(M.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:M.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[M.entityName,".",M.name]})]})]},M.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&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(wo,{field:x.field,selectedValues:x.selectedValues,onValuesChange:C,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?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:()=>a(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:v,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function wo({field:s,selectedValues:a,onValuesChange:n,onBack:r}){const[c,i]=y.useState(""),{values:l,isLoading:d,isFetching:o}=So({field:s,searchQuery:c,limit:500}),u=c?l.filter(h=>String(h.value).toLowerCase().includes(c.toLowerCase())):l,p=h=>{const m=a.includes(h);n(m?a.filter(g=>g!==h):[...a,h])},x=()=>{a.length===u.length&&u.length>0?n([]):n(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:c,onChange:h=>i(h.target.value),className:"pl-10"})]}),d||o?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:a.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:a.includes(h.value),onCheckedChange:()=>p(h.value)}),e.jsx(ps,{className:"text-sm",children:h.label})]},h.id))})]})]})}function To({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:c,hasPivotColumns:i=!1,cardType:l}){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,en;const{attributes:d,listeners:o,setNodeRef:u,transform:p,transition:x,isDragging:h}=t.useSortable({id:s.id}),m=t.useEditorStore(U=>U.card),g=t.useEditorStore(U=>U.frame),v=t.useDashboardStore(U=>U.isVisualEditing),b=t.useDashboardStore(U=>U.selectedSheetId),C=t.useDashboardStore(U=>U.actions.updateSheetCalculatedFields),{scopedFields:E,valuePickFilterableFields:B,isLoading:S}=t.useFilterableFields(),{userContext:M}=t.useCurrentUserInfo(),w=(M==null?void 0:M.type)==="organization",{updateLabel:D,handleAggregationChange:I,handleDateFormatChange:A,handleGranularityChange:j,handleAliasTemplateChange:R,handleValueAliasesChange:N,handleMetricFormatChange:L,removeField:F,handleMetricComparisonChange:f,handleMetricWindowTransformChange:k,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:V,handleMetricWindowPartitionToggle:O,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:_,handleMetricPreviousPeriodDeltaModeChange:z,handleMetricPercentOfTotalScopeChange:H,handleMetricPercentOfTotalOutputChange:X,handleKpiShowTrendlineChange:K,handleKpiTrendlineWindowChange:Z,handleKpiTrendlineGranularityChange:se,handleMetricTargetValueChange:me}=t.useFieldManagement(m),[je,te]=y.useState(!1),[ne,ue]=y.useState(()=>{var U;return!!((U=s.parameters)!=null&&U.windowTransform)}),[be,fe]=y.useState(!1),[ve,G]=y.useState(!1),[pe,Ce]=y.useState(null),Oe=y.useMemo(()=>{const U=oe=>oe!=null&&oe.startsWith("card-source-")?oe.replace("card-source-",""):oe,Y=U(s.id),de=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 ke=U(oe.id);return!!(Y&&ke&&Y===ke)});return{dataType:(de==null?void 0:de.dataType)||s.dataType,resolvedFromScopedField:!!de}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,E]),Ve=t.getGranularityOptionsForFieldType(Oe.dataType),[Ae,Te]=y.useState(s.dateFormat||"YYYY-MM-DD"),[Ee,$]=y.useState(s.customFormat||""),[le,ge]=y.useState(!!s.customFormat),ee=y.useRef(null),[Q,re]=y.useState(s.aliasTemplate||""),[ce,Se]=y.useState(s.valueAliases||{}),[ye,Fe]=y.useState((Ns=s.parameters)==null?void 0:Ns.filters),Be=U=>{U==="custom"?ge(!0):(ge(!1),Te(U),(a==="groupBy"||mt)&&A(n,U,"",a))},We=U=>{$(U),(a==="groupBy"||mt)&&A(n,"custom",U,a)},Je=U=>{var oe;const de=(oe=t.getDateFormatOptionsForGranularity(U)[0])==null?void 0:oe.value;de&&!le&&(Te(de),a==="groupBy"&&A(n,de,"",a)),a==="groupBy"&&j(n,U)},Ye=U=>{re(U),a==="metrics"&&R(n,U)},ae=U=>{Se(U),a==="metrics"&&N(n,U)},Ie=U=>{D(a,n,U)},Pe=t.getExpressionFieldKind(s),Ne=t.getFieldExpressionAnnotation(s),Ge=t.isManagedCalculatedExpressionField(s),we=s.role==="metric"&&Ge,bt=Ge&&(Pe==="user_calculated"||Pe==="inline_expression"&&s.fieldScope!=="domain"),Xe=bt?(Cs=g==null?void 0:g.calculatedFields)==null?void 0:Cs.find(U=>t.matchesCalculatedField(U,s,{allowComparableFallback:!0})):void 0,Tt=bt&&(s.fieldScope==="dashboard"||s.fieldScope===void 0&&!!Xe),Ue=Pe==="domain_calculated"||s.fieldScope==="domain",Et=Ue?t.resolveDomainCalculatedFieldForEdit(s,E):void 0,ct=Ue?"domain":Tt?"dashboard":"card",Ze=Ue?Et||s:Tt&&Xe?Xe:s,It=U=>{var Y;if(Fe(U),a==="metrics"){const de={...s,parameters:{...s.parameters,filters:U}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}fe(!1)},vt=()=>{F(a,n)},Kt={transform:t.CSS.Transform.toString(p),transition:x},Dt=t.getDataType(Oe.dataType||s.dataType),dt=Dt==="date",ut=l==="kpi",mt=a==="detailColumns",xt=(Ss=m.config)==null?void 0:Ss.metricColumns,$e=(ws=m.config)==null?void 0:ws.groupByColumns,et=t.useDashboardStore(U=>{var Y;return(Y=U.dashboard)==null?void 0:Y.filters}),Gt=t.useDashboardStore(U=>U.filterValues),tt=s.granularity||"day",kt=Ve.includes(tt)?tt:"day",yt=a==="groupBy"&&!Ve.includes(tt),ht=t.getDateFormatOptionsForGranularity(kt),Ut=le?"custom":ht.some(U=>U.value===Ae)?Ae:((Ts=ht[0])==null?void 0:Ts.value)??"YYYY-MM-DD";y.useEffect(()=>{var de;if(S||!yt){ee.current=null;return}const U=`${s.id}:${tt}:${Oe.dataType||s.dataType||""}:${n}`;if(ee.current===U)return;ee.current=U;const Y="day";if(j(n,Y),!le){const oe=(de=t.getDateFormatOptionsForGranularity(Y)[0])==null?void 0:de.value;oe&&(Te(oe),A(n,oe,"",a))}},[s.dataType,s.id,A,j,yt,n,le,S,tt,Oe.dataType,a]);const Ht=!!l&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),Qt=l==="kpi"||l==="table",Ke=y.useMemo(()=>$e==null?void 0:$e.find(U=>t.getDataType(U.dataType||"")==="date"),[$e]),At=y.useMemo(()=>($e||[]).some(U=>t.getDataType(U.dataType||"")==="date"),[$e]),pt=y.useMemo(()=>{var oe;if(!Ke)return!1;const U=(oe=m.config)==null?void 0:oe.filters;if(!U)return!1;const Y=ke=>{const Le=ke.field;return Le?Ke.id&&Le.id===Ke.id||Ke.qualifiedFieldName&&Le.qualifiedFieldName===Ke.qualifiedFieldName?!0:Le.name===Ke.name:!1},de=ke=>ke.conditions.some(_e=>t.getDataType(_e.field.dataType||"")==="date"&&Y(_e))?!0:ke.groups.some(_e=>de(_e));return de(U)},[(Es=m.config)==null?void 0:Es.filters,Ke]),Mt=y.useMemo(()=>fo(et||[],Ke,Gt),[et,Gt,Ke]),Nt=pt||Mt,q=s,W=((Ds=(Is=q.parameters)==null?void 0:Is.windowTransform)==null?void 0:Ds.function)||"none",J=t.isMetricTransformEnabled(q),ie=J?W:null,xe=t.supportsMetricTransformForMetric({cardType:l||"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)||"",Qe=((Rs=(Fs=(Ls=q.parameters)==null?void 0:Ls.windowTransform)==null?void 0:Fs.orderBy)==null?void 0:Rs.direction)||"asc",rt=Me.find(U=>U.id===Re),st=ie==="running_total"||ie==="moving_average"||ie==="previous_period_delta",ze=J&&st&&!!rt&&t.getDataType(rt.dataType||"")!=="date",ft=t.getDefaultRunningTotalPartitionByFieldIds({cardType:l||"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=l==="pivotTable"||t.isSubtotalEnabledAggregateTable(l||"table",m.config||{}),gs=[...($e||[]).filter(U=>U.id&&(!st||U.id!==Re)),...Yt?(((Bs=m.config)==null?void 0:Bs.pivotByColumns)||[]).filter(U=>U.id):[]],js=((_s=(zs=(Vs=q.parameters)==null?void 0:Vs.windowTransform)==null?void 0:zs.movingAverage)==null?void 0:_s.windowSize)||7,Qn=((Ks=($s=(qs=q.parameters)==null?void 0:qs.windowTransform)==null?void 0:$s.movingAverage)==null?void 0:Ks.minPeriods)||1,Jn=((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",Yn=((Zs=(Xs=(Ws=q.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.percentOfTotal)==null?void 0:Zs.output)||"percent",Wn=y.useMemo(()=>(xt||[]).some(U=>U.comparisonType==="start_vs_end"),[xt]);y.useEffect(()=>{J&&ue(!0)},[J]);const Xn=a!=="pivotBy"&&a!=="sortBy",Zn=dt&&a==="groupBy"&&(!ut||Wn),ea=!ut&&dt&&(a==="groupBy"||mt),ta=l==="kpi"&&dt&&a==="groupBy",sa=a==="metrics",vs=Ht&&a==="metrics",na=()=>{const U=s,Y=a==="metrics"&&we;return e.jsxs("div",{className:"space-y-1",children:[!Y&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:de=>{de.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}`}),Y&&U.calculatedFormula&&e.jsxs("div",{title:t.formatDisplayFormula(U.calculatedFormula),onPointerDown:de=>{de.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(U.calculatedFormula)]})]})},aa=()=>Xn?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,ra=()=>a!=="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:U=>c(U),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=()=>Zn?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:Je,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:Ve.map(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U,children:t.toTitleCase(U)},U))})]})]}):null,la=()=>ea?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:Be,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(U=>e.jsx(t.SelectItem,{className:"text-xs",value:U.value,children:U.label},U.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:U=>{U.stopPropagation(),We(U.target.value)},onClick:U=>U.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,oa=()=>{var Y,de,oe,ke;const U=ta;return U?e.jsx(e.Fragment,{children:U&&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:((Y=m.config)==null?void 0:Y.showTrendline)||!1,onCheckedChange:K})]})}),((de=m.config)==null?void 0:de.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;Z(_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:((ke=m.config)==null?void 0:ke.trendlineGranularity)||"day",onValueChange:se,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},ia=()=>{if(!sa)return null;const U=we;return e.jsxs(e.Fragment,{children:[U&&w&&!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:()=>G(!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:Y=>{I(n,Y)},disabled:U,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:Y=>L(n,Y),showTitle:!1})]}),e.jsx(t.Collapsible,{open:ne,onOpenChange:ue,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:[!ne&&e.jsx("span",{className:"mr-2",children:J?t.toTitleCase(W.replace(/_/g," ")):"None"}),e.jsx(t.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",ne?"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:J?W:"none",onValueChange:Y=>k(n,Y),disabled:!xe.supported&&!J,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&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xe.reason}),he&&!J&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),J&&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:Y=>T(n,Y),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(Y=>!!Y.id).map(Y=>e.jsx(t.SelectItem,{value:Y.id,className:"text-xs",children:Y.label||Y.name},Y.id))})]}),!Re&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),ze&&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:Qe,onValueChange:Y=>V(n,Y),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:Y=>P(n,Number(Y.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:Qn,onChange:Y=>_(n,Number(Y.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:Jn,onValueChange:Y=>z(n,Y),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:Y=>H(n,Y),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:Yn,onValueChange:Y=>X(n,Y),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(Y=>{const de=!!Y.id&&Jt.has(Y.id);return e.jsxs("button",{type:"button",onClick:()=>Y.id&&O(n,Y.id),className:t.cn("flex h-7 w-full items-center justify-between rounded border px-2 text-xs",de?"border-primary bg-primary/5 text-primary":"border-border text-muted-foreground"),children:[e.jsx("span",{children:Y.label||Y.name}),de?e.jsx(t.Check,{className:"h-3 w-3"}):null]},Y.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:J,onValueChange:Y=>f(n,Y),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 Y=!At||!Nt,de=At?Nt?void 0:"Add a date filter to enable":"Add a date groupBy to enable",oe=(ke,Le)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:ke,disabled:Y,title:de,children:Le})}),Y&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});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:Y=>{const de=Y.target.value;if(de===""){me(n,void 0);return}const oe=Number(de);me(n,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"}),(ye==null?void 0:ye.conditions)&&ye.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:ye.conditions.map(Y=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{Ce(Y),fe(!0)},children:[e.jsxs("span",{className:"font-medium",children:[Y.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(Y.value)?Y.value.length===1?String(Y.value[0]):Y.value.length<=2?Y.value.join(", "):`${Y.value.slice(0,2).join(", ")} +${Y.value.length-2}`:String(Y.value)})}),Array.isArray(Y.value)&&Y.value.length>1&&e.jsx(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 (",Y.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:Y.value.map((de,oe)=>e.jsx("div",{children:String(de)},oe))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var ke;de.stopPropagation();const oe=ye.conditions.filter(Le=>Le.id!==Y.id);if(oe.length>0){const Le={...ye,conditions:oe};It(Le)}else if(Fe(void 0),a==="metrics"){const Le={...s,parameters:{...s.parameters,filters:void 0}},_e=[...((ke=m.config)==null?void 0:ke.metricColumns)||[]];_e[n]=Le,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:_e})}},children:e.jsx(t.X,{className:"h-3 w-3"})})]},Y.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{Ce(null),fe(!0)},children:[e.jsx(t.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Co,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(go,{aliasTemplate:Q,onAliasTemplateChange:Ye}),e.jsx(jo,{valueAliases:ce,onValueAliasesChange:ae})]})]})},ca=(ye==null?void 0:ye.conditions)&&ye.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",je&&"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",...d,...o,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:U=>{U.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}),Ne&&e.jsx("span",{className:t.cn(t.FIELD_EXPRESSION_BADGE_BASE_CLASS,Ne.badgeClassName),children:Ne.label})]}),e.jsx(ps,{className:t.cn("block w-0 min-w-0 flex-1 text-sm text-foreground/95",ca&&"min-w-0"),children:t.getMetricDisplayLabel(s)}),a==="metrics"&&((en=ye==null?void 0:ye.conditions)==null?void 0:en.length)&&!je&&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:ye.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:ye.conditions.map(U=>e.jsxs("div",{children:[U.field.label,":"," ",Array.isArray(U.value)?`${U.value.length} values`:String(U.value)]},U.id))})})]})}),a==="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:U=>{U.stopPropagation(),c(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:U=>{U.stopPropagation(),te(!je)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${je?"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:U=>{U.stopPropagation(),vt()},children:e.jsx(t.X,{className:"h-2.5 w-2.5"})})]}),je&&e.jsxs("div",{className:"space-y-3 rounded-md bg-muted/20 p-2.5",children:[na(),ra(),aa(),l==="kpi"&&ys(),la(),oa(),ia()]})]}),be&&e.jsx(Un,{open:be,onOpenChange:U=>{fe(U),U||Ce(null)},availableFields:B,existingFilters:ye,editingCondition:pe,onSave:U=>{var Y;if(U)It(U);else if(Fe(void 0),a==="metrics"){const de={...s,parameters:{...s.parameters,filters:void 0}},oe=[...((Y=m.config)==null?void 0:Y.metricColumns)||[]];oe[n]=de,t.useEditorStore.getState().actions.updateCardConfig(m.id,{metricColumns:oe})}Ce(null)}}),ve&&a==="metrics"&&we&&e.jsx(t.CalculatedFieldEditor,{open:ve,onOpenChange:G,availableFields:E,existingField:Ze,existingFieldScope:ct,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:U=>{var Ft;if(U.role!=="metric")return;const{card:Y,frame:de,actions:oe}=t.useEditorStore.getState(),ke=((Ft=Y.config)==null?void 0:Ft.metricColumns)||[],Le=de.calculatedFields||[],{nextActiveFields:_e,nextStoredFields:Ct,nextSharedFields:Lt}=t.saveCalculatedFieldToCardScope({activeFields:ke,storedFields:Y.calculatedFields||[],sharedFields:Le,updatedField:U,editingField:Ze,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:C})},onSaveToDashboard:U=>{var tn;if(U.role!=="metric")return;const{card:Y,frame:de,actions:oe}=t.useEditorStore.getState(),ke=s,Le=((tn=Y.config)==null?void 0:tn.metricColumns)||[],_e=de.calculatedFields||[],{nextActiveFields:Ct,nextStoredFields:Lt,nextSharedFields:Ft}=t.saveCalculatedFieldToSharedScope({activeFields:Le,storedFields:Y.calculatedFields||[],sharedFields:_e,updatedField:{...U,id:ke.id,aliasTemplate:ke.aliasTemplate,valueAliases:ke.valueAliases,parameters:ke.parameters,customFormat:ke.customFormat},editingField:Ze,previousScope:ct});t.commitSharedCalculatedFields({nextSharedFields:Ft,currentSharedFields:_e,isVisualEditing:v,selectedSheetId:b,updateFrame:oe.updateFrame,updateSheetCalculatedFields:C}),Ct&&oe.updateCardConfig(m.id,{metricColumns:Ct}),oe.updateCard(m.id,{calculatedFields:Lt})},cardId:m.id})]})}function Eo({concept:s}){const a=()=>{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:a()})]})})}const Io={groupBy:zt,pivotBy:cs,metrics:Ia,detailColumns:t.Table2,sortBy:t.ArrowUpDown};function wt({zone:s,fields:a,label:n,placeholder:r,shouldShow:c,hasPivotColumns:i=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=t.useDroppable({id:s}),{updateSortByColumn:u}=t.useEditorActions(),p=t.useEditorStore(C=>C.card),x=t.useEditorStore(C=>C.card.type),h=a.length>0,m=y.useMemo(()=>!l||!d?!0:t.validateFieldForChartType(l,s,x).isValid,[l,d,s,x]),g=(C,E)=>{var S;!((S=p.config)!=null&&S.sortByColumns)||p.config.sortByColumns.findIndex(M=>M.id===C)===-1||u(p.id,C,{direction:E})};if(s==="sortBy"&&c===!1)return null;const v=s!=="sortBy"&&x!=="kpi",b=Io[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:n})}),e.jsx("div",{ref:o,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":d&&m,"border-red-500 bg-red-50 shadow-[0_0_0_1px_rgba(239,68,68,0.18)] dark:bg-red-950":d&&!m,"border-solid border-border/55 bg-background":!d&&h,"min-h-[56px] border-dashed border-border/60 bg-background":!d&&!h}),children:a.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(Eo,{concept:s})]}):e.jsx(t.SortableContext,{id:s,items:a.map(C=>C.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map((C,E)=>{const S=C.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(To,{field:C,zone:s,index:E,sortDirection:S,onSortDirectionChange:M=>g(C.id,M),hasPivotColumns:i,cardType:x})})},C.id)})})})})]})}function Do({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r,detailFields:c,activeField:i}){var z,H,X;const[l,d]=y.useState(!1),o=t.useEditorStore(K=>{var Z;return!!((Z=K.card.customCardPreferences)!=null&&Z.url)}),u=t.useEditorStore(K=>K.card),p=t.useEditorStore(K=>K.frame),x=t.findCustomVisualConfigCard(p,u),{manifest:h}=t.useCustomVisual(((z=x==null?void 0:x.customCardPreferences)==null?void 0:z.url)||""),m=(H=h==null?void 0:h.visuals)==null?void 0:H.find(K=>{var Z;return K.name===((Z=x==null?void 0:x.customCardPreferences)==null?void 0:Z.componentName)}),g=t.resolveMultiInputType(x,m)==="multiple",v=g&&!!((X=x==null?void 0:x.customCardPreferences)!=null&&X.url),b=t.getConfigSlotExpectedType(m==null?void 0:m.slots);t.useEditorStore(K=>K.actions.updateCardConfig);const C=t.useEditorStore(K=>K.actions.updateCard),E=t.useEditorStore(K=>K.actions.updateFrame),B=t.useDashboardStore(K=>K.isVisualEditing),S=t.useDashboardStore(K=>K.selectedSheetId),M=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),{scopedFields:w}=t.useScopedFields(),{userContext:D}=t.useCurrentUserInfo(),I=g&&(x==null?void 0:x.id)===u.id&&b?b:u==null?void 0:u.type,A=I==="detailTable",j=s.length>0||n.length>0||c.length>0,R=!A&&(I!=="kpi"||n.length<=2),N=!A,L=!A&&I!=="kpi",F=I!=="kpi"&&j,f=A,k="Drop sort fields here",T=(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:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:i}),N&&e.jsx(wt,{zone:"metrics",fields:n,label:_().label,placeholder:_().placeholder,hasPivotColumns:a.length>0,activeField:i}),f&&e.jsx(wt,{zone:"detailColumns",fields:c,label:"Columns",placeholder:"Drop columns here"}),n.length>=1&&T&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>d(!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})]})]}),(!o||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(Gn,{mode:"config"})})})]}),(o||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(In,{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(_n,{})})]})]}),e.jsx(t.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:w,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{if(K.role!=="metric")return;const{nextStoredFields:Z}=t.saveCalculatedFieldToCardScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:p.calculatedFields||[],updatedField:K,previousScope:"card"});C(u.id,{calculatedFields:Z})},onSaveToDashboard:K=>{if(K.role!=="metric")return;const Z=p.calculatedFields||[],{nextSharedFields:se}=t.saveCalculatedFieldToSharedScope({activeFields:n,storedFields:u.calculatedFields||[],sharedFields:Z,updatedField:K,previousScope:"dashboard"});t.commitSharedCalculatedFields({nextSharedFields:se,currentSharedFields:Z,isVisualEditing:B,selectedSheetId:S,updateFrame:E,updateSheetCalculatedFields:M})},cardId:u.id})]})}function ko({onEditJoins:s}){const a=t.useEditorStore(d=>d.card),{autoJoinMetadata:n}=t.useEditorCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,c=(r==null?void 0:r.joins)||[];if(c.length===0)return null;const i=d=>!d||d.length===0?"No conditions":d.map(o=>{var h,m,g,v;const u=`${(h=o.source)==null?void 0:h.entityName}.${(m=o.source)==null?void 0:m.name}`,p=`${(g=o.target)==null?void 0:g.entityName}.${(v=o.target)==null?void 0:v.name}`,x=o.operator||"=";return`${u} ${x} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?i(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,u)=>({id:u,operator:o.operator,condition:i(o.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(La,{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:c.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:c.map((d,o)=>{const u=l(d),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:d.source.name}),e.jsx(t.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.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:d.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})})})]},d.id||o)})})})]})})]}),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 Tn={getItem(s){if(typeof window>"u")return null;try{return localStorage.getItem(s)}catch(a){return console.warn(`Failed to read from localStorage (${s}):`,a),null}},setItem(s,a){if(!(typeof window>"u"))try{localStorage.setItem(s,a)}catch(n){console.warn(`Failed to write to localStorage (${s}):`,n)}}};function Ao({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d}){var A,j;const[o,u]=y.useState(()=>Tn.getItem("chart-selector-expanded")==="true"),[p,x]=y.useState(!1),h=t.useEditorStore(R=>R.card),m=t.useEditorStore(R=>R.actions.updateCardConfig),g=n.length>0||r.length>0||c.length>0||l.length>0,{data:v,autoJoinMetadata:b}=t.useEditorCardQuery(h),C=g||!!v,E=((A=h==null?void 0:h.config)==null?void 0:A.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)||[],S=R=>{m(h.id,{...h==null?void 0:h.config,joinPlan:R}),x(!1)},M=()=>{m(h.id,{...h==null?void 0:h.config,joinPlan:void 0}),x(!1)},w=()=>{x(!1)},D=()=>{x(!0)};y.useEffect(()=>{Tn.setItem("chart-selector-expanded",String(o))},[o]);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",o?"max-h-[210px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(us,{selectedChart:s,onChartChange:a,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:t.cn("flex items-center justify-center",{"mt-3":o,"mt-2":!o}),children:e.jsx(t.ChartQuickSelector,{selectedChart:s,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:I})})]})}),C&&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",C?"pt-1":"pt-4"),children:[e.jsx(ko,{onEditJoins:D}),e.jsx(Do,{groupByFields:n,pivotByFields:r,metricsFields:c,sortByFields:i,detailFields:l,activeField:d})]})}),e.jsx(Mn,{open:p,onOpenChange:x,joinPlan:E,availableDataSources:B,onSave:S,onCancel:w,onRemove:M,children:e.jsx("div",{})})]})}function Mo({initialFilters:s,availableFields:a}={}){const[n,r]=y.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:c,isLoading:i}=t.useFilterableFields(),l=a||c||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},o=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}]}}return{...w,groups:w.groups.map(M)}};r(M(n))},u=S=>{const M=w=>{if(w.id===S){const D=l[0]||d,I=t.getDataType(D.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:D,operator:I?"between":"=",value:I?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(M)}};r(M(n))},p=(S,M)=>{const w=D=>D.id===S?{...D,conditions:D.conditions.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(n))},x=(S,M)=>{const w=D=>D.id===S?{...D,groups:D.groups.filter(I=>I.id!==M)}:{...D,groups:D.groups.map(w)};r(w(n))},h=(S,M,w,D)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const I=A=>A.id===S?{...A,conditions:A.conditions.map(j=>j.id===M?{...j,[w]:D}:j)}:{...A,groups:A.groups.map(I)};r(I(n))},m=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:I.conditions.map(A=>A.id===M?{...A,...w}:A)}:{...I,groups:I.groups.map(D)};r(D(n))},g=(S,M)=>{const w=D=>D.id===S?{...D,logicalOperator:M}:{...D,groups:D.groups.map(w)};r(w(n))},v=(S,M)=>{const w=D=>D.id===S?{...D,negate:M}:{...D,groups:D.groups.map(w)};r(w(n))},b=(S,M,w)=>{const D=I=>I.id===S?{...I,conditions:t.arrayMove(I.conditions,M,w)}:{...I,groups:I.groups.map(D)};r(D(n))},C=(S,M,w)=>{const D=I=>I.id===S?{...I,groups:t.arrayMove(I.groups,M,w)}:{...I,groups:I.groups.map(D)};r(D(n))},E=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const M=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 A=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",N=j[1]?`'${j[1]}'`:"NULL";return`${I} BETWEEN ${R} AND ${N}`}else if((D.operator==="in"||D.operator==="not in")&&Array.isArray(j)){const R=j.map(N=>N?`'${N}'`:"NULL").join(", ");return`${I} ${A} (${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(N=>typeof N=="string"?`'${N}'`:String(N)):typeof j=="string"?R=j.split(",").map(N=>{const L=N.trim();return D.field.dataType==="string"?`'${L}'`:L}):typeof j=="number"&&(R=[String(j)]),j=`(${R.join(", ")})`}switch(A){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} ${A} ${j}`}},w=D=>{const I=D.conditions.map(M),A=D.groups.map(L=>w(L)),j=[...I,...A].filter(Boolean);if(j.length===0)return"";const R=j.join(` ${D.logicalOperator} `),N=j.length>1?`(${R})`:R;return D.negate?`NOT ${N}`:N};return w(S)},B=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:l,isLoading:i,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B}}function Lo({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}const Fo=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Ro({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:c="w-64"}){const[i,l]=y.useState(!1),d=y.useMemo(()=>{const o={};return n.forEach(u=>{const p=Fo(u);o[p]||(o[p]={}),o[p][u.entityId]||(o[p][u.entityId]=[]),o[p][u.entityId].push(u)}),o},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:l,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",c),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Lo,{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(d).map(([o,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"}),o]}),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:()=>{a(h),l(!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))]},`${o}-${p}`))},o))})]})})]})}function fs(s){var v;const a=t.useEditorStore(b=>b.card),{authToken:n,tokenProps:r}=t.useSemaphorContext(),c=t.useEditorStore(b=>b.card.config),i=c==null?void 0:c.joinPlan,l={...s,alias:s.name,label:"value",role:"groupby"},d={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((v=a.dataSource)==null?void 0:v.connectionId)||a.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`,(n==null?void 0:n.accessToken)||"",{connection_id:p,cardConfig:u,cardDataSource:a.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 Oo({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:c}){const[i,l]=Pt.useState(!1),{filterValues:d}=fs(s),o=p=>{n(a.filter(x=>x!==p))},u=p=>{a.includes(p)?n(a.filter(x=>x!==p)):n([...a,p])};return e.jsx("div",{className:t.cn("w-full",c),children:e.jsxs(t.Popover,{open:i,onOpenChange:l,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:a.length>0?a.map(p=>{const x=d.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"&&o(p)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),o(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:d.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",a.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 Po({field:s,value:a,onChange:n,placeholder:r="Select value...",className:c}){const{filterValues:i,isPending:l,error:d}=fs(s);return l?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..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:c||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((o,u)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+u))})]})}function Bo({value:s,operator:a,onChange:n,className:r}){var m,g,v;const{tokenProps:c}=t.useSemaphorContext(),i=((g=(m=c==null?void 0:c.params)==null?void 0:m.calendarContext)==null?void 0:g.tz)||((v=c==null?void 0:c.params)==null?void 0:v.timezone),l=i||Intl.DateTimeFormat().resolvedOptions().timeZone,d=a==="between"||a==="not between",o=y.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,C=s[1]?new Date(s[1]):void 0;if(b&&C)return{from:b,to:C}}},[s,d]),u=y.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const C=new Date(b);if(!isNaN(C.getTime()))return C},[s,d]),p=b=>a==="<="||a===">"?t.endOfDayInTimezone(b,l):t.startOfDayInTimezone(b,l),x=b=>{if(!b){n([]);return}if(b.from&&b.to){n([b.from.toISOString(),b.to.toISOString()]);return}n([])},h=b=>{if(!b){n("");return}const C=p(b);n(C.toISOString())};return e.jsx(t.DateRangePicker,{value:d?o:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:u,onChange:x,onSingleChange:h,timezone:i,showRelativeTab:d,className:r,placeholder:"Select date..."})}const Vo=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],zo=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],_o=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],qo=["=","!=","isNull","isNotNull"],$o=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],Ko={"=":"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 En(s){return Ko[s]||t.titleCase(s)}function Go(s){switch(s){case"string":return zo;case"number":return _o;case"boolean":return qo;case"date":return $o;default:return Vo}}function Hn({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:c,onRemoveCondition:i,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){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),C={transform:t.CSS.Transform.toString(h),transition:m};return e.jsxs("div",{ref:x,style:C,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"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:E=>l(n,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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Ro,{value:s.field,onValueChange:E=>{const B=E,S=t.getDataType(B.dataType)==="date";o(n,s.id,{field:B,value:"",operator:S?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:E=>{E==="in"||E==="not in"?o(n,s.id,{operator:E,value:[]}):E==="isNull"||E==="isNotNull"?o(n,s.id,{operator:E,value:null}):E==="between"||E==="not between"?o(n,s.id,{operator:E,value:[]}):o(n,s.id,{operator:E,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?En(s.operator):""})}),e.jsx(t.SelectContent,{children:Go(t.getDataType(s.field.dataType)).map(E=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:E,children:En(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(Oo,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(E=>typeof E=="string")?s.value:[],onChange:E=>o(n,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=>o(n,s.id,{value:E.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(Po,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:E=>o(n,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=>o(n,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(Bo,{value:s.value,operator:s.operator,onChange:E=>o(n,s.id,{value:E}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:E=>c(n,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(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Uo({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:c,onRemoveGroup:i,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:u,onReorderGroups:p,onAddCondition:x,onAddGroup:h,availableFields:m,renderFilterGroup:g,updateConditionFields:v}){const{attributes:b,listeners:C,setNodeRef:E,transform:B,transition:S,isDragging:M}=t.useSortable({id:s.id}),w={transform:t.CSS.Transform.toString(B),transition:S},D=A=>{const{active:j,over:R}=A;if(R&&j.id!==R.id){const N=s.conditions.findIndex(F=>F.id===j.id),L=s.conditions.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&u(s.id,N,L)}},I=A=>{const{active:j,over:R}=A;if(R&&j.id!==R.id&&n){const N=s.groups.findIndex(F=>F.id===j.id),L=s.groups.findIndex(F=>F.id===R.id);N!==-1&&L!==-1&&p(n,N,L)}};return e.jsxs("div",{ref:E,style:w,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${M?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...C,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:()=>c(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:A=>r(s.id,A),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:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((A,j)=>e.jsx(Hn,{condition:A,index:j,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:m,updateConditionFields:v},A.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(A=>A.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(A=>g(A,a+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 Ho({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:c}){const{currentFilters:i,availableFields:l,isLoading:d,addCondition:o,addGroup:u,removeCondition:p,removeGroup:x,updateCondition:h,updateConditionFields:m,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:b,reorderGroups:C,generateSQLPreview:E,hasAnyFilters:B,setCurrentFilters:S}=Mo({initialFilters:s,availableFields:a}),M=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[w,D]=y.useState(!1),I=(R,N,L)=>{const F=f=>f.id===R?{...f,conditions:f.conditions.map(k=>k.id===N?{...k,field:L,dataType:L.dataType}:k)}:{...f,groups:f.groups.map(F)};S(F(i))},A=(R,N=0,L)=>N===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const T=R.conditions.findIndex(O=>O.id===f.id),V=R.conditions.findIndex(O=>O.id===k.id);T!==-1&&V!==-1&&b(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.conditions.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.conditions.map((F,f)=>e.jsx(Hn,{condition:F,index:f,groupId:R.id,groupLogicalOperator:R.logicalOperator,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onUpdateGroupOperator:g,availableFields:l,updateConditionFields:m},F.id))})}),e.jsx(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragEnd:F=>{const{active:f,over:k}=F;if(k&&f.id!==k.id){const T=R.groups.findIndex(O=>O.id===f.id),V=R.groups.findIndex(O=>O.id===k.id);T!==-1&&V!==-1&&C(R.id,T,V)}},children:e.jsx(t.SortableContext,{items:R.groups.map(F=>F.id),strategy:t.verticalListSortingStrategy,children:R.groups.map(F=>A(F,N+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:()=>o(R.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),w&&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(Uo,{group:R,depth:N,parentGroupId:L,onUpdateGroupOperator:g,onUpdateGroupNegate:v,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:I,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:C,onAddCondition:o,onAddGroup:u,availableFields:l,renderFilterGroup:A,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:[d?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..."})]}):A(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:w,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:c,children:"Cancel"}),j>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(B?i:null),children:"Apply Filters"})]})]})}function Qo({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:c,isOpen:i,onOpenChange:l}){const d=u=>{n(s,u),l(!1)},o=()=>{r(s),l(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:l,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(Ho,{filters:a,availableFields:c,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function Jo({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var E,B;const[c,i]=y.useState(null),l=t.useEditorStore(S=>S.card),d=t.useEditorStore(S=>S.actions.updateCardConfig),o=t.useEditorStore(S=>S.actions.setCardPreferences),u=(E=l==null?void 0:l.config)==null?void 0:E.joinPlan,p=y.useCallback(S=>S.entityName===t.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),x=(B=l==null?void 0:l.dataSource)==null?void 0:B.semanticDomainId,{data:h}=t.useJoinabilityMap(x),m=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],g=y.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(M=>M.id===S)?"source":n("groupBy").find(M=>M.id===S)?"groupBy":n("metrics").find(M=>M.id===S)?"metrics":n("pivotBy").find(M=>M.id===S)?"pivotBy":n("sortBy").find(M=>M.id===S)?"sortBy":n("detailColumns").find(M=>M.id===S)?"detailColumns":null,[a,n]),v=y.useCallback(S=>{i(S.active.id)},[]),b=y.useCallback(S=>{var R;const{active:M,over:w}=S;if(!w||!s){i(null);return}const D=M.id,I=w.id,A=g(D),j=g(I)||I;if(j==="sortBy"){if(A==="source"){const N=a.find(F=>F.id===D);if(!N){i(null);return}if(!(n("groupBy").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||n("metrics").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName)||n("detailColumns").some(F=>F.name===N.name&&F.qualifiedEntityName===N.qualifiedEntityName))){i(null);return}}else if(A==="pivotBy"){i(null);return}else if(A!=="groupBy"&&A!=="metrics"&&A!=="sortBy"&&A!=="detailColumns"){i(null);return}}if(A==="source"&&j==="sortBy"){const N=[...a].find(k=>k.id===D);if(!N){i(null);return}const L=n("sortBy");if(t.fieldAlreadyExists(N,L)){i(null);return}const F=t.validateFieldForChartType(N,"sortBy",l.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(N,"sortBy",L);i(null),r("sortBy",[...L,f]);return}if(A==="source"&&j!=="source"&&j!=="sortBy"){const N=[...a].find(O=>O.id===D);if(!N){i(null);return}const L=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy"),...n("detailColumns")],F=L.filter(O=>!p(O));if(F.length>0){const O=F[0].qualifiedEntityName;if(!O){i(null);return}if(O!==N.qualifiedEntityName&&!p(N)&&N.qualifiedEntityName)if(x&&(h!=null&&h.joinabilityMap)){if(t.calculateFieldState(N,{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,N.qualifiedEntityName,u)){t.showJoinRequiredNotification(),i(null);return}}}const f=n(j);if(t.fieldAlreadyExists(N,f)){i(null);return}const k=t.validateFieldForChartType(N,j,l.type);if(!k.isValid){t.ue.error("Invalid Field Type",{description:k.reason,position:"top-center",duration:3e3}),i(null);return}const T=t.getNewField(N,j,f),V=[...f,T];if(i(null),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,T,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(A&&j&&A!=="source"&&j!=="source"&&A!==j){const N=n(A),L=n(j),F=N.find(O=>O.id===D);if(!F){i(null);return}const f=t.validateFieldForChartType(F,j,l.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 T=N.filter(O=>O.id!==D),V=[...L,k];if(r(A,T),r(j,V),j==="metrics"&&s){const O=t.seedSemanticMetricFormatDefaults(l,k,l.preferences);O&&o(O),t.cleanupKpiMetricComparisonMode(l.type,l.config,d,s,V)}return}if(A&&j&&A===j&&A!=="source"){const N=n(A),L=N.findIndex(f=>f.id===D),F=N.findIndex(f=>f.id===I);if(L!==F){const f=t.arrayMove(N,L,F);r(A,f)}}i(null)},[s,a,n,r,g,u,x,h,p,l,d,o]),C=c?m.find(S=>S.id===c):null;return{activeId:c,activeField:C,handleDragStart:v,handleDragEnd:b}}function Yo({activeView:s,onViewChange:a,splitViewEnabled:n}){const r=t.useEditorStore(d=>d.card),{config:c}=y.useContext(t.SemaphorContext).tokenProps,i=(c==null?void 0:c.showInfoTab)!==!1,l=()=>n?!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:d=>a(d),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"}),l()&&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 Wo=[{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 Xo(){var o,u;const s=t.useEditorStore(p=>p.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=y.useState(!1),[c,i]=y.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),a(s.id,parseInt(p))},d=p=>{const x=p.target.value;i(x),x&&!isNaN(parseInt(x))&&a(s.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:c,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((u=(o=s.config)==null?void 0:o.rowLimit)==null?void 0:u.toString())||"100",onValueChange:l,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:Wo.map(p=>e.jsx(t.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function Zo({card:s,queryData:a,isLoading:n,isFetching:r,pagination:c,onPaginationChange:i,onSortChange:l,sortState:d,splitViewEnabled:o,isDynamicInspectorOpen:u,onDynamicInspectorOpenChange:p}){const x=y.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),h=t.getVisualizationMode(s)==="dynamic",m=e.jsx(ot,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Vn,{fallbackPreview:e.jsx(ot,{}),records:x,title:s.title,isInspectorOpen:u,onInspectorOpenChange:p})});return h?o?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:[(n||r)&&(a==null?void 0:a.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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]}):m:!o||["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:[(n||r)&&(a==null?void 0:a.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"})}),(a==null?void 0:a.records)&&e.jsx(t.TableVisual,{card:s,data:x,paginationMetadata:c,onPaginationChange:i,isLoading:n||r,onSortChange:l,sortState:d})]})})]})}const ei="semaphor-split-view-enabled";function ti(){return Ln(ei,!0)}function si({activeView:s,onViewChange:a,onFiltersClick:n,activeCard:r,columns:c}){var be,fe,ve;const i=t.useEditorStore(G=>G.card),l=t.useEditorStore(G=>G.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),d=t.useEditorStore(G=>G.actions.removeCardInlineFilterValue),o=t.useDashboardStore(G=>G.filterValues),u=t.useDashboardStore(G=>G.selectedSheetId),{updateCardConfig:p,setCard:x,updateCardInFrame:h,setShowAIDialog:m}=t.useEditorActions(),g=t.useEditorStore(G=>G.showAIDialog),v=t.useEditorStore(G=>G.isDevMode),b=t.useDashboardStore(G=>G.isVisualEditing),[C,E]=y.useState(!1),[B,S]=y.useState(!1),[M,w]=y.useState(!1),[D,I]=y.useState(null),{config:A}=y.useContext(t.SemaphorContext).tokenProps,j=(A==null?void 0:A.showInfoTab)!==!1,R=(A==null?void 0:A.showQueryDebugTools)!==!1,[N,L]=ti();t.useEditorStore(G=>{var pe;return!!((pe=G.card.customCardPreferences)!=null&&pe.url)});const f=t.getVisualizationMode(i)==="dynamic",{data:k,errorMessage:T,isLoading:V,isFetching:O,errorSql:P,pagination:_,refetch:z,comparisonMetadata:H,queryRequestPayload:X,resolvedPrimaryDateField:K}=t.useEditorCardQuery(r),Z=y.useMemo(()=>(k==null?void 0:k.records)||[],[k==null?void 0:k.records]),[se,me]=y.useState(!1);y.useEffect(()=>{O||me(!1)},[O]);const je=()=>{const G=!N;G&&s==="table"&&a("chart"),L(G)},te=(G,pe)=>{const Ce={...r,paginationConfig:{page:G+1,pageSize:pe}};x(Ce),h(Ce)},ne=G=>{if(!i.config)return;const pe=t.sortStateToSortByColumns(G,i.config.metricColumns,i.config.groupByColumns,i.config.detailColumns);p(i.id,{...i.config,sortByColumns:pe})},ue=y.useMemo(()=>{var G;return t.sortByColumnsToSortState((G=i.config)==null?void 0:G.sortByColumns)},[(be=i.config)==null?void 0:be.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(Yo,{activeView:s,onViewChange:a,splitViewEnabled:N}),e.jsx(t.FilterInfo,{cardId:r.id,cardFilters:(fe=r.config)==null?void 0:fe.filters,cardFilterCount:t.getFilterCount(((ve=r.config)==null?void 0:ve.filters)||null),onFiltersClick:n,inlineFilters:r.inlineFilters,inlineFilterValues:l,sheetId:u||"",removeInlineFilterValue:G=>d(r.id,G),resolvedPrimaryDateField:K}),H&&i.type!=="table"&&e.jsx(t.ComparisonMetadataBadge,{metadata:H,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Xo,{})}),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:()=>{me(!0),z()},children:e.jsx(t.RefreshCcw,{className:t.cn("h-4 w-4",{"animate-spin":se})})}),s==="chart"&&!f&&e.jsx(Bn,{showInlineFilters:!1,showDisplayOptions:!1}),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:je,children:[N?e.jsx(ga,{className:"mr-2 h-4 w-4"}):e.jsx(Aa,{className:"mr-2 h-4 w-4"}),N?"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(zn,{onCustomize:()=>w(!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":N&&!["table","pivotTable","aggregateTable","detailTable"].includes(r.type)}),children:e.jsx(Zo,{card:r,queryData:k,isLoading:V,isFetching:O,pagination:_,onPaginationChange:te,onSortChange:ne,sortState:ue,splitViewEnabled:N,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:w})}),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:Z,comparisonMetadata:H,paginationMetadata:_,onPaginationChange:te,isLoading:V||O,onSortChange:ne,sortState:ue})]}),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:T?e.jsx(ds,{error:T,errorSql:P,onSendFeedback:()=>{const G=t.prepareFeedbackData(t.FeedbackCategory.QUERY_GENERATION,{cardConfig:i.config,dataSource:r.dataSource,dashboardFilters:o,errorMessage:T,errorSql:P,generatedSql:k==null?void 0:k.sql});I(G),S(!0)},onOpenInEditor:()=>{m(!0),setTimeout(()=>{const G=t.useEditorStore.getState().actions;G.setIsDevMode(!0),G.setCardSql(P||""),setTimeout(()=>{G.setRunSql(!0)},100)},100)}}):(k==null?void 0:k.sql)&&e.jsx(Rn,{sql:k.sql,showCardDetails:!0,debugPayloads:R?{queryRequest:X,queryResponse:k,columns:c,dashboardFilters:o}:void 0})})})]}),D&&e.jsx(t.FeedbackDialog,{open:B,onOpenChange:S,feedbackData:D})]})})}function ni({activeField:s}){const[a,n]=y.useState(!0);return y.useEffect(()=>{s&&n(!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 ${a?"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 ai=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var c;if((c=r.reason)!=null&&c.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function ri({column:s,isSelected:a,onSelect:n,availableFields:r,width:c,onWidthChange:i}){var O,P,_;const l=t.useEditorStore(z=>z.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:u,updateFilters:p}=t.useEditorActions(),[x,h]=y.useState(!1),[m,g]=y.useState(!1),v=y.useRef(null),b=y.useCallback(z=>{z.preventDefault(),z.stopPropagation(),g(!0),v.current={startX:z.clientX,startWidth:c||150};const H=K=>{if(!v.current)return;const Z=K.clientX-v.current.startX,se=Math.max(80,v.current.startWidth+Z);i==null||i(s.id,se)},X=()=>{g(!1),v.current=null,document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",X)};document.addEventListener("mousemove",H),document.addEventListener("mouseup",X)},[c,s.id,i]),C=(O=l==null?void 0:l.config)==null?void 0:O.filters,E=(P=C==null?void 0:C.conditions)==null?void 0:P.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),B=z=>{z?p(l.id,z):d(l.id,{filters:void 0})},{attributes:S,listeners:M,setNodeRef:w,transform:D,transition:I,isDragging:A}=t.useSortable({id:s.id}),j={transform:t.CSS.Transform.toString(D),transition:I},R=t.getDataType(s.dataType),N=li(R),L=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.sortByColumns)||[],H=z.findIndex(K=>K.name===s.name);if(H!==-1){const K=[...z];K[H]={...K[H],direction:"asc"},d(l.id,{sortByColumns:K})}else d(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},F=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.sortByColumns)||[],H=z.findIndex(K=>K.name===s.name);if(H!==-1){const K=[...z];K[H]={...K[H],direction:"desc"},d(l.id,{sortByColumns:K})}else d(l.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var X;const z=((X=l==null?void 0:l.config)==null?void 0:X.groupByColumns)||[];if(!z.some(K=>K.name===s.name)){const K={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...z,K]})}},k=z=>{var K;const H=((K=l==null?void 0:l.config)==null?void 0:K.metricColumns)||[];if(!H.some(Z=>Z.name===s.name&&Z.aggregate===z)){const Z={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};d(l.id,{metricColumns:[...H,Z]})}},T=()=>{s.role==="groupby"?o(l.id,s.id):s.role==="metric"&&u(l.id,s.id)},V={...j,width:c?`${c}px`:void 0,minWidth:c?`${c}px`:"120px"};return e.jsxs("th",{ref:w,style:V,className:t.cn("group relative border-r border-border bg-background px-1 py-0",A&&"opacity-50",a&&"bg-primary/10",m&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...M,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:n,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",a&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(N,{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(ha,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(t.DropdownMenuItem,{onClick:F,children:[e.jsx(xa,{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:T,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(Un,{open:x,onOpenChange:h,availableFields:r.length>0?r:[s],existingFilters:C,editingCondition:E?(_=C==null?void 0:C.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:B})]})}function li(s){switch(s){case"number":return t.Hash;case"date":return t.Calendar;case"string":default:return t.Type}}function oi({selectedColumn:s,onColumnSelect:a,isLoading:n=!1,sourceFields:r=[],filterableFields:c=r}){var A,j,R,N;const i=t.useEditorStore(L=>L.card),{updateCardConfig:l}=t.useEditorActions(),[d,o]=y.useState(null),[u,p]=y.useState({}),[x,h]=y.useState(!1),m=y.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]},[(A=i==null?void 0:i.config)==null?void 0:A.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns]),g=y.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.useEditorCardQuery(i),C=(v==null?void 0:v.records)||[],E=y.useCallback((L,F)=>{p(f=>({...f,[L]:F}))},[]),B=y.useCallback(L=>{var T,V;const F=t.getDataType(L.dataType),f=((T=i==null?void 0:i.config)==null?void 0:T.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"};l(i.id,{metricColumns:[...k,O]})}else{const O={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};l(i.id,{groupByColumns:[...f,O]})}h(!1)},[(R=i==null?void 0:i.config)==null?void 0:R.groupByColumns,(N=i==null?void 0:i.config)==null?void 0:N.metricColumns,i.id,l]),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),M=L=>{o(L.active.id)},w=L=>{const{active:F,over:f}=L;if(o(null),!f||F.id===f.id)return;const k=m.findIndex(V=>V.id===F.id),T=m.findIndex(V=>V.id===f.id);if(k!==-1&&T!==-1){const V=t.arrayMove(m,k,T),O=V.filter(_=>_.role==="groupby"),P=V.filter(_=>_.role==="metric");l(i.id,{groupByColumns:O,metricColumns:P})}},D=d?m.find(L=>L.id===d):null,I=L=>{let F="";for(;L>=0;)F=String.fromCharCode(L%26+65)+F,L=Math.floor(L/26)-1;return F};return n?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:S,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:w,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(ri,{column:L,isSelected:(s==null?void 0:s.id)===L.id,onSelect:()=>a(L),availableFields:c,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"})})}):C.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"})}):C.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:ii(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(C.length,100)," of ",C.length," rows"]}),e.jsxs("span",{children:[m.length," columns"]})]})]})}function ii(s,a){if(s==null)return"—";if(typeof s=="number")return a.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 n=new Date(s);if(!isNaN(n.getTime()))return n.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function ci({entityGroups:s,isLoading:a=!1}){var B,S;const n=t.useEditorStore(M=>M.card),{updateCardConfig:r,removeGroupByColumn:c,removeMetricColumn:i}=t.useEditorActions(),[l,d]=y.useState(!0),[o,u]=y.useState(""),[p,x]=y.useState(new Set),h=((B=n==null?void 0:n.config)==null?void 0:B.groupByColumns)||[],m=((S=n==null?void 0:n.config)==null?void 0:S.metricColumns)||[],g=M=>{const w=new Set(p);w.has(M)?w.delete(M):w.add(M),x(w)},v=M=>h.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName)||m.some(w=>w.name===M.name&&w.qualifiedEntityName===M.qualifiedEntityName),b=(M,w)=>{if(w)if(t.getDataType(M.dataType)==="number"){const I={...M,id:`metric-${M.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(n.id,{metricColumns:[...m,I]})}else{const I={...M,id:`groupby-${M.id}-${Date.now()}`,role:"groupby"};r(n.id,{groupByColumns:[...h,I]})}else{const D=h.findIndex(A=>A.name===M.name&&A.qualifiedEntityName===M.qualifiedEntityName),I=m.findIndex(A=>A.name===M.name&&A.qualifiedEntityName===M.qualifiedEntityName);D!==-1&&c(n.id,h[D].id),I!==-1&&i(n.id,m[I].id)}},C=M=>{if(!o)return M;const w=o.toLowerCase();return M.filter(D=>D.name.toLowerCase().includes(w)||D.label&&D.label.toLowerCase().includes(w))},E=M=>{switch(t.getDataType(M)){case"number":return t.Hash;case"date":return t.Calendar;default:return t.Type}};return l?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:()=>d(!1),title:"Close panel",children:e.jsx(Sa,{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:o,onChange:M=>u(M.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(M=>{const w=E(M.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.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:()=>c(n.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.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(M=>{const w=E(M.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(w,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:M.label||M.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.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(n.id,M.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]},M.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:a?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(M=>{const w=C(M.columns);if(w.length===0)return null;const D=p.has(M.entityId)||o.length>0;return e.jsxs(t.Collapsible,{open:D,onOpenChange:()=>g(M.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:M.label||M.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.length})]}),e.jsx(t.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:w.map(I=>{const A=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(A,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:I.label||I.name})]},I.id)})})})]},M.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:()=>d(!0),title:"Open panel",children:e.jsx(wa,{className:"h-4 w-4"})})})}const di=[{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 ui({value:s,onChange:a,onSubmit:n,onCancel:r,selectedColumn:c,availableColumns:i}){const[l,d]=y.useState(!1),[o,u]=y.useState("column"),p=y.useRef(null);y.useEffect(()=>{const g=v=>{v.key==="Escape"&&s?r():v.key==="Enter"&&s&&!l&&n(s)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,r,n,l]);const x=g=>{const v=`[${g.label||g.name}]`,b=p.current;if(b){const C=b.selectionStart||0,E=b.selectionEnd||0,B=s.slice(0,C)+v+s.slice(E);a(B),setTimeout(()=>{b.setSelectionRange(C+v.length,C+v.length),b.focus()},0)}else a(s+v);d(!1)},h=g=>{const v=p.current;if(v){const b=v.selectionStart||0,C=v.selectionEnd||0,E=s.slice(0,b)+g.syntax+s.slice(C);a(E),setTimeout(()=>{v.setSelectionRange(b+g.name.length+1,b+g.syntax.length-1),v.focus()},0)}else a(s+g.syntax);d(!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:c?e.jsx("span",{className:"truncate",children:c.label||c.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:l&&o==="function",onOpenChange:g=>{d(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(ka,{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:di.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:l&&o==="column",onOpenChange:g=>{d(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=>a(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:()=>n(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function mi({className:s}){var m,g,v,b;const a=t.useEditorStore(C=>C.card),[n,r]=y.useState(null),[c,i]=y.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=t.useColumns(),{valuePickFilterableFields:u=[]}=t.useFilterableFields();(m=a==null?void 0:a.config)!=null&&m.groupByColumns,(g=a==null?void 0:a.config)!=null&&g.metricColumns,(v=a==null?void 0:a.config)!=null&&v.groupByColumns,(b=a==null?void 0:a.config)!=null&&b.pivotByColumns;const p=C=>{r(C),i(C?`[${C.label||C.name}]`:"")},x=C=>{console.log("Formula submitted:",C),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(ui,{value:c,onChange:i,onSubmit:x,onCancel:h,selectedColumn:n,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(oi,{selectedColumn:n,onColumnSelect:p,isLoading:o,sourceFields:l,filterableFields:u})}),e.jsx(ci,{entityGroups:d,isLoading:o})]})]})}function xi(){var T,V;const[s,a]=y.useState("chart"),[n,r]=y.useState(!1),[c,i]=y.useState(!0),l=t.useEditorStore(O=>O.showAIDialog),d=t.useDashboardStore(O=>O.isVisualEditing),{setCardType:o}=t.useEditorActions(),u=t.useEditorStore(O=>O.card.type);y.useEffect(()=>ai(),[]);const p=O=>{o(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:C}=t.useEditorActions(),{columnFields:E=[],scopedFields:B=[],filterableFields:S=[]}=t.useFilterableFields(),M=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),w=h,{getFieldsForContainer:D,setFieldsForContainer:I}=t.useFieldManagement(w),{activeField:A,handleDragStart:j,handleDragEnd:R}=Jo({activeCardId:x.activeCardId,sourceFields:B,getFieldsForContainer:D,setFieldsForContainer:I}),N=(O,P)=>{P&&C(O,P)},L=O=>{var P;v(O,{config:{...(P=x.cards.find(_=>_.id===O))==null?void 0:P.config,filters:void 0}})},F=S,f=O=>{if(!O)return 0;let P=O.conditions.length;return O.groups.forEach(_=>{P+=f(_)}),P},k=f(((T=w==null?void 0:w.config)==null?void 0:T.filters)||null);return e.jsxs(t.DndContext,{sensors:M,collisionDetection:t.closestCenter,onDragStart:j,onDragEnd:R,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Fn,{isVisible:c,onToggleVisibility:()=>i(!c)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(mi,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(Ao,{selectedChart:u,onChartChange:p,groupByFields:D("groupBy"),pivotByFields:D("pivotBy"),metricsFields:D("metrics"),sortByFields:D("sortBy"),detailFields:D("detailColumns"),activeField:A}),e.jsx(si,{selectedChart:u,activeView:s,onViewChange:a,onFiltersClick:()=>r(!0),filterCount:k,activeCard:w,columns:E,getFieldsForContainer:D,cards:x.cards,activeCardId:x.activeCardId,addCard:m,setActiveCard:b})]})}),!c&&d&&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"})})})]}),w&&e.jsx(Qo,{cardId:w.id,filters:((V=w.config)==null?void 0:V.filters)||null,onFiltersChange:N,onClearFilters:L,availableFields:F,isOpen:n,onOpenChange:r}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(ni,{activeField:A||null})})]})}function hi({authToken:s,onSave:a,onClose:n}){const r=y.useRef(null),c=t.useEditorStore(w=>w.showAIDialog),i=t.useEditorStore(w=>w.isDevMode),l=t.useAssistantLayoutStore(w=>w.setFullscreen),d=t.useAssistantLayoutStore(w=>w.setPanelOpen),o=t.useAssistantLayoutStore(w=>w.setContainer),u=t.useAssistantPanel("editor"),p=t.useFullscreenAssistant(),x=t.useAssistantContainer("editor"),h=p==="editor",m=y.useCallback(w=>{o("editor",w)},[o]),{setAuthToken:g}=t.useDashboardActions(),{setShowAIDialog:v,setOnSave:b,setOnClose:C}=t.useEditorActions(),{setActiveAssistantType:E}=t.useAIActions();y.useEffect(()=>{a&&b(a),n&&C(n)},[a,b,n,C]),y.useEffect(()=>{s&&s.accessToken&&g(s)},[s,g]),y.useEffect(()=>{var w,D;c?((w=r.current)==null||w.resize(40),d("editor",!0),E("editor")):((D=r.current)==null||D.resize(0),d("editor",!1),p==="editor"&&l(null),E(null))},[c,d,E,l,p]);function B(w){var D;w<1?(v(!1),d("editor",!1),p==="editor"&&l(null),E(null),(D=r.current)==null||D.resize(0)):(c||(v(!0),E("editor")),u.isOpen||d("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(Fn,{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(xo,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),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(wn,{isFullscreen:h,onFullscreenChange:w=>l(w?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:m,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function M(){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(xi,{})}),e.jsx(t.ResizableHandle,{disabled:!c}),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(wn,{isFullscreen:h,onFullscreenChange:w=>l(w?"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:S()}):M()})}function pi(){t.useDashboardStore(u=>u.selectedCardId);const s=t.useDashboardStore(u=>u.selectedSheetId),a=t.useDashboardStore(u=>u.dashboard),{setIsVisualEditing:n,setSelectedSheetId:r}=t.useDashboardStore(u=>u.actions),c=t.useDashboardStore(u=>u.isVisualEditing),i=t.useDashboardStore(u=>u.actions.updateFrame),l=t.useResolveExistingFrameSemanticExecutionPayload();async function d(u){var g,v,b;const p=s?(g=a==null?void 0:a.sheets)==null?void 0:g.some(C=>{var E;return C.id===s&&((E=C.frames)==null?void 0:E.some(B=>B.id===u.id))}):!1,x=(b=(v=a==null?void 0:a.sheets)==null?void 0:v.find(C=>{var E;return(E=C.frames)==null?void 0:E.some(B=>B.id===u.id)}))==null?void 0:b.id,h=p?s:x||null;if(!h)return;const m=t.findDashboardFrameById(a,u.id);try{const C=await l(u,{previousFrame:m});i(h,u,{semanticExecutionPayload:C}),s!==h&&r(h),n(!1)}catch(C){console.error("Failed to resolve semantic metadata on save:",C),t.ue.error(C instanceof Error?C.message:"Failed to resolve semantic metadata for this visual")}}function o(){n(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),children:e.jsx(hi,{onSave:d,onClose:o})})}exports.default=pi;
|