react-semaphor 0.1.461 → 0.1.462
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/{dashboard-briefing-launcher-3owMxX5K.js → dashboard-briefing-launcher-C6ePN5_I.js} +1246 -1244
- package/dist/chunks/dashboard-briefing-launcher-Qto0i-Gl.cjs +26 -0
- package/dist/chunks/{dashboard-controls-Bpm_xOXQ.cjs → dashboard-controls--Wg8-58g.cjs} +1 -1
- package/dist/chunks/{dashboard-controls-B4GvjGr1.js → dashboard-controls-CJcvFl2B.js} +3 -3
- package/dist/chunks/{dashboard-json-DzyxoBp-.js → dashboard-json-DFhvCpHL.js} +1 -1
- package/dist/chunks/{dashboard-json-yLM01xK4.cjs → dashboard-json-DXrlNlUM.cjs} +1 -1
- package/dist/chunks/{edit-dashboard-visual-1T278Nr_.cjs → edit-dashboard-visual-D2JLKep9.cjs} +2 -2
- package/dist/chunks/{edit-dashboard-visual-nwSasO_j.js → edit-dashboard-visual-Dhx5wAKM.js} +893 -893
- package/dist/chunks/{editor-action-buttons-CX1Pken3.cjs → editor-action-buttons-Ba8M_DAF.cjs} +1 -1
- package/dist/chunks/{editor-action-buttons-Dqw0asfA.js → editor-action-buttons-C_wg1zTn.js} +1 -1
- package/dist/chunks/{index-B1qplNxl.cjs → index-BAN1CQ6R.cjs} +185 -185
- package/dist/chunks/{index-DazD5k0F.js → index-HMTOcZOr.js} +24309 -24305
- package/dist/chunks/{report-preferences-dialog-DKPyjiCt.cjs → report-preferences-dialog-BaVeLREU.cjs} +1 -1
- package/dist/chunks/{report-preferences-dialog-Dv3vCCFt.js → report-preferences-dialog-Ditwc9JX.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/data-app-builder/index.cjs +1 -1
- package/dist/data-app-builder/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/dashboard-briefing-launcher-xuGrw8H3.cjs +0 -26
package/dist/chunks/{edit-dashboard-visual-1T278Nr_.cjs → edit-dashboard-visual-D2JLKep9.cjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),C=require("react"),n=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),C=require("react"),n=require("./index-BAN1CQ6R.cjs"),oe=require("./x-B6ghREd2.cjs"),t=require("./switch-DBZsEV0U.cjs"),Ke=require("./saved-temporal-bucket-format-3QKveR3v.cjs");require("./validators-dJlwubP4.cjs");require("./analyze-result-contract-DSGoFuXQ.cjs");const Jt=require("../value-format-preferences/index.cjs"),Ye=require("./search-BqqhaMx9.cjs"),Nt=require("./editor-action-buttons-Ba8M_DAF.cjs"),It=require("./temporal-bucket-authoring-BK1UhYpD.cjs"),cr=require("./dashboard-filter-value-compatibility-UapptYnn.cjs"),he=require("./index-DjjKJPDy.cjs"),dr=require("react-dom");require("./index-ByFbacH7.cjs");require("./color-CyB5o13F.cjs");const oa=require("./pivot-result-lifecycle-BXzIlQVu.cjs"),Mn=require("./temporal-bucket-pMfghsLX.cjs"),ur=require("./palette-BN-jYtaK.cjs"),mr=require("./common-types-BcV9PD9D.cjs");function xr(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const r in s)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,o.get?o:{enumerable:!0,get:()=>s[r]})}}return a.default=s,Object.freeze(a)}const hr=xr(C);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -169,4 +169,4 @@ ${o}`].filter(Boolean).join(`
|
|
|
169
169
|
${a||r.sql||r.python}
|
|
170
170
|
|
|
171
171
|
`;i(m)}:void 0}}function va(s,a){const[r,o]=C.useState(!1),d=t.useEditorStore(x=>x.card),l=t.useDashboardStore(x=>x.dashboard.filters),{currentUser:i}=n.useCurrentUserInfo(),{tokenProps:c}=C.useContext(n.SemaphorContext),u=C.useCallback(()=>{o(!0)},[]),m=C.useMemo(()=>{const x=typeof window<"u"?window.location.href:"",g=typeof navigator<"u"?navigator.userAgent:"",p=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:n.FeedbackCategory.QUERY_GENERATION,user:i,tokenContext:c,systemState:{cardConfig:d.config,dataSource:d.dataSource,dashboardFilters:l,errorMessage:s||void 0,errorSql:a||d.sql||d.python,generatedSql:a||d.sql},metadata:{url:x,userAgent:g,timestamp:new Date().toISOString(),viewport:p}}},[i,c,d,l,s,a]);return{feedbackDialogOpen:r,setFeedbackDialogOpen:o,handleSendFeedback:u,feedbackPayload:m}}const wo="__editor_sql__",To="__editor_python__";function Eo(s){var r;const a=he.normalizeDashboardCardPythonCode(s.python||"");return{sql:(r=s.sql)!=null&&r.trim()?wo:"",python:a.trim()?To:""}}function ya({className:s,style:a,...r}){var ze,We,_e,Xe,Ze,et,re;const o=t.useEditorStore(J=>J.card),d=n.useDashboardAppearance(),i=t.useEditorStore(J=>J.isDevMode)?!1:((ze=o.customCardPreferences)==null?void 0:ze.showCardHeader)??!0,c=((_e=(We=o.preferences)==null?void 0:We.displayOptions)==null?void 0:_e.showInlineFilterBar)??!0,u=t.useEditorStore(J=>J.frame),m=t.useEditorStore(J=>J.inlineFilterValuesMap[o.id]),x=t.useDashboardStore(J=>J.dashboard.filters),g=t.useDashboardStore(J=>J.selectedSheetId),p=t.useEditorStore(J=>J.actions.setRunSql),h=t.useEditorStore(J=>J.actions.setCardInlineFilterValue),v=t.useEditorStore(J=>J.actions.removeCardInlineFilterValue),{updateFilter:M}=t.useDashboardActions(),N=x==null?void 0:x.find(J=>J.id===u.filterId),b=C.useMemo(()=>he.findCustomVisualConfigCard(u,o),[u,o]),{manifest:w}=n.useCustomVisual(((Xe=b==null?void 0:b.customCardPreferences)==null?void 0:Xe.url)||""),F=C.useMemo(()=>{var J;return(J=w==null?void 0:w.visuals)==null?void 0:J.find(pe=>{var ue;return pe.name===((ue=b==null?void 0:b.customCardPreferences)==null?void 0:ue.componentName)})},[w,(Ze=b==null?void 0:b.customCardPreferences)==null?void 0:Ze.componentName]),S=he.resolveMultiInputType(b,F),y=C.useMemo(()=>he.getCustomVisualInputCards({frame:u,configCard:b,isMultiInputVisual:S==="multiple"}),[u,b,S]),k=C.useMemo(()=>{const J=y.findIndex(pe=>(pe==null?void 0:pe.id)===(o==null?void 0:o.id));return J<0?-1:he.getSlotIndexForCard(o,J)},[y,o]),E=C.useMemo(()=>!b||S!=="multiple"||k<0?o.type:he.getEffectiveCardTypeForSlot(o,k,F==null?void 0:F.slots)??o.type,[b,S,k,o,F==null?void 0:F.slots]),A=E??o.type,T=C.useMemo(()=>A===o.type?o:{...o,type:A},[o,A]),I=T.type==="table"||T.type==="matrixTable"||T.type==="pivotTable"||T.type==="aggregateTable"||T.type==="detailTable",L=C.useMemo(()=>E!==o.type?{...o,type:E}:o,[o,E]),{data:j,isLoading:P,isFetching:V,errorMessage:f,errorSql:O,pagination:D}=n.useEditorCardQuery(L),R=!!f,B=A==="matrixTable"&&n.hasMatrixResultData(j),Y=n.getMatrixVisualLoadingState({data:j,isLoading:P,isFetching:V}),{handleOpenInEditor:_,handleDebugWithAssistant:z}=Fs(f,O||o.sql||o.python),{feedbackDialogOpen:U,setFeedbackDialogOpen:G,handleSendFeedback:q,feedbackPayload:Q}=va(f,O||o.sql||o.python),H=C.useMemo(()=>(j==null?void 0:j.records)||[],[j==null?void 0:j.records]),{setCard:se,updateCardInFrame:ce}=t.useEditorActions(),{data:ge}=n.useTopoJson(T),fe=T.id,Te=T.config,Ve=T.interactionConfig,Ue=T.controls,Me=T.controlBindings,Ee=T.customCfg,Fe=T.preferences,Oe=T.queryConfig,Pe=Eo({sql:T.sql,python:T.python}),le=Pe.sql,De=Pe.python,ve=j==null?void 0:j.records,Ie=C.useMemo(()=>({id:fe,type:A,config:Te,interactionConfig:Ve,preferences:Fe,controls:Ue,controlBindings:Me,sql:le,python:De}),[fe,A,Te,Ve,Fe,Ue,Me,le,De]),$=C.useMemo(()=>A==="pivotTable"?n.resolvePendingPivotTableResultState({data:j,card:T,isPending:P||V}):{kind:"not_loaded"},[T,A,j,V,P]),xe=n.usePivotTableConfig(T,$,(et=j==null?void 0:j.metadata)==null?void 0:et.comparisonMetadata),Ce=(J,pe)=>{var ne,me;const ue={...o,paginationConfig:{page:J+1,pageSize:pe}};se(ue),ce(ue),o.sql&&((me=(ne=o.preferences)==null?void 0:ne.tablePrefs)!=null&&me.enableDevModePagination)&&p(!0)},ae=J=>{var ne,me,qe,$e,Je;const pe=n.sortStateToSortByColumns(J,(ne=o.config)==null?void 0:ne.metricColumns,(me=o.config)==null?void 0:me.groupByColumns,(qe=o.config)==null?void 0:qe.detailColumns),ue={...o,config:{...o.config||{},sortByColumns:pe}};se(ue),ce(ue),o.sql&&((Je=($e=o.preferences)==null?void 0:$e.tablePrefs)!=null&&Je.enableDevModePagination)&&p(!0)},ie=n.useChartNumericPresentation(Ie,ve||void 0),Re=C.useMemo(()=>{var J;return!fe||!ve?null:n.createChartConfig({card:Ie,data:ve,cardType:A,queryConfig:Oe,customCfg:Ee,preferences:Fe,topoJson:ge,comparisonMetadata:(J=j==null?void 0:j.metadata)==null?void 0:J.comparisonMetadata,numericPresentation:ie,resultColumns:j==null?void 0:j.columns,columnKeyMap:j==null?void 0:j.columnKeyMap})},[Ie,fe,Ee,Fe,Oe,ve,j==null?void 0:j.columns,j==null?void 0:j.columnKeyMap,(re=j==null?void 0:j.metadata)==null?void 0:re.comparisonMetadata,A,ie,ge]);function Z(J){return e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(n.EditorCustomVisual,{card:J})})}function Ae(){var J;if(j!=null&&j.records&&(j==null?void 0:j.records.length)===0&&!P&&!V&&!B&&A!=="pivotTable")return f?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(cs,{error:f,errorSql:O||o.sql||o.python,onOpenInEditor:_,onDebugWithAssistant:z,onSendFeedback:q,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(n.Inbox,{className:"h-8 w-8 text-muted-foreground/40"}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No results to display"})]});if((P||V)&&(!(j!=null&&j.records)||j.records.length===0)&&!B)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(n.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!T.id)return null;if(A==="custom")return Z(o);if(!["table","matrixTable","pivotTable","aggregateTable","detailTable","custom"].includes(A)&&Re)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:P||V?e.jsx(e.Fragment,{}):e.jsx(n.ChartJsVisual,{cfg:Re})});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(n.TableVisual,{card:T,data:H,resultColumns:j==null?void 0:j.columns,columnKeyMap:j==null?void 0:j.columnKeyMap,totalsByColumnId:j==null?void 0:j.tableTotalsByColumnId,comparisonMetadata:(J=j==null?void 0:j.metadata)==null?void 0:J.comparisonMetadata,paginationMetadata:D,onPaginationChange:Ce,onSortChange:ae,isLoading:P||V})});if(A==="matrixTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.MatrixTableVisual,{card:T,result:j==null?void 0:j.matrixResult,isLoading:Y})});if(A==="pivotTable"&&xe)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(n.PivotTableTanstack,{card:T,data:xe.data,options:xe.options,onAggregationChange:pe=>{const ue=n.handleAggregationChange(pe,o.config),ne={...o,config:ue};se(ne),ce(ne)},onAggregationLabelChange:pe=>{const ue=n.handleAggregationLabelChange(pe,o.config),ne={...o,config:ue};se(ne),ce(ne)}})});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(n.AggregateTable,{card:T,data:(j==null?void 0:j.records)||[],resultColumns:j==null?void 0:j.columns,columnKeyMap:j==null?void 0:j.columnKeyMap,groupByColumns:j==null?void 0:j.groupByColumns,pivotSchema:j==null?void 0:j.pivotSchema,paginationMetadata:D,onPaginationChange:Ce,onAggregationChange:pe=>{const ue=n.handleAggregationChange(pe,o.config),ne={...o,config:ue};se(ne),ce(ne)},isLoading:P||V})})}return e.jsxs(n.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none bg-card text-card-foreground",s),style:{...d.cardFrameStyle,...a},...r,children:[(P||V)&&(j==null?void 0:j.records)&&j.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),i&&e.jsxs(n.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:d.cardGutterStyle,children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(n.EditableText,{value:o.title,onSave:J=>se({...o,title:J}),isEditable:!0,placeholder:"Add title",displayClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]",inputClassName:"text-[17px] font-semibold leading-tight tracking-[-0.005em]"})}),e.jsx(n.InfoHover,{card:o}),e.jsx(Nt.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(go,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(n.EditableText,{value:(o.description||"").trim(),onSave:J=>se({...o,description:J.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),N&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(n.EditableText,{value:N.title||N.column,onSave:J=>M({...N,title:J}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(n.FilterComponent,{filter:N})]})]}),c&&o.inlineFilters&&o.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:d.cardGutterStyle,children:e.jsx(n.InlineFilterBar,{card:o,sheetId:g||"",inlineFilterValues:m,setInlineFilterValue:J=>h(o.id,J),removeInlineFilterValue:J=>v(o.id,J)})}),e.jsxs(n.CardContent,{className:t.cn("flex min-h-0 grow flex-col",I?R?"px-4 pb-0 pt-2":"p-0 [&_.data-table-scroll-container]:border-0 [&_.data-table-scroll-container]:bg-transparent":R?"px-4 py-0":"px-4"),style:I&&!R?void 0:d.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:Ae()}),n.isCardSummaryVisibleOnCard(T)&&e.jsx("div",{className:t.cn("pt-3",I&&"px-4"),children:e.jsx(n.CardSummary,{card:T,mode:"editor",records:j==null?void 0:j.records})})]}),e.jsx(n.FeedbackDialog,{open:U,onOpenChange:G,feedbackData:Q,showDebugInfo:!0})]})}function qn(s){var a,r;return JSON.stringify({...s,data:{...s.data,datasets:(r=(a=s.data)==null?void 0:a.datasets)==null?void 0:r.map(o=>{const d={...o};return Object.keys(d).forEach(l=>{l.startsWith("semaphor")&&delete d[l]}),{...d,data:[]}})}},null,2)}const vs=({language:s,value:a,onChange:r,readonly:o})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:a,onValueChange:r,readOnly:o,embedded:!0}),Io=()=>e.jsxs(n.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(n.DialogTitle,{children:"Customize Card"})}),e.jsxs(n.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."})]})]}),Do=({customCode:s,cardCustomCfgString:a,mergedConfig:r,onConfigChange:o,onCodeChange:d})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(vs,{language:"json",value:r,onChange:o})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(vs,{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(vs,{language:"javascript",value:s,onChange:d})})]}),ko=({error:s,hasCardCustomConfig:a,onReset:r,onApply:o,onClose:d})=>e.jsxs(n.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:r,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:d,variant:"outline",children:"Close"})]});function Mo({triggerVariant:s="icon",className:a,label:r="Customize Visual"}={}){const[o,d]=C.useState(!1),[l,i]=C.useState(""),[c,u]=C.useState(""),[m,x]=C.useState(""),[g,p]=C.useState(""),h=t.useEditorStore(I=>I.card),v=n.useEffectiveEditorCardType(),M=t.useEditorStore(I=>I.card.customCfg),N=M?JSON.stringify(M,null,2):"",b=C.useMemo(()=>v!==h.type?{...h,type:v}:h,[h,v]),{data:w}=n.useEditorCardQuery(b),{data:F}=n.useTopoJson(h),S=n.useChartNumericPresentation(h,w==null?void 0:w.records),{setCardCustomCfg:y,setCustomVisualCode:k}=t.useEditorActions(),E=()=>{var L,j,P;if(!((L=w==null?void 0:w.records)!=null&&L.length))return;const I=n.createChartConfig({card:h,data:w.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:F,comparisonMetadata:(j=w==null?void 0:w.metadata)==null?void 0:j.comparisonMetadata,numericPresentation:S,resultColumns:w==null?void 0:w.columns,columnKeyMap:w==null?void 0:w.columnKeyMap});if(I){i(qn(I)),x(((P=h.preferences)==null?void 0:P.customVisualCode)||"");const V=n.merge(I,M);u(qn(V))}},A=()=>{try{if(m&&k(m),c){const I=JSON.parse(c),L=n.getObjectDiff(JSON.parse(l),I);y(L),p("")}}catch{p("Invalid JSON configuration")}},T=Object.keys(M||{}).length===0;return e.jsxs(n.Dialog,{open:o,onOpenChange:d,children:[e.jsx(n.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:E,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",T?"":"text-green-600 hover:text-green-700",a),children:[e.jsx(n.Settings,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(n.IconButton,{tooltip:"Customize Visual",onClick:E,className:t.cn(T?"":"text-green-600 hover:text-green-700",a),children:e.jsx(n.Settings,{className:"h-4 w-4"})})}),e.jsxs(n.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Io,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,children:e.jsx(ya,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Do,{customCode:m,cardCustomCfgString:N,mergedConfig:c,onConfigChange:I=>u(I??""),onCodeChange:I=>x(I??"")})]}),e.jsx(ko,{error:g,hasCardCustomConfig:!!M,onReset:()=>{u(l),y(null)},onApply:A,onClose:()=>d(!1)})]})]})}function Ao(s){let a=0;for(let o=0;o<s.length;o++)a=s.charCodeAt(o)+((a<<5)-a);return`hsl(${Math.abs(a%360)}, 65%, 45%)`}function Lo(s){const a=s.trim().split(/\s+/);return a.length>1?(a[0][0]+a[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function Rs({chartType:s,chartName:a,isCustom:r=!1,className:o="h-6 w-6"}){if(!r&&s)return n.getChartIconByType(s,o);const d=n.getAutoDetectedChartIcon(a);if(d)return C.cloneElement(d,{className:o});const l=Lo(a),i=Ao(a);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",o),style:{backgroundColor:i},children:l})}function Fo({isStarred:s,onClick:a,className:r}){const o=d=>{d.stopPropagation(),d.preventDefault(),a(d)};return e.jsx("button",{type:"button",onClick:o,className:t.cn("flex items-center justify-center rounded-control p-0.5 transition-all","hover:bg-muted/80",r),"aria-label":s?"Remove from favorites":"Add to favorites",children:e.jsx(n.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 $n({chartType:s,chartName:a,isCustom:r=!1,pluginName:o,isStarred:d,showStar:l=!0,isSelected:i=!1,onSelect:c,onToggleStar:u}){return e.jsxs("div",{className:"group relative",children:[l&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",d?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(Fo,{isStarred:d,onClick:()=>u()})}),r&&o&&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",children:o})]})}),e.jsxs("button",{type:"button",onClick:c,"aria-pressed":i,className:t.cn("flex w-full flex-col items-center justify-center gap-1.5 rounded-control border border-input bg-background px-2 py-2.5 transition-colors","hover:border-foreground/30 hover:bg-muted/40",i&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(Rs,{chartType:s,chartName:a,isCustom:r,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:a,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:a})]})]})}function Ca(s,a){return s==="matrixTable"?!a.isDevMode:!0}function Qt(s,a){return s==="matrixTable"?!1:Ca(s,a)}const Ro=[{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"},{id:"matrixTable",name:"Matrix Table"}];function Po(s){return Ro.filter(a=>Ca(a.id,s))}function Na({onChartSelect:s,onClose:a}){const[r,o]=C.useState(""),{starredCharts:d,isStarred:l,toggleStar:i}=n.useStarredChartsStore(),{data:c=[],isLoading:u}=n.useCustomVisualsQuery(),{setCardType:m,setCardPreferences:x,setIsDevMode:g}=t.useEditorStore(L=>L.actions),p=t.useEditorStore(L=>L.card),h=t.useEditorStore(L=>L.isDevMode),{setCardCustomCfg:v,setCustomCardPreferences:M,setVisualizationMode:N,setQueryConfig:b,replaceFrameCards:w,clearModeDrafts:F,initializeModeDrafts:S}=t.useEditorActions(),y=C.useMemo(()=>{const L=Po({isDevMode:h});if(!r)return L;const j=r.toLowerCase();return L.filter(P=>P.name.toLowerCase().includes(j))},[h,r]),k=C.useMemo(()=>{const L=c.filter(P=>P.componentType==="chart"&&P.pluginType!=="standard");if(!r)return L;const j=r.toLowerCase();return L.filter(P=>P.name.toLowerCase().includes(j))},[c,r]),E=L=>{v(null),x({}),N("builtin"),m(L),["custom","text","map"].includes(L)&&(g(!0),b(void 0)),s==null||s(L),a==null||a()},A=L=>{v(null),x({}),N("builtin"),b(void 0);const j=he.resolveMultiInputTypeFromVisual(L);if(j==="multiple"&&L.slots&&L.slots.length>0){F();const V=he.createCardsFromSlots(L.slots,L,p);w(V),V[0]&&S(V[0]),a==null||a();return}else m("custom"),M({type:"component",visualType:j,url:L.url,componentName:L.name,icon:L.icon,pluginChartType:L.chartType,minInputs:L.minInputs,maxInputs:L.maxInputs});s==null||s("custom",L),a==null||a()},T=L=>{const j={type:"default",id:L.id,name:L.name};i(j)},I=L=>{const j={type:"custom",id:L.name,url:L.url,icon:L.icon,name:L.name};i(j)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[e.jsx(Ye.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:L=>o(L.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),e.jsxs("div",{className:"max-h-[360px] overflow-y-auto pr-1",children:[y.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:y.map(L=>e.jsx($n,{chartType:L.id,chartName:L.name,isCustom:!1,isStarred:l("default",L.id),onSelect:()=>E(L.id),onToggleStar:()=>T(L)},L.id))}),k.length>0&&e.jsxs(e.Fragment,{children:[y.length>0&&e.jsxs("div",{className:"my-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Custom charts"}),e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:k.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:k.map((L,j)=>e.jsx($n,{chartName:L.name,isCustom:!0,pluginName:L.pluginName,isStarred:l("custom",L.name),onSelect:()=>A(L),onToggleStar:()=>I(L)},`${L.url}-${L.name}-${j}`))})]}),u&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),y.length===0&&k.length===0&&!u&&e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No charts found"})]})]})}function Oo({selectedChart:s,onChartChange:a}){var k,E,A,T;const r=t.useEditorStore(I=>I.card),o=t.useEditorStore(I=>I.frame),d=t.useEditorStore(I=>I.isDevMode),{replaceFrameCards:l,clearModeDrafts:i,initializeModeDrafts:c,setIsDevMode:u}=t.useEditorActions(),m=C.useMemo(()=>he.findCustomVisualConfigCard(o,r),[o,r]),{manifest:x}=n.useCustomVisual(((k=m==null?void 0:m.customCardPreferences)==null?void 0:k.url)||""),g=C.useMemo(()=>{var I;return(I=x==null?void 0:x.visuals)==null?void 0:I.find(L=>{var j;return L.name===((j=m==null?void 0:m.customCardPreferences)==null?void 0:j.componentName)})},[x,(E=m==null?void 0:m.customCardPreferences)==null?void 0:E.componentName]),p=he.resolveMultiInputType(m,g)==="multiple",h=n.useEffectiveEditorCardType(),v=p?h:s??r.type,M=(A=r==null?void 0:r.customCardPreferences)==null?void 0:A.componentName,N=(T=m==null?void 0:m.customCardPreferences)==null?void 0:T.componentName,b=p&&!!N,w=C.useMemo(()=>{const I=n.chartTypes.find(L=>L.id===v);return I?I.label:v==="custom"?M||"Custom Visual":"Select chart type"},[v,M]),F=C.useMemo(()=>{const I=n.chartTypes.find(L=>L.id===v);if(I){const L=I.icon;return e.jsx(L,{className:"h-4 w-4"})}if(v==="custom"&&M){const L=n.getAutoDetectedChartIcon(M);return L||e.jsx(Rs,{chartName:M,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Dr,{className:"h-4 w-4"})},[v,M]);return{displayChartType:v,displayLabel:w,displayIcon:F,showBadge:b,badgeLabel:N,isMultiInputContext:p,handleChartSelect:I=>{a==null||a(I)},handleClearCustomVisual:I=>{I.stopPropagation();const L={...r,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};l([L]),i(),c(L),d&&u(!0),a==null||a("bar")}}}function Bo({selectedChart:s,onChartChange:a,variant:r="ghost",className:o}){const[d,l]=C.useState(!1),{displayLabel:i,displayIcon:c,showBadge:u,badgeLabel:m,handleChartSelect:x,handleClearCustomVisual:g}=Oo({selectedChart:s,onChartChange:a}),p=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",o),children:[e.jsxs(t.Popover,{open:d,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:p?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":d,className:"flex h-9 w-full items-center justify-between gap-2 border-b border-border bg-card px-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:i})]}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",d&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":d,className:t.cn("w-full justify-between gap-2",r==="ghost"&&"border border-border/70 bg-background text-foreground/90",r==="outline"&&"border-border/70 bg-background text-foreground/90",r==="secondary"&&"text-foreground"),children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c,e.jsx("span",{className:"truncate",children:i})]}),e.jsx(oe.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(Na,{onChartSelect:h=>x(h),onClose:()=>l(!1)})})]}),u&&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:m,children:[e.jsx(n.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m}),e.jsx("button",{onClick:g,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(oe.X,{className:"h-2.5 w-2.5"})})]})]})}const Rt={table:t.Table2,matrixTable:n.Grid3x3,bar:n.ChartColumnIncreasing,line:n.ChartLine,stackedBar:n.ChartColumnStacked,stackedLine:n.MdStackedLineChart,scatter:n.ChartScatter,bubble:n.TbChartBubble,pie:n.ChartPie,doughnut:n.Donut,kpi:n.TiSortNumerically,treemap:n.TbChartTreemap,bullet:n.BulletChartIcon,funnel:n.TbChartFunnel,tornado:n.Tornado,heatmap:n.Grid3x3,range:n.ChartNoAxesGantt,radar:n.Radar,polarArea:n.PiChartPolar,text:n.BookType,map:n.Map},Wt={table:"Table",matrixTable:"Matrix Table",bar:"Bar Chart",line:"Line Chart",stackedBar:"Stacked Bar",stackedLine:"Stacked Line",scatter:"Scatter",bubble:"Bubble",pie:"Pie Chart",doughnut:"Donut",kpi:"KPI",treemap:"Treemap",bullet:"Bullet",funnel:"Funnel",tornado:"Tornado",heatmap:"Heatmap",range:"Range",radar:"Radar",polarArea:"Polar Area",text:"Text",map:"Map"},Sa=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],wa=6;function Vo({selectedChart:s,onChartChange:a}){var F,S;const[r,o]=C.useState(!1),d=t.useEditorStore(y=>y.card),{setCardType:l,setCardPreferences:i}=t.useEditorStore(y=>y.actions),{setCardCustomCfg:c,setCustomCardPreferences:u,setQueryConfig:m,replaceFrameCards:x,clearModeDrafts:g,initializeModeDrafts:p}=t.useEditorActions(),{starredCharts:h}=n.useStarredChartsStore(),{data:v=[]}=n.useCustomVisualsQuery(),M=t.useEditorStore(y=>y.isDevMode),N=C.useMemo(()=>{const y=h.filter(T=>T.type==="default"?Qt(T.id,{isDevMode:M}):v.some(I=>I.name===T.id)),k=new Set(y.map(T=>T.id)),E=Sa.filter(T=>!k.has(T.id)&&Qt(T.id,{isDevMode:M}));return[...y.map(T=>({id:T.id,label:T.name,icon:T.type==="default"?Rt[T.id]:void 0,isCustom:T.type==="custom",url:T.url})),...E.map(T=>({id:T.id,label:Wt[T.id]??T.id,icon:Rt[T.id],isCustom:!1}))].slice(0,wa)},[h,v,M]),b=s==="custom"&&((F=d==null?void 0:d.customCardPreferences)==null?void 0:F.componentName);return N.some(y=>{var k;return y.isCustom?b&&((k=d==null?void 0:d.customCardPreferences)==null?void 0:k.componentName)===y.id:s===y.id})||(s==="custom"?(S=d==null?void 0:d.customCardPreferences)!=null&&S.componentName:Wt[s]),e.jsxs("div",{className:"px-4 pb-3 pt-4",children:[e.jsx("p",{className:"pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chart type"}),e.jsx(Ta,{selectedChart:s,onChartChange:a,compactMore:!0})]})}function Ta({selectedChart:s,onChartChange:a,compactMore:r=!1,responsiveCompact:o=!1}){var A,T;const[d,l]=C.useState(!1),i=t.useEditorStore(I=>I.card),{setCardType:c,setCardPreferences:u}=t.useEditorStore(I=>I.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:g,replaceFrameCards:p,clearModeDrafts:h,initializeModeDrafts:v}=t.useEditorActions(),{starredCharts:M}=n.useStarredChartsStore(),{data:N=[]}=n.useCustomVisualsQuery(),b=t.useEditorStore(I=>I.isDevMode),w=((A=i==null?void 0:i.customCardPreferences)==null?void 0:A.componentName)??null,F=C.useMemo(()=>{const I=M.filter(f=>f.type==="default"?Qt(f.id,{isDevMode:b}):N.some(O=>O.name===f.id)),L=new Set(I.map(f=>f.id)),j=Sa.filter(f=>!L.has(f.id)&&Qt(f.id,{isDevMode:b})),P=[...I.map(f=>({id:f.id,label:f.name,icon:f.type==="default"?Rt[f.id]:void 0,isCustom:f.type==="custom",url:f.url})),...j.map(f=>({id:f.id,label:Wt[f.id]??f.id,icon:Rt[f.id],isCustom:!1}))];if(!P.some(f=>f.isCustom?s==="custom"&&f.id===w:f.id===s))if(s==="custom"&&w){const f=N.find(O=>O.name===w);f&&P.unshift({id:f.name,label:f.name,icon:void 0,isCustom:!0,url:f.url})}else s&&Rt[s]&&Qt(s,{isDevMode:b})&&P.unshift({id:s,label:Wt[s]??s,icon:Rt[s],isCustom:!1});return P.slice(0,wa)},[M,N,s,w,b]),S=s==="custom"&&w,y=I=>{if(I.isCustom){const L=N.find(V=>V.name===I.id);if(!L)return;m(null),u({}),g(void 0);const j=he.resolveMultiInputTypeFromVisual(L);if(j==="multiple"&&L.slots&&L.slots.length>0){h();const V=he.createCardsFromSlots(L.slots,L,i);p(V),V[0]&&v(V[0]);return}c("custom"),x({type:"component",visualType:j,url:L.url,componentName:L.name,icon:L.icon,pluginChartType:L.chartType,minInputs:L.minInputs,maxInputs:L.maxInputs}),a("custom");return}a(I.id)},k=F.some(I=>{var L;return I.isCustom?S&&((L=i==null?void 0:i.customCardPreferences)==null?void 0:L.componentName)===I.id:s===I.id}),E=k?"More":s==="custom"?((T=i==null?void 0:i.customCardPreferences)==null?void 0:T.componentName)||"Custom":Wt[s]||"More";return e.jsx("div",{className:"flex items-center",children:e.jsxs("div",{className:"inline-flex h-7 items-center overflow-hidden rounded-control border border-input bg-background",children:[F.map(I=>{var P;const L=I.icon,j=I.isCustom?S&&((P=i==null?void 0:i.customCardPreferences)==null?void 0:P.componentName)===I.id:s===I.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>y(I),"aria-label":I.label,"aria-pressed":!!j,className:t.cn("flex h-full w-7 items-center justify-center text-foreground/65 transition-colors hover:bg-muted/50 hover:text-foreground",o&&!j&&"hidden @[800px]:flex",j&&"bg-foreground/[0.08] font-medium text-foreground"),children:[L?e.jsx(L,{className:"h-3.5 w-3.5"}):e.jsx(Rs,{chartName:I.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:I.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:I.label})]},`${I.isCustom?"custom":"default"}-${I.id}`)}),e.jsxs(t.Popover,{open:d,onOpenChange:l,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":E,className:t.cn("inline-flex h-full items-center gap-1 border-l border-input transition-colors hover:bg-muted/50",r?"w-7 justify-center":"px-2 text-[12px]",!r&&(k?"text-muted-foreground":"text-foreground")),children:[!r&&e.jsx("span",{className:"truncate",children:E}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",d&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:I=>I.preventDefault(),children:e.jsx(Na,{onChartSelect:I=>{a(I),l(!1)},onClose:()=>l(!1)})})]})]})})}function _o(){const s=t.useEditorStore(u=>{var m,x;return(x=(m=u.card.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),a=t.useEditorStore(u=>u.card.type),{setChartOrientation:r,setCardPreferences:o}=t.useEditorStore(u=>u.actions),d=u=>{if(r(u),a!=="bullet")return;const m=u==="y"?"horizontal":"vertical",x=t.useEditorStore.getState().card.preferences,g={...x||{},bulletConfig:{...(x==null?void 0:x.bulletConfig)||{},orientation:m}};o(g)};function l(){const u=s??"x",m=()=>{d(u==="x"?"y":"x")};return e.jsx(n.IconButton,{onClick:m,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="x"?e.jsx(fs,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})}function i(){const u=()=>{d(s==="y"||s===void 0?"x":"y")};return e.jsx(n.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(fs,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})}function c(){const u=s??"y",m=()=>{d(u==="y"?"x":"y")};return e.jsx(n.IconButton,{onClick:m,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="y"?e.jsx(ps,{className:"h-3.5 w-3.5"}):e.jsx(fs,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:a==="funnel"?i():a==="bullet"?c():l()})}function Ps({className:s,triggerVariant:a="icon",label:r="Display Options"}){var M,N,b,w,F,S,y,k,E,A;const o=t.useEditorStore(T=>T.card),{setCardPreferences:d,updateCardInFrame:l,setCard:i}=t.useEditorActions(),[c,u]=C.useState(!1),m=((N=(M=o.preferences)==null?void 0:M.displayOptions)==null?void 0:N.showFilterInfo)??!0,x=((w=(b=o.preferences)==null?void 0:b.displayOptions)==null?void 0:w.showCardToolbar)??!0,g=((S=(F=o.preferences)==null?void 0:F.displayOptions)==null?void 0:S.showChrome)??!0,p=((k=(y=o.preferences)==null?void 0:y.displayOptions)==null?void 0:k.allowScroll)??!0,h=((A=(E=o.preferences)==null?void 0:E.displayOptions)==null?void 0:A.showInlineFilterBar)??!0,v=(T,I)=>{var P;const L={...o.preferences,displayOptions:{...(P=o.preferences)==null?void 0:P.displayOptions,[T]:I}};d(L);const j={...o,preferences:L};i(j),l(j)};return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(n.DropdownMenu,{modal:!1,open:c,onOpenChange:u,children:[e.jsx(n.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:r})]}):e.jsx(n.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(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"Display Options"}),e.jsx(n.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(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:T=>{v("showFilterInfo",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:T=>{v("showCardToolbar",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:g,onCheckedChange:T=>{v("showChrome",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:T=>{v("allowScroll",T)},onSelect:T=>T.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(n.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:T=>{v("showInlineFilterBar",T)},onSelect:T=>T.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 Os({className:s,triggerVariant:a="icon",label:r="Inline Filters"}){const[o,d]=C.useState(!1),l=t.useEditorStore(y=>y.card),i=t.useEditorStore(y=>y.selectedConnectionId),{tokenProps:c}=n.useSemaphorContext(),{setCard:u}=t.useEditorActions(),m=t.useDashboardStore(y=>y.actions.removeCardInlineFilterValue),x=t.useDashboardStore(y=>y.actions.setCardInlineFilterValue),g=t.useEditorStore(y=>y.actions.removeCardInlineFilterValue),p=t.useEditorStore(y=>y.actions.setCardInlineFilterValue),h=t.useDashboardStore(y=>y.isVisualEditing),v=(l==null?void 0:l.inlineFilters)||[],M=n.useTimezone()??void 0;function N(y){var P,V,f,O,D;const k=((f=(V=(P=l==null?void 0:l.dataSource)==null?void 0:P.selectedEntities)==null?void 0:V[0])==null?void 0:f.database)||"",E=y.qualifiedFieldName||y.name;if(v.find(R=>n.doesStoredFilterMatchField(R,y)))return;const T=y.qualifiedFieldName?y.qualifiedFieldName.split(".").slice(0,-1).join("."):y.qualifiedEntityName||y.entityName,I=n.buildFilterFieldMeta(y),L=n.buildFilterSemanticContext(l==null?void 0:l.dataSource,{connectionId:i||((O=l==null?void 0:l.dataSource)==null?void 0:O.connectionId),connectionType:(D=l==null?void 0:l.dataSource)==null?void 0:D.connectionType}),j={id:Ke.v4(),column:E,title:y.label||y.name,dataType:y.dataType,table:y.entityName||"",database:k,qualifiedTableName:T,connectionId:i||"",operation:"in",sql:"",fieldMeta:I,semanticContext:L,width:250};u({...l,inlineFilters:[...v,j]})}function b(y){const k=v.filter(E=>E.id!==y);u({...l,inlineFilters:k}),h?g(l.id,y):m(l.id,y)}function w(y,k){const E=v.map(L=>L.id===y?{...L,...k}:L);if(u({...l,inlineFilters:E}),!(Object.prototype.hasOwnProperty.call(k,"defaultValues")||Object.prototype.hasOwnProperty.call(k,"defaultDateFilter")))return;const T=E.find(L=>L.id===y);if(!T)return;const I=t.buildFilterValueFromDefaults(T,M);I?h?p(l.id,I):x(l.id,I):h?g(l.id,y):m(l.id,y)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(l==null?void 0:l.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:o,onOpenChange:d,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]",v.length>0&&"text-primary"),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),v.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:v.length})]}):e.jsxs(n.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":v.length>0}),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),v.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:v.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(n.DndContext,{collisionDetection:n.closestCenter,children:e.jsx(n.SortableContext,{items:[],strategy:n.verticalListSortingStrategy,children:e.jsx(n.FieldsList,{context:"inline-filter",onFieldSelect:N,inlineFilters:v})})})}),v.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:v.map(y=>e.jsx(Yo,{filter:y,onUpdate:k=>w(y.id,k),onRemove:()=>b(y.id)},y.id))})]})]})})]})})}function Yo({filter:s,onUpdate:a,onRemove:r}){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(n.CustomFilterPopover,{filter:s,variant:"inline",onAccept:o=>a(o),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(n.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:r,children:e.jsx(oe.X,{className:"h-3 w-3"})})]})]})}const zo={metric_selector:"Displayed metric",field_selector:"Group by field",aggregation_selector:"Aggregation",grain_selector:"Time grain"};function qo(s,a){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:a||null}const $o={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function ls(s,a){return`${s}:${a}`}function Ko(s,a,r){const o=new Set(r.filter(l=>l.target!=="sql_param"&&l.target!=="presentation_currency").map(l=>ls(l.controlId,l.target))),d=a.map(l=>{const i=t.getCompatibleBindingTargetOptions({card:s,control:l}).map(x=>x.value),c=$o[l.type],m=[...c?[c]:[],...i.filter(x=>x!==c)].find(x=>!o.has(ls(l.id,x)));return m?{controlId:l.id,target:m}:null}).find(Boolean);return d?{controlId:d.controlId,target:d.target,mapping:{}}:null}function Uo({card:s,dashboardControls:a,bindings:r,onChange:o,availableFieldChoices:d,availableMetricChoices:l,suppressTransientStaleState:i=!1}){const c=[...a,...s.controls||[]],[u,m]=C.useState({}),x=n.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings}),g=t.getBindingTargetSuggestions(s),p=new Set(r.map(F=>ls(F.controlId,F.target))),h=c.some(F=>t.getCompatibleBindingTargetOptions({card:s,control:F}).some(S=>!p.has(ls(F.id,S.value)))),v=i?0:r.reduce((F,S)=>{const y=M(S.target),k=Object.values(S.mapping).filter(E=>{const A=S.target==="config_metric_selector"||S.target==="config_field_selector"?typeof E=="string"?E:E==null?void 0:E.id:typeof E=="string"?E:void 0;return typeof A=="string"&&!y.some(T=>T.value===A)}).length;return F+k},0);function M(F){var S,y,k,E;switch(F){case"config_metric_selector":return l?l.filter(A=>!!A.target).map(A=>({value:A.target.id,label:A.target.label||A.option.label,target:A.target})):((y=(S=s.config)==null?void 0:S.metricColumns)==null?void 0:y.map(A=>({value:A.id,label:A.label||A.id,target:A})))||[];case"config_field_selector":return d?d.filter(A=>!!A.target).map(A=>({value:A.target.id,label:A.target.label||A.option.label,target:A.target})):((E=(k=s.config)==null?void 0:k.groupByColumns)==null?void 0:E.map(A=>({value:A.id,label:A.label||A.id,target:A})))||[];case"config_aggregation":return(g.config_aggregation||[]).map(A=>({value:A,label:A}));case"config_grain":return(g.config_grain||[]).map(A=>({value:A,label:A.charAt(0).toUpperCase()+A.slice(1)}));default:return[]}}const N=(F,S)=>{o(r.map((y,k)=>k!==F?y:S(y)))},b=F=>{o(r.filter((S,y)=>y!==F))},w=()=>{const F=Ko(s,c,r);F&&o([...r,F])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const F=x.map(({controlId:S,paramId:y})=>{const k=c.find(E=>E.id===S);return k?{id:S,paramId:y,label:k.label,reference:`[[param.${y}]]`}:{id:S,paramId:y,label:S,reference:`[[param.${y}]]`}});return e.jsx("div",{className:"space-y-2",children:F.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]]`."}):F.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(n.CopyButton,{text:S.reference,ariaLabel:`Copy ${S.reference}`})]})]})},`${S.id}:${S.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[v>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(n.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[v," ",v===1?"mapping needs":"mappings need"," attention before save. Replace each missing target or choose Not mapped."]})]}):null,r.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."}):r.map((F,S)=>{const y=g[F.target]||[],k=c.find(f=>f.id===F.controlId),E=k?t.ensureManualSource(k):null,A=(E==null?void 0:E.source.kind)==="manual"?E.source.options:[],T=M(F.target),I=Array.from(new Set([...A.map(f=>f.value),...Object.keys(F.mapping)])).map(f=>{const O=A.find(D=>D.value===f);return{value:f,label:(O==null?void 0:O.label)||f}}),L=`${F.controlId}-${F.target}-${S}`,j=u[L]??S===0,P=Object.keys(F.mapping).length,V=k!=null&&k.type?zo[k.type]||k.type:null;return e.jsxs(n.Collapsible,{open:j,onOpenChange:f=>m(O=>({...O,[L]:f})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(n.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[j?e.jsx(oe.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx(Ye.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:(k==null?void 0:k.label)||"Control"}),V?e.jsx(n.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:V}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:P>0?`${P} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>b(S),children:e.jsx(n.Trash2,{className:"h-4 w-4"})})]}),e.jsx(n.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:I.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."}):T.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:I.map(f=>{const O=F.mapping[f.value],D=F.target==="config_metric_selector"||F.target==="config_field_selector"?typeof O=="string"?O:O==null?void 0:O.id:typeof O=="string"?O:void 0,R=!i&&typeof D=="string"&&!T.some(_=>_.value===D),B=qo(O,D),Y=D&&R?[...T,{value:D,label:"Needs remap",target:O}]:T;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:D||"__none__",onValueChange:_=>N(S,z=>{if(z.target==="config_metric_selector"){const G={...z.mapping};if(_==="__none__")delete G[f.value];else{const q=Y.find(Q=>Q.value===_);q!=null&&q.target?G[f.value]=q.target:delete G[f.value]}return{...z,mapping:G}}if(z.target==="config_field_selector"){const G={...z.mapping};if(_==="__none__")delete G[f.value];else{const q=Y.find(Q=>Q.value===_);q!=null&&q.target?G[f.value]=q.target:delete G[f.value]}return{...z,mapping:G}}const U={...z.mapping};return _==="__none__"?delete U[f.value]:U[f.value]=_,{...z,mapping:U}}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Choose what this should use"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:"Not mapped"}),Y.map(_=>e.jsx(t.SelectItem,{value:_.value,children:_.label},_.value))]})]}),R?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(n.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",B?` · Previously: ${B}`:""]})]}):null]})]},`${F.controlId}-${F.target}-${f.value}`)})}),y.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",y.join(", ")]})]})})]},L)}),h?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:w,children:[e.jsx(n.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}function Ho(s,a){const{eligibleTargets:r}=n.getCardCurrencyPresentationTargets(s,a),o=n.getCardCurrencyPresentationFields(s),d=new Map(o.map(i=>[i.id,i])),l=new Map(n.resolveMatrixCardMeasureInstances(s).map(i=>{var c,u,m;return[i.measureId,((c=i.metric)==null?void 0:c.label)||((u=i.value)==null?void 0:u.label)||((m=i.value)==null?void 0:m.field.label)||i.measureId]}));return r.map(i=>{var c;return{key:n.currencyPresentationTargetKey(i),label:i.kind==="metric"?((c=d.get(i.metricId))==null?void 0:c.label)||i.metricId:i.kind==="column"?i.columnKey:l.get(i.measureId)||i.measureId,target:i}})}function Go(s){return s?s.kind==="metric"?s.metricId:s.kind==="column"?s.columnKey:s.measureId:"invalid target"}function Qo({card:s,dashboardControls:a,resultColumnKeys:r=[],bindings:o,onChange:d}){const l=[...a,...s.controls||[]],i=l.filter(n.isCurrencyPresentationControl),c=C.useMemo(()=>Ho(s,r),[s,r]),u=C.useMemo(()=>n.getCardCurrencyPresentationTargets(s,r),[s,r]),m=n.diagnoseCurrencyPresentationBindings({bindings:o,controls:l,...u}),{preferences:x,resolveBoundCurrency:g}=n.useCardNumericPresentation(s,r),[p,h]=C.useState(""),[v,M]=C.useState(""),N=c.find(F=>F.key===v),b=!!(p&&N)&&!o.some(F=>F.presentationTarget&&N&&n.currencyPresentationTargetKey(F.presentationTarget)===N.key),w=F=>{if(!x)return;const S=n.resolveCurrencyPresentationTargetFormat({card:s,target:F,resultColumnKeys:r,valueFormatPreferences:x,boundCurrency:g(F)});if(S)return oa.formatNumericCanonical(1e3,S)};return i.length===0&&o.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a manual enum whose options are ISO currency codes to enable presentation currency bindings."}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h5",{className:"text-xs font-medium",children:"Currency presentation"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Change only the display currency for an explicit metric or column."})]}),o.map((F,S)=>e.jsxs("div",{className:"flex items-center gap-2 rounded-control border border-border/60 px-2 py-1.5 text-xs",children:[e.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[F.controlId," →"," ",Go(F.presentationTarget),F.presentationTarget?` · ${w(F.presentationTarget)??"unavailable"}`:null]}),e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>d(o.filter((y,k)=>k!==S)),children:e.jsx(n.Trash2,{className:"h-3.5 w-3.5"})})]},`${F.controlId}:${JSON.stringify(F.presentationTarget)}`)),m.length>0?e.jsx("div",{className:"space-y-1 text-xs text-destructive",children:m.map((F,S)=>e.jsxs("p",{children:[F.controlId?`${F.controlId}: `:"",F.code.split("_").join(" ")]},`${F.controlId||"binding"}:${F.code}:${S}`))}):null,e.jsxs("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2",children:[e.jsxs(t.Select,{value:p,onValueChange:h,children:[e.jsx(t.SelectTrigger,{size:"xs",children:e.jsx(t.SelectValue,{placeholder:"Currency control"})}),e.jsx(t.SelectContent,{children:i.map(F=>e.jsx(t.SelectItem,{value:F.id,children:F.label},F.id))})]}),e.jsxs(t.Select,{value:v,onValueChange:M,children:[e.jsx(t.SelectTrigger,{size:"xs",children:e.jsx(t.SelectValue,{placeholder:"Target"})}),e.jsx(t.SelectContent,{children:c.map(F=>e.jsx(t.SelectItem,{value:F.key,children:F.label},F.key))})]}),e.jsx(t.Button,{variant:"outline",size:"xs",disabled:!b,onClick:()=>{N&&(d([...o,{controlId:p,target:"presentation_currency",presentationTarget:N.target}]),M(""))},children:e.jsx(n.Plus,{className:"h-3.5 w-3.5"})})]})]})}const Wo=[];function Bs({className:s,triggerVariant:a="icon",label:r="Controls"}){var f,O;const{handleOpenChange:o,preventPassiveDismissDuringCreate:d,resolvedOpen:l,setIsCreateFlowActive:i}=Nt.useCreateFlowOverlayState({}),c=t.useEditorStore(D=>D.card),u=t.useEditorStore(D=>D.frame),m=t.useEditorStore(D=>D.queryResultColumns),x=t.useDashboardStore(D=>D.dashboard),p=t.useDashboardStore(D=>D.dashboard.controls)||Wo,{setCard:h,updateCardInFrame:v}=t.useEditorActions(),[M,N]=C.useState(null);C.useEffect(()=>{l&&!M&&(c!=null&&c.id)&&N(c.id)},[c==null?void 0:c.id,l,M]),C.useEffect(()=>{!l&&M!==null&&N(null)},[l,M]);const b=C.useMemo(()=>M?(u==null?void 0:u.cards.find(D=>D.id===M))||((c==null?void 0:c.id)===M?c:void 0):c,[c,u==null?void 0:u.cards,M]),w=(b==null?void 0:b.controls)||[],F=b?t.collectDashboardControlIds(x,{excludeCardId:b.id}):p.map(D=>D.id),S=((b==null?void 0:b.controlBindings)||[]).filter(n.isStructuralControlBinding),y=((b==null?void 0:b.controlBindings)||[]).filter(n.isPresentationCurrencyBinding),k=n.buildCardControlUsageById({card:b,controls:w}),E={choices:t.getFieldSelectorChoicesForCard(b),targetMap:Object.fromEntries((((f=b==null?void 0:b.config)==null?void 0:f.groupByColumns)||[]).map(D=>[D.id,D]))},A={choices:t.getMetricSelectorChoicesForCard(b),targetMap:Object.fromEntries((((O=b==null?void 0:b.config)==null?void 0:O.metricColumns)||[]).map(D=>[D.id,D]))},T=E.choices.map(D=>({option:D,target:E.targetMap[D.value]})),I=A.choices.map(D=>({option:D,target:A.targetMap[D.value]})),L=(D,R)=>{if(!b)return;const B=(R==null?void 0:R.type)==="rename"?t.applyControlMutationToCard(b,{type:"rename",oldId:R.oldId,newId:R.newId}):(R==null?void 0:R.type)==="remove"?t.applyControlMutationToCard(b,{type:"remove",controlId:R.controlId}):b,Y={...B,controls:D,controlBindings:t.syncStructuralBindingsWithControls(B.controlBindings,D)};v(Y),(c==null?void 0:c.id)===Y.id&&h(Y)},j=D=>{if(!b)return;const R={...b,controlBindings:[...t.mergeConfigBindingsWithSqlParamBindings(D,(b.controlBindings||[]).filter(B=>!n.isPresentationCurrencyBinding(B))),...y]};v(R),(c==null?void 0:c.id)===R.id&&h(R)},P=D=>{if(!b)return;const R={...b,controlBindings:[...(b.controlBindings||[]).filter(B=>!n.isPresentationCurrencyBinding(B)),...D]};v(R),(c==null?void 0:c.id)===R.id&&h(R)},V=a==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",V&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:l,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:V?e.jsxs(t.Button,{variant:"ghost",className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px]",(w.length>0||S.length>0)&&"text-primary"),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r}),w.length+S.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:w.length+S.length})]}):e.jsxs(n.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":w.length>0||S.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),w.length+S.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:w.length+S.length})]})}),e.jsxs(t.PopoverContent,{className:t.cn("flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",V&&"z-[60]"),align:"end",onEscapeKeyDown:d,onPointerDownOutside:d,children:[e.jsxs("div",{className:"space-y-1 border-b pb-4",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Card-only controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add controls that belong only to this card, or decide how this card should respond to shared dashboard controls."}),b!=null&&b.sql?e.jsx("p",{className:"text-xs text-muted-foreground",children:"SQL cards reference controls explicitly with syntax like `[[param.wac_type]]`."}):null]}),e.jsx("div",{className:"flex-1 overflow-y-auto pt-5",children:e.jsxs("div",{className:"space-y-5 pr-1",children:[e.jsx(Nt.ControlDefinitionListEditor,{scope:"card",card:b,controls:w,reservedControlIds:F,usageByControlId:k,availableFieldChoices:T,availableMetricChoices:I,onCreateFlowActiveChange:i,onChange:(D,R,B)=>L(D,B),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.jsxs(e.Fragment,{children:[e.jsx(Uo,{card:b,dashboardControls:p,bindings:S,onChange:j,availableFieldChoices:T,availableMetricChoices:I}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(Qo,{card:b,dashboardControls:p,resultColumnKeys:m,bindings:y,onChange:P})})]}):null]})})]})]})})}function Ea({showOrientation:s=!0,showGridStyle:a=!0,showInlineFilters:r=!0,showControls:o=!0,showDisplayOptions:d=!0}={}){const l=t.useEditorStore(h=>h.card),i=t.useEditorStore(h=>{var v,M;return(M=(v=h.card)==null?void 0:v.preferences)==null?void 0:M.chartOptions}),c=n.getChartGridStyle(i),{setChartGrid:u}=t.useEditorActions();function m(){const h=["xy","none","x","y"],M=(h.indexOf(c)+1)%h.length;u(h[M])}const x=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(l.type),g=a&&!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(l.type);return x||g||r||o||d?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[x&&e.jsx(e.Fragment,{children:e.jsx(_o,{})}),g&&e.jsxs(n.IconButton,{tooltip:"Grid Style",onClick:m,className:"h-7 w-7 px-0",children:[(c==="xy"||!c)&&e.jsx(n.Grid3x3,{className:"h-3.5 w-3.5"}),c==="x"&&e.jsx(As,{className:"h-3.5 w-3.5"}),c==="y"&&e.jsx(n.Rows3,{className:"h-3.5 w-3.5"}),c==="none"&&e.jsx(n.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(Os,{}),o&&e.jsx(Bs,{}),d&&e.jsx(Ps,{})]}):null}function Jo({errorMessage:s,errorSql:a,onOpenInEditor:r,onDebugWithAssistant:o}){const{feedbackDialogOpen:d,setFeedbackDialogOpen:l,handleSendFeedback:i,feedbackPayload:c}=va(s,a);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-auto px-4 py-0",children:e.jsx(cs,{error:s,errorSql:a,errorMessageClassName:"max-h-40",fillAvailableSqlHeight:!0,className:"max-h-none",onOpenInEditor:r,onDebugWithAssistant:o,onSendFeedback:i,showFeedbackButton:!0})}),e.jsx(n.FeedbackDialog,{open:d,onOpenChange:l,feedbackData:c,showDebugInfo:!0})]})}function Xo({isPreviewMode:s,onPreviewToggle:a,configCard:r}){var O,D,R,B,Y;const o=t.useEditorStore(_=>_.frame),d=t.useEditorStore(_=>_.card),l=t.useEditorStore(_=>_.editorContext),i=(l==null?void 0:l.type)==="documentSection",{setFrame:c,setActiveTabCardId:u,setCard:m,updateCardInFrame:x,clearModeDrafts:g,initializeModeDrafts:p}=t.useEditorActions(),{manifest:h}=n.useCustomVisual(((O=r==null?void 0:r.customCardPreferences)==null?void 0:O.url)||""),v=(D=h==null?void 0:h.visuals)==null?void 0:D.find(_=>{var z;return _.name===((z=r==null?void 0:r.customCardPreferences)==null?void 0:z.componentName)}),N=he.resolveMultiInputType(r,v)==="multiple",b=(v==null?void 0:v.minInputs)??((R=r==null?void 0:r.customCardPreferences)==null?void 0:R.minInputs)??1,w=(v==null?void 0:v.maxInputs)??((B=r==null?void 0:r.customCardPreferences)==null?void 0:B.maxInputs),F=C.useMemo(()=>he.getCustomVisualInputCards({frame:o,configCard:r,isMultiInputVisual:N}),[o,r,N]),S=N?F.filter(Boolean).length:o.cards.length,y=i?!1:w?S<w:!0,k=S>Math.max(b||1,1),E=!!((Y=r==null?void 0:r.customCardPreferences)!=null&&Y.dataInputCardIds),A=(_,z)=>{_.dataTransfer.setData("tabIndex",z.toString())},T=_=>{_.preventDefault()},I=(_,z)=>{const U=_.dataTransfer.getData("tabIndex");if(U===z.toString())return;const G=Array.from(o.cards),[q]=G.splice(parseInt(U),1);G.splice(z,0,q),c({...o,cards:G})};function L(_){const z=(r==null?void 0:r.id)===_;if(!(E&&z?o.cards.length>1:k))return;let G=o.cards.filter(se=>se.id!==_);N&&!E&&(G=he.reindexSlotCards(G));const q=G[0],Q={...o,cards:G,activeCardId:q.id},H=_===d.id;H&&g(),c(Q),u(q.id),m(q),H&&p(q)}function j(_,z){if(!y)return;const U={...o,cards:[...o.cards,z],activeCardId:_.id};c(U),u(z.id)}function P(){if(i)return;if(N&&(r==null?void 0:r.id)===d.id){V(d);return}const _={...d,id:Ke.v4(),title:`${d.title} Copy`,tabTitle:`${d.tabTitle||d.title} Copy`,customCardPreferences:d.customCardPreferences?{...d.customCardPreferences,slotIndex:N?Math.max(-1,...F.map((z,U)=>he.getSlotIndexForCard(z,U)))+1:d.customCardPreferences.slotIndex}:void 0};j(d,_)}function V(_){var H;if(i||!y)return;let z=N?"table":"bar",U="Title",G="";const q=N?Math.max(-1,...F.map((se,ce)=>he.getSlotIndexForCard(se,ce)))+1:S;if(N&&((H=v==null?void 0:v.slots)!=null&&H.length)){const se=he.getSlotDefinitionForIndex(v.slots,q);se&&(z=he.getSlotExpectedChartType(se),U=se.label||`Tab ${q+1}`,G=se.description||"")}const Q={dataSource:_.dataSource,connectionId:_.connectionId,lastSelectedDatabase:_.lastSelectedDatabase,lastSelectedSchema:_.lastSelectedSchema,lastSelectedTable:_.lastSelectedTable,lastSelectedDatamodelId:_.lastSelectedDatamodelId,id:Ke.v4(),title:U,tabTitle:U,description:G,preferences:{onClickFilter:[{columnIndex:0,expression:""}],...z==="text"?{textVisualOptions:{richContent:t.createEmptyRichContent()}}:{}},type:z,sql:"",data:[],mode:"explorer",...N&&{customCardPreferences:{slotIndex:q}}};j(_,Q)}function f(_,z){return _.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||_.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const U=z.displayTab===void 0?!1:!z.displayTab;m({...z,displayTab:U}),x({...z,displayTab:U})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx(Ye.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(n.EyeOff,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{variant:"underline",className:"group flex h-9 shrink-0 items-center justify-start gap-1 overflow-x-auto rounded-none border-b-0 border-t border-border bg-background px-4",children:e.jsxs("div",{className:"flex items-center gap-1",children:[o.cards.map((_,z)=>{var H,se;const U=N?he.getSlotIndexForCard(_,z):-1,G=N&&((H=v==null?void 0:v.slots)!=null&&H.length)&&U>=0?he.getSlotDefinitionForIndex(v.slots,U):null,q=G?(Array.isArray(G.expectedType)?G.expectedType[0]:G.expectedType)||"table":_.type,Q=N&&((se=v==null?void 0:v.slots)==null?void 0:se.length)&&v.slots.every(ce=>typeof ce.position=="number"||typeof ce.position=="string"&&!ce.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!N&&!i,onDragStart:N||i?void 0:ce=>A(ce,z),onDragOver:N||i?void 0:T,onDrop:N||i?void 0:ce=>I(ce,z),className:t.cn("inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[5px] border px-2 text-[12px] font-normal text-muted-foreground transition-colors","mb-0 border-transparent pb-0","hover:bg-muted/40 hover:text-foreground","data-[state=active]:border-border data-[state=active]:bg-card data-[state=active]:text-foreground"),value:_.id,children:[N&&G?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:n.getChartIconByType(q,"size-3.5")}),e.jsx("span",{children:G.label||`Tab ${U+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:G.label}),G.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:G.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[G.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(G.expectedType)?G.expectedType.join(" / "):G.expectedType}),G.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:[f(o,_),e.jsx(n.Editable,{enabled:o.activeCardId===_.id,text:_.tabTitle||_.title,onSave:ce=>{m({...d,tabTitle:ce}),x({...d,tabTitle:ce})},children:_.tabTitle||_.title},_.id)]}),!i&&o.activeCardId===_.id&&!Q&&e.jsx(n.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ce=>{ce.stopPropagation(),P()}}),!i&&o.activeCardId===_.id&&(E&&(r==null?void 0:r.id)===_.id?o.cards.length>1:k)&&e.jsx(oe.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>L(_.id)})]},_.id)}),!i&&e.jsx(n.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>V(d),disabled:!y,children:e.jsx(n.Plus,{className:"h-3 w-3"})}),N&&e.jsxs(n.Toggle,{pressed:s,onPressedChange:a,size:"sm",className:"ml-1 h-6 gap-1 rounded-[5px] px-2 text-[11px] data-[state=on]:bg-muted data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[s?e.jsx(n.EyeOff,{className:"h-3 w-3"}):e.jsx(Ye.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function kt({renderCardOverride:s,alwaysRenderOverride:a=!1}={}){var We,_e,Xe,Ze,et;const r=n.useResolvedTemporalStylePreferences(),o=t.useEditorStore(re=>re.frame),d=t.useEditorStore(re=>re.card),[l,i]=C.useState(!1),c=C.useMemo(()=>he.findCustomVisualConfigCard(o,d),[o,d]),u=t.useEditorStore(re=>re.isSqlRunning);t.useEditorStore(re=>re.isDevMode);const{setFrame:m,setActiveTabCardId:x,setCard:g,setRunSql:p,mergeDraftsIntoCard:h,clearModeDrafts:v,initializeModeDrafts:M}=t.useEditorActions(),[N,b]=C.useState({}),[w,F]=C.useState(()=>new Set),{authToken:S}=n.useSemaphorContext(),y=t.getTokenParams(S==null?void 0:S.accessToken),{compiledAppearance:k}=t.useAppearance(),E=C.useMemo(()=>n.buildCustomCardTheme(k),[k]),{getCard:A,manifest:T,isLoading:I}=n.useCustomVisual(((We=c==null?void 0:c.customCardPreferences)==null?void 0:We.url)||""),L=(_e=c==null?void 0:c.customCardPreferences)==null?void 0:_e.componentName,j=L?A(L):null,P=(Xe=T==null?void 0:T.visuals)==null?void 0:Xe.find(re=>re.name===L),V=he.resolveMultiInputType(c,P),f=l&&V==="multiple"&&!!c,O=C.useMemo(()=>he.getCustomVisualInputCards({frame:o,configCard:c,isMultiInputVisual:!0}).map(J=>(J==null?void 0:J.id)===d.id?d:J),[o,c,d]),D=C.useMemo(()=>he.buildSlotOrderedCards(O),[O]),R=C.useMemo(()=>{const re=O.findIndex(J=>(J==null?void 0:J.id)===d.id);return re<0?-1:he.getSlotIndexForCard(d,re)},[O,d]),B=C.useMemo(()=>!c||V!=="multiple"||R<0?d.type:he.getEffectiveCardTypeForSlot(d,R,P==null?void 0:P.slots)??d.type,[c,V,R,d,P==null?void 0:P.slots]),Y=C.useMemo(()=>f?{...d,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:B!==d.type?{...d,type:B}:d,[d,B,f]),{data:_,dataUpdatedAt:z,isLoading:U,isFetching:G,isError:q,errorMessage:Q,errorSql:H,queryKey:se}=n.useEditorCardQuery(Y),ce=JSON.stringify(se),{handleOpenInEditor:ge,handleDebugWithAssistant:fe}=Fs(Q,H||d.sql||d.python),Te=d.type==="text"&&((et=(Ze=d.preferences)==null?void 0:Ze.textVisualOptions)==null?void 0:et.isDynamicText)===!0&&!!Q,Ve=C.useCallback((re,J)=>{const pe=he.normalizeMultiInputPayload(J);b(ue=>({...ue,[re]:pe}))},[]),Ue=C.useCallback((re,J)=>{F(pe=>{const ue=new Set(pe);return J?ue.add(re):ue.delete(re),ue})},[]),Me=w.size>0,Ee=C.useMemo(()=>D.map((re,J)=>he.getEffectiveCardTypeForSlot(re,J,P==null?void 0:P.slots)),[D,P==null?void 0:P.slots]),Fe=C.useMemo(()=>n.createCustomVisualTemporalBucketFormatter(n.buildMultiInputTemporalPresentationInputs({slotOrderedCards:D,multiInputData:N,valueFormatPreferences:r})),[N,D,r]),Oe=t.useInteractionStore(re=>re.interactionStates),Pe=t.useDashboardStore(re=>{var J;return(J=re.dashboard)==null?void 0:J.id}),le=t.useDashboardStore(re=>re.dashboard.filters),De=t.useDashboardStore(re=>re.filterValues),ve=t.useDashboardStore(re=>re.selectedSheetId),Ie=t.useEditorStore(re=>re.inlineFilterValuesMap[(c==null?void 0:c.id)||""]),$=t.useEditorStore(re=>re.actions.setCardInlineFilterValue),xe=t.useEditorStore(re=>re.actions.removeCardInlineFilterValue),Ce=C.useMemo(()=>c?n.buildInlineFilterNodes({card:c,sheetId:ve||"",inlineFilterValues:Ie,setInlineFilterValue:re=>$(c.id,re),removeInlineFilterValue:re=>xe(c.id,re)}):[],[c,ve,Ie,$,xe]),{cardFilters:ae,cardFilterValues:ie}=C.useMemo(()=>c?n.calculateContextAwareFilters({card:c,interactionStates:Oe,currentDashboardId:Pe,filters:le,filterValues:De,selectedSheetId:ve}):{cardFilters:[],cardFilterValues:[]},[c,Oe,Pe,le,De,ve]);function Re(re){const J=o.cards.find(pe=>pe.id===re);J&&(n.flushPendingEditorDrafts(),h(),Z(re),x(re),v(),M(J))}function Z(re){const J=t.useEditorStore.getState().card,pe=t.useEditorStore.getState().frame,ue={...pe,cards:pe.cards.map(me=>me.id===J.id?J:me),activeCardId:re};m(ue);const ne=ue.cards.find(me=>me.id===re);ne.sql&&p(!0),g(ne)}function Ae(){return I?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})}):j?e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[O.map((J,pe)=>{if(!J)return null;const ue=he.getSlotIndexForCard(J,pe),ne=he.getEffectiveCardTypeForSlot(J,ue,P==null?void 0:P.slots);return e.jsx(n.MultiInputEmptyRenderer,{onLoadingStatus:Ue,onDataChange:Ve,card:J,effectiveCardType:ne},`${J.id}-${ue}`)}),Me&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(n.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",Me&&"opacity-50"),children:e.jsx(C.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(j,{editing:!0,...n.buildMultiInputCustomVisualProps({configCard:c,slotOrderedCards:D,slotTypes:Ee,multiInputData:N,params:y,theme:E,filters:ae,filterValues:[...ie||[],...Ie||[]],inlineFilters:Ce,formatTemporalBucketValue:Fe})})})})]}):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."})}function ze(){var re;return f?Ae():s&&(a||!U&&!G&&!q&&!Q)?s({card:d,data:_,isLoading:U,isFetching:G,isError:q}):d.type==="kpi"?U||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):Q?e.jsx(Jo,{errorMessage:Q,errorSql:H||d.sql||d.python,onOpenInEditor:ge,onDebugWithAssistant:fe}):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("div",{className:"rounded-md border border-border",children:e.jsx(n.KPICard,{card:d,data:_==null?void 0:_.records,isPending:U||G,isError:q,comparisonMetadata:(re=_==null?void 0:_.metadata)==null?void 0:re.comparisonMetadata})}),n.isCardSummaryVisibleOnCard(d)&&e.jsx(n.CardSummary,{card:d,mode:"editor",records:_==null?void 0:_.records})]})}):d.type==="text"?U||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):Te?e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-auto px-4 py-0",children:e.jsx(cs,{error:Q,errorSql:H||d.sql||d.python,onOpenInEditor:ge,onDebugWithAssistant:fe,showFeedbackButton:!1})}):e.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 py-4",children:e.jsx(n.TextCard,{isLoading:u,card:d,data:_==null?void 0:_.records})}):e.jsx(n.ErrorBoundary,{FallbackComponent:n.FallbackVisual,resetKeys:[ce,z,G],children:e.jsx(ya,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Re,value:o.activeCardId,className:"flex min-h-0 flex-1 flex-col",children:[f?e.jsx("div",{className:"mt-0 min-h-0 flex-1 overflow-hidden",children:ze()}):o.cards.map(re=>e.jsx(t.TabsContent,{className:"mt-0 min-h-0 flex-1 overflow-hidden focus-visible:ring-0 focus-visible:ring-offset-0",value:re.id,children:ze()},re.id)),e.jsx(Xo,{isPreviewMode:f,onPreviewToggle:i,configCard:c})]})}function Zo({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 Ia({fallbackPreview:s,records:a,title:r,isInspectorOpen:o,onInspectorOpenChange:d}){var P;const l=t.useEditorStore(V=>V.card),i=t.useEditorStore(V=>V.actions.setCard),c=t.useEditorStore(V=>V.actions.updateCardInFrame),u=t.normalizeDynamicRendererSource((P=l.dynamicCardPreferences)==null?void 0:P.rendererCode),[m,x]=C.useState(u),[g,p]=C.useState(u);C.useEffect(()=>{x(u),p(u)},[u,l.id]);const h=C.useMemo(()=>t.normalizeDynamicRendererSource(m),[m]),v=C.useMemo(()=>t.validateDynamicRendererSource(h),[h]),M=!!u,N=C.useMemo(()=>{var V;return t.buildCardWithVisualizationMode(l,g?"dynamic":"builtin",{rendererCode:g||void 0,artifactId:((V=l.dynamicCardPreferences)==null?void 0:V.artifactId)||l.id,title:r||l.title})},[l,g,r]),b=!!g,w=h!==g,F=g!==u,S=!h||!v.valid||w||F,y=h?v.valid?w?"Unapplied changes":"Pending save":"Needs attention":"Draft",k=!h||w||F?"outline":"destructive",E=h?v.valid?w?"The preview still reflects the last applied code until you apply this draft.":F?"Preview reflects pending changes. Accept changes to save them.":"":v.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function A(){if(!v.valid){n.ue.error(v.error||"Visual code is invalid.");return}p(h),n.ue.success("Dynamic preview updated.")}function T(){x(g)}function I(){var f;const V=t.buildCardWithVisualizationMode(l,g?"dynamic":"builtin",{rendererCode:g||void 0,artifactId:((f=l.dynamicCardPreferences)==null?void 0:f.artifactId)||Ke.v4(),title:r||l.title});i(V),c(V),d(!1),n.ue.success(g?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function L(){x(u),p(u),d(!1)}function j(){x(""),p("")}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:M?e.jsx(n.PersistedDynamicVisual,{card:l,records:a,title:r,layoutMode:"fill",fallback:s},u||"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(n.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(Zo,{onClick:()=>d(!0)})]})}),e.jsx(n.Dialog,{open:o,onOpenChange:V=>{if(!V){L();return}d(!0)},children:e.jsxs(n.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(n.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(n.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(n.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),S&&e.jsx(n.Badge,{className:"mr-4 shrink-0",variant:k,children:y})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.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:b?e.jsx(n.PersistedDynamicVisual,{card:N,records:a,title:r,layoutMode:"fill",fallback:s},g||"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(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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(n.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(n.AlertDialog,{children:[e.jsx(n.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:!M&&!h,children:[e.jsx(oe.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(n.AlertDialogContent,{children:[e.jsxs(n.AlertDialogHeader,{children:[e.jsx(n.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(n.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(n.AlertDialogFooter,{children:[e.jsx(n.AlertDialogCancel,{children:"Cancel"}),e.jsx(n.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:j,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:T,disabled:!w,children:[e.jsx(t.RotateCcw,{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:A,disabled:!w||!v.valid,children:[e.jsx(n.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:[E&&e.jsx("p",{className:t.cn("text-xs",v.valid?"text-muted-foreground":"text-destructive"),children:E}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!v.valid&&h&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:m,onValueChange:V=>x(V||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(n.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:E||"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:L,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:I,disabled:!F,children:"Accept changes"})]})]})]})})]})}function Da({onCustomize:s}){const a=t.useEditorStore(m=>m.card),r=t.useEditorStore(m=>m.frame),o=t.useEditorStore(m=>m.actions.setIsShowingVisual),{setVisualizationMode:d,setDynamicCardPreferences:l}=t.useEditorActions(),c=t.getVisualizationMode(a)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(a))return null;const u=m=>{var x;m==="dynamic"&&!a.dynamicCardPreferences&&l(t.createEmptyDynamicCardPreferences(a.type,(x=a.preferences)==null?void 0:x.displayOptions)),d(m),o(!0)};return e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onSelect:m=>{m.preventDefault(),u(c?"builtin":"dynamic")},className:"flex items-center justify-between gap-2 text-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.CodeXml,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{size:"xs",checked:c,onCheckedChange:m=>u(m?"dynamic":"builtin"),onClick:m=>m.stopPropagation()})]}),c&&s?e.jsxs(n.DropdownMenuItem,{onSelect:m=>{m.preventDefault(),s()},className:"gap-2 text-[13px]",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),"Customize Visual"]}):null]})}function ka({sql:s,showCardDetails:a=!1,debugPayloads:r,className:o}){const[d,l]=C.useState(!1),i=t.useEditorStore(x=>x.isDevMode),{switchEditorMode:c,setRunSql:u}=t.useEditorActions(),m=()=>{c("dev",{sqlToLoad:s}),setTimeout(()=>{u(!0)},100)};return e.jsx(xa,{className:t.cn("overflow-hidden",o),children:e.jsx(ba,{sql:s,label:"Generated query",ariaLabel:"Executed SQL",copyAriaLabel:"Copy generated query",headerActions:i?void 0:e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{onClick:m,variant:"outline",size:"xs",className:Pt,children:"Open in SQL editor"}),a&&e.jsx(fa,{isOpen:d,onClick:()=>l(x=>!x)})]}),className:"min-h-0",bodyClassName:"max-h-[min(420px,calc(var(--radix-hover-card-content-available-height,100vh)-3rem))]",children:d&&a&&e.jsx(ga,{debugPayloads:r})})})}function ys({children:s,visualAsideControl:a,mode:r="both",inlineToolbar:o=!1,overflowActions:d,isDynamicInspectorOpen:l,onDynamicInspectorOpenChange:i}){var Xe,Ze,et,re,J,pe,ue;const c=n.useQueryClient(),u=t.useEditorStore(ne=>ne.frame),m=t.useEditorStore(ne=>ne.card),x=t.useEditorStore(ne=>ne.isDevMode),g=t.useEditorStore(ne=>ne.editorContext),p=(g==null?void 0:g.type)==="documentSection",h=t.useEditorStore(ne=>ne.isShowingVisual),v=t.useEditorStore(ne=>ne.actions.setIsShowingVisual),M=t.useDashboardStore(ne=>ne.isVisualEditing),{isConsoleMode:N}=n.useDashboardPreferences(),b=t.useEditorStore(ne=>ne.pythonStdOut),w=t.useEditorStore(ne=>ne.actions.setRunSql),F=n.useEffectiveEditorCardType(),S=F==="table"||F==="detailTable"||F==="matrixTable",y=m.type==="table"||m.type==="detailTable",E=t.supportsRegularTableSettings(F)&&!!(a!=null&&a.onOpen),T=t.getVisualizationMode(m)==="dynamic",[I,L]=C.useState(!1),j=l??I,P=i??L,{setFrame:V,setCard:f,setActiveTabCardId:O,setCardPreferences:D,mergeDraftsIntoCard:R,clearModeDrafts:B,initializeModeDrafts:Y,updatePageSize:_,updateCardInFrame:z,setCardType:U}=t.useEditorActions(),G=C.useMemo(()=>F!==m.type?{...m,type:F}:m,[m,F]),{data:q,isLoading:Q,isFetching:H,errorMessage:se,errorSql:ce,refetch:ge,queryKey:fe,pagination:Te}=n.useEditorCardQuery(G),Ve=C.useRef(fe);Ve.current=fe;const{handleDebugWithAssistant:Ue}=Fs(se,ce),Me=C.useMemo(()=>(q==null?void 0:q.records)||[],[q==null?void 0:q.records]),{cardFilterValues:Ee}=mo((m==null?void 0:m.id)??""),[Fe,Oe]=C.useState(!1),Pe=((Ze=(Xe=m.preferences)==null?void 0:Xe.tablePrefs)==null?void 0:Ze.enableDevModePagination)??!1,le=C.useMemo(()=>{var ne,me;return n.getTablePageSizeOptions((me=(ne=m.preferences)==null?void 0:ne.tablePrefs)==null?void 0:me.pageSize)},[(re=(et=m.preferences)==null?void 0:et.tablePrefs)==null?void 0:re.pageSize]),De=n.resolveTablePageSize((pe=(J=m.preferences)==null?void 0:J.tablePrefs)==null?void 0:pe.pageSize);C.useEffect(()=>{H||Oe(!1)},[H]);const ve=()=>{if(Oe(!0),x){n.flushPendingEditorDrafts(),setTimeout(()=>{c.removeQueries({queryKey:Ve.current,exact:!0}),w(!0)},0);return}ge()},Ie=ne=>{var me;D({...m.preferences,tablePrefs:{...(me=m.preferences)==null?void 0:me.tablePrefs,enableDevModePagination:ne}})},$=ne=>{var $e;const me=Number(ne),qe={...m,preferences:{...m.preferences,tablePrefs:{...($e=m.preferences)==null?void 0:$e.tablePrefs,pageSize:me}},paginationConfig:{page:1,pageSize:me}};f(qe),z(qe),m.sql&&Pe&&w(!0)};C.useEffect(()=>{S&&!h&&!x&&!N&&v(!0)},[N,x,S,h,v]);function xe(ne,me){var Je,Ge;const qe={...m,paginationConfig:{page:ne+1,pageSize:me}};f(qe);const $e={...u,cards:u.cards.map(st=>st.id===m.id?qe:st)};V($e),m.sql&&((Ge=(Je=m.preferences)==null?void 0:Je.tablePrefs)!=null&&Ge.enableDevModePagination)&&w(!0)}function Ce(ne){var Je,Ge,st,St,dt;const me=n.sortStateToSortByColumns(ne,(Je=m.config)==null?void 0:Je.metricColumns,(Ge=m.config)==null?void 0:Ge.groupByColumns,(st=m.config)==null?void 0:st.detailColumns),qe={...m,config:{...m.config||{},sortByColumns:me}};f(qe);const $e={...u,cards:u.cards.map(pt=>pt.id===m.id?qe:pt)};V($e),m.sql&&((dt=(St=m.preferences)==null?void 0:St.tablePrefs)!=null&&dt.enableDevModePagination)&&w(!0)}const ae=Array.isArray(q==null?void 0:q.records)?q.records:[],ie=ae.length>0;function Re(){var me;if(!ie)return;const ne=JSON.stringify(ae,null,2);typeof navigator>"u"||!((me=navigator.clipboard)!=null&&me.writeText)||navigator.clipboard.writeText(ne).catch(qe=>{console.error("Failed to copy JSON",qe)})}function Z(){if(!ie)return;const ne=JSON.stringify(ae,null,2),me=new Blob([ne],{type:"application/json"}),qe=URL.createObjectURL(me),$e=document.createElement("a");$e.href=qe,$e.download=`${m.title}.json`,$e.click()}function Ae(){if(!ie)return;const me=[Object.keys(ae.reduce((Ge,st)=>({...Ge,...st}),{})).join(","),...ae.map(Ge=>Object.values(Ge).join(","))].join(`
|
|
172
|
-
`),qe=new Blob([me],{type:"text/csv"}),$e=URL.createObjectURL(qe),Je=document.createElement("a");Je.href=$e,Je.download=`${m.title}.csv`,Je.click()}if(!m)return e.jsx(e.Fragment,{children:"No Active Card"});const ze=r==="both"||r==="toolbar",We=r==="both"||r==="canvas",_e=!Q&&!H&&!se&&(q!=null&&q.sql)?e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:o?e.jsx(n.IconButton,{className:"h-7 w-7 shrink-0 px-0",buttonProps:{"aria-label":"View executed SQL"},children:e.jsx(br,{className:"h-3.5 w-3.5",strokeWidth:1.75})}):e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"Executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",collisionPadding:16,className:"w-[500px] overflow-hidden p-0",children:e.jsx(ka,{sql:q.sql})})]})}):null;return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",o?"ml-auto min-w-0 shrink-0":r==="toolbar"?"h-auto pb-1":t.cn("h-full",!S&&"pt-2")),children:[ze&&e.jsxs("div",{className:t.cn("z-10 mb-0 flex items-center",o?"min-w-0 shrink-0 gap-1.5":"min-h-10 gap-2 px-4"),children:[o?_e:null,h&&e.jsx("div",{className:t.cn("flex items-center",o?"shrink-0":"grow gap-4"),children:e.jsx("div",{className:"flex items-center gap-3",children:!p&&!T&&e.jsx(Ta,{selectedChart:m.type,onChartChange:ne=>U(ne),compactMore:!0,responsiveCompact:o})})}),!h&&!o&&e.jsx("div",{className:"grow"}),e.jsxs("div",{className:t.cn("flex items-center text-muted-foreground",o?"gap-1.5":"gap-2"),children:[s,o?null:_e,Ee&&Ee.length>0&&e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(n.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(n.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:Ee.length})]})}),e.jsxs(n.HoverCardContent,{align:"end",className:"flex max-h-[400px] w-[500px] flex-col overflow-hidden p-0",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(t.CodeEditor,{value:JSON.stringify(Ee,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),!T&&e.jsx("div",{className:o?"hidden @[1250px]:flex":"",children:e.jsx(Ea,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1})}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"ghost",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 shrink-0 gap-1.5 text-[12px]",o?"hidden w-7 px-0 @[850px]:inline-flex @[1350px]:w-auto @[1350px]:px-2":"px-2",a.isOpen&&"bg-accent text-accent-foreground"),children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{className:o?"hidden @[1350px]:inline":"",children:"Settings"})]}),(x||N)&&y&&e.jsx(tl,{enabled:Pe,selectedPageSize:De,pageSizeOptions:le,onEnabledChange:Ie,onPageSizeChange:$,responsive:o}),e.jsx(n.IconButton,{tooltip:"Refresh",disabled:Q||H,className:t.cn("h-7 w-7 px-0",o&&"hidden @[1150px]:inline-flex"),onClick:ve,children:e.jsx(Ds,{className:t.cn("h-3.5 w-3.5",{"animate-spin":Fe})})}),e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",collisionPadding:8,className:"max-h-[var(--radix-dropdown-menu-content-available-height)] w-56 overflow-y-auto overscroll-contain",children:[(o||(d==null?void 0:d.reset))&&e.jsxs(e.Fragment,{children:[o&&e.jsxs(n.DropdownMenuItem,{disabled:Q||H,onSelect:ve,children:[e.jsx(Ds,{className:"h-3.5 w-3.5"}),"Refresh result"]}),d==null?void 0:d.reset,e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Ae,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Z,className:"gap-2 text-[13px]",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Re,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]}),e.jsx(n.DropdownMenuSeparator,{}),(d==null?void 0:d.query)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"Query"}),d.query,e.jsx(n.DropdownMenuSeparator,{})]}),(o&&(a==null?void 0:a.show)||x||N)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"Output"}),o&&(a==null?void 0:a.show)&&e.jsx(n.DropdownMenuCheckboxItem,{checked:a.isOpen,onCheckedChange:()=>a.onToggle(),children:"Settings"}),(x||N)&&e.jsx(n.DropdownMenuCheckboxItem,{checked:!h,onCheckedChange:ne=>v(ne!==!0),children:"Show raw results"}),o&&(x||N)&&y&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuCheckboxItem,{checked:Pe,onCheckedChange:ne=>Ie(ne===!0),children:"Paginate results"}),Pe&&e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:["Page size",e.jsx("span",{className:"ml-auto tabular-nums text-muted-foreground",children:De})]}),e.jsx(n.DropdownMenuSubContent,{children:e.jsx(n.DropdownMenuRadioGroup,{value:String(De),onValueChange:$,children:le.map(ne=>e.jsx(n.DropdownMenuRadioItem,{value:String(ne),children:ne},ne))})})]})]}),e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!T&&!["table","detailTable","custom"].includes(m.type)&&M&&e.jsx(Mo,{triggerVariant:"menu",className:"w-full"}),e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),E&&e.jsxs(n.DropdownMenuItem,{onSelect:()=>{var ne;return(ne=a==null?void 0:a.onOpen)==null?void 0:ne.call(a,"style")},className:"gap-2 text-[13px]",children:[e.jsx(Tr,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(Da,{onCustomize:()=>P(!0)})]})]})]})]}),We&&(h?T?e.jsx(kt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ia,{fallbackPreview:e.jsx(kt,{}),records:Me,title:m.title,isInspectorOpen:j,onInspectorOpenChange:P})}):e.jsx(kt,{}):e.jsxs(n.ResizablePanelGroup,{className:t.cn(b&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[b&&e.jsxs(e.Fragment,{children:[e.jsx(n.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:b&&e.jsx(el,{})}),e.jsx(n.ResizableHandle,{})]}),e.jsxs(n.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":b}),children:[Array.isArray(q==null?void 0:q.records)&&!se&&(x?e.jsx(fo,{data:q.records,card:G,paginationMetadata:Te,onPaginationChange:xe,onPageSizePreferenceChange:_,onSortChange:Ce,isLoading:Q||H}):q.records.length>0?e.jsx(n.TableVisual,{card:m,data:Me,resultColumns:q==null?void 0:q.columns,columnKeyMap:q==null?void 0:q.columnKeyMap,totalsByColumnId:q==null?void 0:q.tableTotalsByColumnId,comparisonMetadata:(ue=q==null?void 0:q.metadata)==null?void 0:ue.comparisonMetadata,paginationMetadata:Te,onPaginationChange:xe,onSortChange:Ce,isLoading:Q||H}):null),se&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(cs,{error:se,errorSql:ce||m.sql||m.python,onDebugWithAssistant:Ue,showFeedbackButton:!1})})]})]}))]})}function el(){const s=t.useEditorStore(r=>r.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 tl({enabled:s,selectedPageSize:a,pageSizeOptions:r,onEnabledChange:o,onPageSizeChange:d,responsive:l}){return e.jsxs("div",{className:t.cn("items-center gap-2",l?s?"flex":"hidden @[1550px]:flex":"flex"),children:[e.jsx(n.Checkbox,{id:"dev-pagination","aria-label":"Paginate results",title:l&&s?"Pagination enabled":void 0,checked:s,onCheckedChange:i=>o(i===!0)}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:t.cn("cursor-pointer text-[13px]",l&&"hidden @[1550px]:block"),children:"Paginate"}),s&&e.jsxs(t.Select,{value:String(a),onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-7 w-20 rounded-[5px] px-2 text-[12px]",l&&"hidden @[1550px]:flex"),children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:r.map(i=>e.jsx(t.SelectItem,{value:String(i),children:i},i))})]})]})}function at({value:s,onCommit:a,type:r="text",placeholder:o,className:d}){const[l,i]=C.useState(s),c=C.useRef(!1);C.useEffect(()=>{i(s)},[s]);const u=()=>{if(c.current){c.current=!1;return}l!==s&&a(l)},m=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(s),x.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:l,onChange:x=>i(x.target.value),onBlur:u,onKeyDown:m,className:d})}function Ct({defaultValue:s,label:a,options:r,value:o,onValueChange:d,className:l,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function sl(s,a){return he.getSlotDefinitionForIndex(s,a)||null}function Ht(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,o,d]=a;return`Tabs ${Number(o)+1}-${Number(d)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function nl(s){return s?Array.isArray(s)?s:[s]:[]}function Cs(s){var o,d;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const a=!!((d=s.sql)!=null&&d.trim()),r=Ke.hasValidCardConfig(s.config);return a||r}function al({slots:s,cards:a,minInputs:r}){const o=[],d=a.filter(Boolean).length;return r&&d<r&&o.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(l=>{if(!l.required)return;if(typeof l.position=="number"){const u=a[l.position];Cs(u)||o.push({type:"missing-required",message:`${Ht(l.position)} ("${l.label}") is required but has no data configured.`});return}const i=l.position.match(/^(\d+)-(\d+)$/);if(i){const[,u,m]=i.map(Number);for(let x=u;x<=m;x+=1){const g=a[x];if(!Cs(g)){o.push({type:"missing-required",message:`${Ht(x)} ("${l.label}") is required but has no data configured.`});break}}return}const c=l.position.match(/^(\d+)\+$/);if(c){const u=Number(c[1]);if(a.length<=u){o.push({type:"missing-required",message:`${Ht(u)} ("${l.label}") is required but has no data configured.`});return}for(let m=u;m<a.length;m+=1){const x=a[m];if(!Cs(x)){o.push({type:"missing-required",message:`${Ht(m)} ("${l.label}") is required but has no data configured.`});break}}}}),a.forEach((l,i)=>{if(!l)return;const c=sl(s,i);if(!c||!c.expectedType)return;const u=nl(c.expectedType);u.length!==0&&(u.includes(l.type)||o.push({type:"wrong-type",message:`${Ht(i)} ("${c.label}") expects ${u.join(", ")}, but is configured as ${l.type}.`}))})),o}const rl={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 Ma(){var j,P,V;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],o=t.useEditorStore(f=>f.card),d=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:l}=t.useEditorActions(),i=C.useMemo(()=>he.findCustomVisualConfigCard(d,o),[d,o]),c=i==null?void 0:i.customCardPreferences,{components:u,manifest:m}=n.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),x=(j=m==null?void 0:m.visuals)==null?void 0:j.find(f=>f.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),p=he.resolveMultiInputType(i||o,x)==="multiple",h=!!i&&i.id===o.id,v=(x==null?void 0:x.minInputs)??((P=i==null?void 0:i.customCardPreferences)==null?void 0:P.minInputs),M=(x==null?void 0:x.maxInputs)??((V=i==null?void 0:i.customCardPreferences)==null?void 0:V.maxInputs),N=C.useMemo(()=>he.getCustomVisualInputCards({frame:d,configCard:i||o,isMultiInputVisual:p}),[d,i,o,p]),b=C.useMemo(()=>he.buildSlotOrderedCards(N),[N]),w=C.useMemo(()=>b.map((f,O)=>{if(!f)return null;const D=he.getSlotIndexForCard(f,O),R=he.getEffectiveCardTypeForSlot(f,D,x==null?void 0:x.slots);return{...f,type:R??f.type}}),[b,x==null?void 0:x.slots]),F=C.useMemo(()=>al({slots:x==null?void 0:x.slots,cards:w,minInputs:v}),[x==null?void 0:x.slots,w,v]),S=C.useMemo(()=>{const f=N.findIndex(O=>(O==null?void 0:O.id)===o.id);return f<0?-1:he.getSlotIndexForCard(o,f)},[N,o]);function y(f){if(typeof f=="number")return`Tab ${f+1}`;const O=f.match(/^(\d+)-(\d+)$/);if(O){const[,R,B]=O;return`Tabs ${Number(R)+1}-${Number(B)+1}`}const D=f.match(/^(\d+)\+$/);return D?`Tabs ${Number(D[1])+1}+`:`Tab ${f}`}function k(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function E(f,O,D=[],R="",B,Y,_){const z=A({key:O,defaultValue:R,settingsValue:Y,sourceCard:_});return f==="input"?e.jsx(at,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:U=>{T({key:O,value:U,settingsField:B,settingsValue:Y,sourceCard:_})}},O):f==="select"?e.jsx(Ct,{className:"h-8 w-full",label:"",options:D,value:String(z!==void 0?z:R??""),onValueChange:U=>{T({key:O,value:U,settingsField:B,settingsValue:Y,sourceCard:_})}}):null}function A({key:f,defaultValue:O,settingsValue:D,sourceCard:R}){const B=D==null?void 0:D[f];return B!==void 0?B:f==="title"&&(R==null?void 0:R.title)!==void 0?R.title:f==="description"&&(R==null?void 0:R.description)!==void 0?R.description:O}function T({key:f,value:O,settingsField:D,settingsValue:R,sourceCard:B}){const Y={...R||{}},_=f==="title"&&(B==null?void 0:B.title)!==void 0,z=f==="description"&&(B==null?void 0:B.description)!==void 0;_&&O===String((B==null?void 0:B.title)??"")||z&&O===String((B==null?void 0:B.description)??"")?delete Y[f]:Y[f]=O,l({...s||{},[D]:Y})}function I({settingsSchema:f,settingsField:O,settingsValue:D,sourceCard:R,headerLabel:B}){const Y=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),Y.map(([_,z])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:z.title}),((U=z.docs)==null?void 0:U.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:z.docs.description})})]})})]}),E(z.ui,_,z.options,z.defaultValue,O,D,R)]},_)})]})}function L(){return e.jsxs(e.Fragment,{children:[p&&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:x!=null&&x.slots&&x.slots.length>0?e.jsx("div",{className:"space-y-3",children:x.slots.map((f,O)=>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:y(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:[k(f.expectedType)&&e.jsxs("span",{children:["Expected: ",k(f.expectedType)]}),f.required&&e.jsx("span",{children:"Required"})]})]},`${f.label}-${O}`))}):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."}),(v||M)&&e.jsxs("p",{children:[v?`Min ${v} tabs`:"",v&&M?" • ":"",M?`Max ${M} tabs`:""]})]})})]}),p&&F.length>0&&e.jsx(n.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(n.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:F.map((f,O)=>e.jsx("li",{children:f.message},`${f.type}-${O}`))})})}),x&&!p&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:I({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),x&&p&&(x.settings||x.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[h&&x.settings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:i||o,headerLabel:"Global Settings"})}),x.slotSettings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:x.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const f=o.tabTitle||o.title,O=S>=0?S:0,D=h?"Slot 0":`Slot ${O}`;return f?`${D}: ${f} Settings`:`${D} Settings`})()})})]})]})}return e.jsxs(n.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(n.AccordionItem,{value:"plugin-settings",children:[e.jsx(n.AccordionTrigger,{children:"Plugin"}),e.jsx(n.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:[(!p||h)&&e.jsx(Ct,{icon:e.jsx(ia,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(c==null?void 0:c.url)||"",onValueChange:f=>l({...s||{url:"",componentName:""},url:f})}),p&&!h&&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&&(!p||h)&&e.jsx(e.Fragment,{children:u&&e.jsx(Ct,{icon:e.jsx(gr,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.map(f=>({value:f.name,label:f.name})))||[],value:s.componentName||"",onValueChange:f=>{var R;const O=(R=m==null?void 0:m.visuals)==null?void 0:R.find(B=>B.name===f),D=u==null?void 0:u.find(B=>B.name===f);l({...s,componentName:f,visualType:(O==null?void 0:O.visualType)||(D==null?void 0:D.type)||"single",minInputs:O==null?void 0:O.minInputs,maxInputs:O==null?void 0:O.maxInputs,pluginChartType:O==null?void 0:O.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(n.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(x==null?void 0:x.name)||"Settings"}),(x==null?void 0:x.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.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(n.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:[x.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.docs.description}),x.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(n.Markdown,{remarkPlugins:[n.remarkGfm],components:rl,children:x.docs.dataSchema})})]}),(()=>{var O;const f=(O=x.docs)==null?void 0:O.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((D,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:D})]},R))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:L()})]})]})}function is(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Aa(s,a,r){if(!a||a==="auto")return{type:"auto"};if(a==="duration")return{type:"duration",multiplyBy:void 0,percentValueMode:void 0,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits};const o={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0&&!(a==="currency"&&(r!=null&&r.preserveSparseCurrency))?La(o,is(a)):o}function ol(s,a){return{...s,decimalPlaces:void 0,minimumFractionDigits:a,maximumFractionDigits:a}}function Kn(s){const a=s.decimalPlaces;return{...s,currency:void 0,decimalPlaces:void 0,minimumFractionDigits:s.minimumFractionDigits??a,maximumFractionDigits:s.maximumFractionDigits??a}}function ll(s,a){const r=s.type||"auto";return r==="auto"?s:r==="duration"?{type:"duration",prefix:s.prefix,suffix:s.suffix,negativeInParentheses:s.negativeInParentheses,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits}:Aa(s,r,a)}function La(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Ft="__report_default__",il=["auto","number","currency","percent","scientific","date","duration"],Un=[{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"}],Hn=[{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"}],Ns=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],cl=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],dl=s=>s.charAt(0).toUpperCase()+s.slice(1);function ul(s,a){try{return oa.resolveCurrencyFractionDigits(s,a).maximumFractionDigits??is("currency")}catch{return is("currency")}}function Xt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:o="NUMBER FORMAT",maxDecimalPlaces:d=10,reportDefaults:l,showAutoFormat:i=!0}){var I,L;const c=s.type||"auto",u=ll(s,{preserveSparseCurrency:!!l}),m=j=>{j.stopPropagation()},x=(j,P)=>{a({...u,[j]:P})},g=u.decimalPlaces??u.maximumFractionDigits??u.minimumFractionDigits,p=s.currency??(l==null?void 0:l.currency)??"USD",h=s.locale??(l==null?void 0:l.locale)??"en-US",v=c==="currency"?ul(h,p):void 0,M=g??v??is(c),N=c==="currency"&&u.decimalPlaces===void 0&&u.minimumFractionDigits===void 0&&u.maximumFractionDigits===void 0,[b,w]=C.useState(()=>String(M)),[F,S]=C.useState(()=>u.multiplyBy!==void 0?String(u.multiplyBy):""),y=j=>{const P=Aa(s,j,{preserveSparseCurrency:!!l});a(l&&j==="currency"&&s.type!=="currency"?Kn(P):P)},k=j=>l&&c==="currency"?ol(u,j):La(u,j),E=((I=Un.find(j=>j.value===(l==null?void 0:l.currency)))==null?void 0:I.label)??(l==null?void 0:l.currency),A=((L=Hn.find(j=>j.value===(l==null?void 0:l.locale)))==null?void 0:L.label)??(l==null?void 0:l.locale),T=c==="number"||c==="currency"||c==="percent"||c==="scientific";return C.useEffect(()=>{w(String(M))},[M]),C.useEffect(()=>{S(u.multiplyBy!==void 0?String(u.multiplyBy):"")},[u.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsxs(t.Select,{value:c,onValueChange:j=>y(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:il.filter(j=>i||j!=="auto").map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":dl(j)},j))})]})]}),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.jsxs("div",{className:"flex-1",children:[e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:d,placeholder:"0",value:b,onClick:m,onPointerDown:m,onKeyDown:m,onChange:j=>{const P=j.target.value.replace(/[^\d]/g,"");w(P),P!==""&&a(k(Math.max(0,Math.min(d,parseInt(P,10)))))},onBlur:()=>{if(b!=="")return;const j=M;w(String(j)),a(k(j))},className:"h-8 text-xs"}),N&&e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"Currency default"})]})]}),c==="currency"&&e.jsx("div",{className:"space-y-1",children: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||(l?Ft:"USD"),onValueChange:j=>{if(j===Ft){a(Kn(u));return}x("currency",j)},children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[l&&e.jsxs(t.SelectItem,{value:Ft,className:"text-xs",children:["Report default — ",E]}),Un.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:j=>j.stopPropagation(),onCheckedChange:j=>x("useSuffix",j)})]}),c!=="duration"&&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||(l&&T?Ft:"en-US"),onValueChange:j=>x("locale",j===Ft?void 0:j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[l&&T&&e.jsxs(t.SelectItem,{value:Ft,className:"text-xs",children:["Report default — ",A]}),Hn.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("prefix",j.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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("suffix",j.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:j=>j.stopPropagation(),onCheckedChange:j=>x("negativeInParentheses",j)})]}),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:F,onClick:m,onPointerDown:m,onKeyDown:m,onChange:j=>{const P=j.target.value.replace(/[^0-9.]/g,"");S(P),x("multiplyBy",P?parseFloat(P):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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("dateFormat",j.target.value),className:"h-8 text-xs"})})]}),c==="duration"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Value Is"}),e.jsxs(t.Select,{value:s.durationInputUnit||"second",onValueChange:j=>x("durationInputUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Display"}),e.jsxs(t.Select,{value:s.durationDisplayStyle||"compact",onValueChange:j=>x("durationDisplayStyle",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cl.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Smallest"}),e.jsxs(t.Select,{value:s.durationSmallestUnit||"second",onValueChange:j=>x("durationSmallestUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Largest"}),e.jsxs(t.Select,{value:s.durationLargestUnit||"day",onValueChange:j=>x("durationLargestUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]})]})]})]})}function Gn({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function o(i,c,u){const m=[...s];m[i]={...m[i],[c]:u},a(m)}function d(i){const c=[...s];c.splice(i,1),a(c)}function l(){a([...s,r])}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:l,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(n.Plus,{className:"size-3"})})]}),s.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:u=>o(c,"start",u.target.value),value:i.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:i.end,onChange:u=>o(c,"end",u.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:u=>o(c,"color",u.target.value),value:i.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:Ke.colors.green[600]}),e.jsx("option",{children:Ke.colors.red[500]}),e.jsx("option",{children:Ke.colors.yellow[400]}),e.jsx("option",{children:Ke.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>d(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(oe.X,{className:"size-3"})})]},c))]})}const ml=[];function xl(s){return(s==null?void 0:s.enabled)===!1||typeof(s==null?void 0:s.enabled)=="string"&&s.enabled.trim().toLowerCase()==="false"}function hl(s){var r;const a=t.fromPersistedKpiFormatOptions((r=s==null?void 0:s.kpiVisualOptions)==null?void 0:r.formatOptions)||(s!=null&&s.formatNumber?t.fromLegacyFormatNumber(s==null?void 0:s.formatNumber):void 0);return t.toTFormatOptions(a,{preserveOmittedProperties:!0})||{type:"number",minimumFractionDigits:0,maximumFractionDigits:0}}function Qn(s){return{enabled:!0,colorRanges:s==null?void 0:s.colorRanges}}function pl(){var p,h,v,M;const s=t.useEditorStore(N=>N.card),a=t.useEditorStore(N=>N.actions.setCardPreferences),r=t.useEditorStore(N=>{var b,w;return((w=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.colorRanges)??ml}),o=t.useEditorStore(N=>N.actions.setColorRanges),d=n.useResolvedValueFormatLocale()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale,l=n.useResolvedDefaultCurrency()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,i=!n.isSqlBackedKpi(s)&&Ke.hasValidCardConfig(s.config),c=hl(s.preferences),u=!!t.fromPersistedKpiFormatOptions((h=(p=s.preferences)==null?void 0:p.kpiVisualOptions)==null?void 0:h.formatOptions),m=!xl((v=s.preferences)==null?void 0:v.formatNumber)&&(u||!!((M=s.preferences)!=null&&M.formatNumber)),x=N=>{const b=t.useEditorStore.getState().card.preferences??{};a({...b,formatNumber:Qn(b.formatNumber),kpiVisualOptions:{...b.kpiVisualOptions,formatOptions:N}})},g=N=>{const b=t.useEditorStore.getState().card.preferences??{};if(N){a({...b,formatNumber:Qn(b.formatNumber),kpiVisualOptions:{...b.kpiVisualOptions,formatOptions:c}});return}a({...b,formatNumber:{...b.formatNumber,enabled:!1}})};return i?e.jsx(Gn,{colorRanges:r,setColorRanges:o}):e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"query-kpi-format-number",checked:m,onCheckedChange:N=>g(N===!0)}),e.jsx(t.Label,{htmlFor:"query-kpi-format-number",className:"text-xs",children:"Format number"})]}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Xt,{formatOptions:c,onFormatOptionsChange:x,showTitle:!1,showAutoFormat:!1,reportDefaults:{currency:l,locale:d}}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Gn,{colorRanges:r,setColorRanges:o})]})]})}const fl={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 Fa(s){return fl[s]}function gl({chartType:s,showDocsLink:a=!0}){const r=Fa(s);return r?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:r.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:r.fields.map((o,d)=>e.jsxs("tr",{className:d<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[o.name,o.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:o.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:o.description||"—"})]},o.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:r.description}),a&&r.docsUrl&&e.jsxs("a",{href:r.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:o=>o.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(n.ExternalLink,{className:"h-3 w-3"})]})]}):null}function bl({chartType:s}){return Fa(s)?e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.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(n.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(gl,{chartType:s})})]}):null}function Vs({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-medium",children:a}),e.jsx(bl,{chartType:s})]})}function jl(){const s=t.useEditorStore(d=>!Ke.hasValidCardConfig(d.card.config)),a=t.useEditorStore(d=>{var l,i;return((i=(l=d.card.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:i.queryComparisonPolarity)??Mn.DEFAULT_METRIC_COMPARISON_POLARITY}),r=t.useEditorStore(d=>d.actions.setCardPreferences),o=d=>{const l=t.useEditorStore.getState().card.preferences??{},i={...l.kpiVisualOptions,queryComparisonPolarity:d===Mn.DEFAULT_METRIC_COMPARISON_POLARITY?void 0:d};r({...l,kpiVisualOptions:i})};return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Vs,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(pl,{})}),s&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx(t.Label,{htmlFor:"query-kpi-favorable-direction",className:"text-xs",children:"Favorable direction"}),e.jsxs(t.Select,{value:a,onValueChange:d=>o(d),children:[e.jsx(t.SelectTrigger,{id:"query-kpi-favorable-direction",className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Applies when the query returns current and comparison values."})]})]})}function Wn({children:s,summary:a,open:r,className:o}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",o),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 vl(){const[s,a]=C.useState([]),r=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:d}=t.useEditorStore(m=>m.actions),l=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var x;return(x=m.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),C.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function i(m,x){var g,p;x?r!=null&&r.onClickFilter&&((g=r==null?void 0:r.onClickFilter)==null?void 0:g.length)>0?d({...r,onClickFilter:[...r.onClickFilter,{columnIndex:m,expression:""}]}):d({...r,onClickFilter:[{columnIndex:m,expression:""}]}):(d({...r,onClickFilter:(p=r==null?void 0:r.onClickFilter)==null?void 0:p.filter(h=>h.columnIndex!==m)}),a(h=>{const v=[...h];return v[m]=!1,v}))}function c(m,x){var p;const g=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.map(h=>h.columnIndex===m?{...h,expression:x.target.value}:h);d({...r,onClickFilter:g})}function u(m){var x,g,p,h;if(s!=null&&s[m]||(g=(x=r==null?void 0:r.onClickFilter)==null?void 0:x.find(v=>v.columnIndex===m))!=null&&g.expression)return e.jsx(t.Input,{value:(h=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(v=>v.columnIndex===m))==null?void 0:h.expression,onChange:v=>c(m,v),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:l==null?void 0:l.map((m,x)=>{var g,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(n.Checkbox,{checked:!!((g=r==null?void 0:r.onClickFilter)!=null&&g.find(h=>h.columnIndex===x)),onCheckedChange:h=>i(x,h)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(h=>h.columnIndex===x))&&e.jsx(n.Pencil,{onClick:()=>{a(h=>{const v=[...h];return v[x]=!h[x],v})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(x)]})},m)})})}const yl=[{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"}],Cl=["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"],Nl=Cl.map(s=>({label:s,value:s}));function Sl(){var u,m,x,g,p,h,v,M,N,b,w,F,S,y,k,E,A,T;const s=t.useEditorStore(I=>I.card),a=(m=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:m.topoJsonUrl,[r,o]=C.useState(((g=(x=s==null?void 0:s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:l}=n.useTopoJson(s),i=Object.keys((l==null?void 0:l.objects)||{}).map(I=>({label:I,value:I}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Vs,{chartType:"map"}),e.jsx(Wn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ct,{className:"h-9",options:c,onValueChange:I=>{console.log("value",I),d({...s.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:I=>{o(I.target.value)},onBlur:()=>{var I;console.log("onBlur",r),d({...s.preferences,mapVisualOptions:{...(I=s.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:r}})},value:r,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(Ct,{className:"h-9",options:i,value:((h=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:h.objectKey)||"",label:"Map Object",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(Ct,{className:"h-9",options:yl,value:((M=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:M.projection)||"",label:"Projection",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(Ct,{className:"h-9",options:Nl,value:((b=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:b.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Wn,{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:((F=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:F.projectionScale)||1,onChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((k=(y=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:k[0])||0,onChange:I=>{var L,j,P,V;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[Number(I.target.value),((V=(P=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:P.projectionOffset)==null?void 0:V[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((T=(A=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[1])||0,onChange:I=>{var L,j,P,V;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[((V=(P=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:P.projectionOffset)==null?void 0:V[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(vl,{})]})}const wl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function Tl(s){return s&&(wl[s]??s)}function Ra({value:s,onChange:a,showPosition:r=!1}){const o=s.colors||{};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Select,{value:s.displayMode||"difference",onValueChange:d=>a({displayMode:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"difference",children:"Difference"}),e.jsx(t.SelectItem,{value:"percent_change",children:"Percent change"}),e.jsx(t.SelectItem,{value:"both",children:"Both"}),e.jsx(t.SelectItem,{value:"ratio",children:"Ratio (current ÷ comparison)"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"comparison-precision",className:"text-xs",children:"Percent/ratio precision"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"0 through 6 decimals"})]}),e.jsx(t.Input,{id:"comparison-precision",type:"number",min:0,max:6,step:1,value:s.precision??"",placeholder:"Default",onChange:d=>{if(d.target.value===""){a({precision:void 0});return}const l=Number(d.target.value);Number.isInteger(l)&&l>=0&&l<=6&&a({precision:l})},className:"h-7 w-16 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Indicator"}),e.jsxs(t.Select,{value:s.indicatorStyle||"arrow_badge",onValueChange:d=>a({indicatorStyle:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"arrow_badge",children:"Arrow + badge"}),e.jsx(t.SelectItem,{value:"arrow",children:"Arrow"}),e.jsx(t.SelectItem,{value:"badge",children:"Badge"}),e.jsx(t.SelectItem,{value:"none",children:"None"})]})]})]}),r&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Position"}),e.jsxs(t.Select,{value:s.position||"right",onValueChange:d=>a({position:d}),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:"right",children:"Right"}),e.jsx(t.SelectItem,{value:"left",children:"Left"}),e.jsx(t.SelectItem,{value:"top",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-color",className:"text-xs",children:"Use sentiment color"}),e.jsx(t.Switch,{id:"comparison-color",size:"xs",checked:s.showColor!==!1,onCheckedChange:d=>a({showColor:d})})]}),s.showColor!==!1&&e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase","#16a34a"],["decrease","Decrease","#dc2626"],["neutral","No change","#6b7280"]].map(([d,l,i])=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:l}),e.jsx(n.ColorField,{value:Tl(o[d]||i),onChange:c=>a({colors:{...o,[d]:c||i}}),defaultValue:i,ariaLabel:`${l} color`,allowEmpty:!1})]},d))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-conditional-label",className:"text-xs",children:"Different label per direction"}),e.jsx(t.Switch,{id:"comparison-conditional-label",size:"xs",checked:s.conditionalLabel===!0,onCheckedChange:d=>a({conditionalLabel:d})})]}),s.conditionalLabel?e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase"],["decrease","Decrease"],["neutral","No change"]].map(([d,l])=>{var i;return e.jsx(t.Input,{"aria-label":`${l} label`,value:((i=s.conditionalLabels)==null?void 0:i[d])||l,onChange:c=>a({conditionalLabels:{...s.conditionalLabels,[d]:c.target.value}}),className:"h-7 text-xs"},d)})}):e.jsx(t.Input,{"aria-label":"Comparison label",value:s.labelName||"",onChange:d=>a({labelName:d.target.value}),placeholder:"Previous",className:"h-7 text-xs"})]})}function El(){var g,p,h,v,M;const s=t.useEditorStore(N=>N.card),{setCardPreferences:a}=t.useEditorActions(),r=n.useEffectiveEditorCardType(),o=((g=s.config)==null?void 0:g.metricColumns)||[],d=o.length===2&&(((p=s.config)==null?void 0:p.groupByColumns)||[]).length===0,l=o.some(N=>{var b;return((b=N.comparison)==null?void 0:b.mode)==="explicit"});if(!t.COMPARISON_PRESENTATION_SUPPORTED_CHART_TYPES.includes(r))return null;const c=((h=s.preferences)==null?void 0:h.comparisonPresentation)||{},u=N=>a({...s.preferences,comparisonPresentation:{...c,...N}}),m=r==="kpi"&&((v=s.preferences)==null?void 0:v.metricPairComparisonEnabled)===!0,x=l||m;return e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"inherit-global-date-comparison",className:"text-xs",children:"Inherit Global Date comparison"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Author-set metric comparisons still take precedence."})]}),e.jsx(t.Switch,{id:"inherit-global-date-comparison",size:"xs",checked:((M=s.preferences)==null?void 0:M.inheritGlobalComparison)!==!1,onCheckedChange:N=>{const b={...s.preferences};N?delete b.inheritGlobalComparison:b.inheritGlobalComparison=!1,a(b)}})]}),r==="kpi"&&d&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-metric-pair-comparison",className:"text-xs",children:"Enable metric comparison"}),e.jsx(t.Switch,{id:"enable-metric-pair-comparison",size:"xs",checked:m,onCheckedChange:N=>a({...s.preferences,metricPairComparisonEnabled:N})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"show-explicit-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-explicit-comparison",size:"xs",checked:c.showComparison!==!1,onCheckedChange:N=>u({showComparison:N})})]}),x&&e.jsx(Ra,{value:c,onChange:u,showPosition:r==="kpi"&&d})]})]})}function Pa({cardType:s,queryResultColumns:a,focusSection:r,focusRequestId:o}){var z,U,G;const d=t.useEditorStore(q=>q.card),l=t.useEditorStore(q=>q.queryResultColumns),i=t.useEditorStore(q=>{var Q;return(Q=q.card)==null?void 0:Q.preferences}),c=i==null?void 0:i.tablePrefs,u=t.useEditorStore(q=>q.actions.setCardPreferences),m=t.useEditorStore(q=>q.actions.updateTableConditionalFormatting),x=((z=d.config)==null?void 0:z.metricColumns)||[],g=s??d.type,p=a??l,h=d.type===g?d:{...d,type:g},v=n.getTableConditionalFormattingColumnOptions(h,p),M=n.getTableOutputColumnOptions(h,p),N=n.supportsTableConditionalFormatting(g),b=g==="table",w=g==="table",F=((U=v[0])==null?void 0:U.value)||"",S=n.normalizeConditionalFormatting((G=i==null?void 0:i.tablePrefs)==null?void 0:G.conditionalFormatting),y=n.resolveTablePresentationStyle(c),k=n.isEligibleFlatTableTotalsCard(h),E=n.hasFlatTableTotalsBehavior(h),[A,T]=C.useState("style");C.useEffect(()=>{if(r==="style"){T("style");return}if(r==="columns"&&w){T("columns");return}r==="conditional-formatting"&&N&&T("conditional-formatting")},[w,N,o,r]);const I=x.some(q=>{var Q;return((Q=q.comparison)==null?void 0:Q.mode)==="explicit"}),L=(i==null?void 0:i.comparisonPresentation)||{},j=q=>{u({...i,comparisonPresentation:{...L,...q}})},P=q=>{m({version:1,rules:q})},V=q=>{u({...i,tablePrefs:{...c,density:q}})},f=q=>{u({...i,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,...q}}})},O=q=>{var Q;f({totals:{...(Q=c==null?void 0:c.tableStyle)==null?void 0:Q.totals,...q}})},D=q=>{var Q;u({...i,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,totals:{...(Q=c==null?void 0:c.tableStyle)==null?void 0:Q.totals,enabled:q}}}})},R=(q,Q)=>{u({...i,tablePrefs:{...c,columnVisibility:n.setTableColumnVisibility(c==null?void 0:c.columnVisibility,q,Q)}})},B=()=>{u({...i,tablePrefs:{...c,columnVisibility:n.showAllTableColumns()}})},Y=()=>{u({...i,tablePrefs:{...c,density:n.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:n.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:k?E:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},_=I?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Comparison"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(t.Label,{htmlFor:"show-table-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-table-comparison",size:"xs",checked:L.showComparison!==!1,onCheckedChange:q=>j({showComparison:q})})]}),e.jsx(Ra,{value:L,onChange:j})]}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:A,onValueChange:q=>T(q),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),w?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!N,children:"Conditional formatting"})]}),e.jsx(t.TabsContent,{value:"style",className:"mt-0",children:e.jsx(n.TablePresentationSettings,{style:y,onDensityChange:V,onStyleChange:f,showFullStyle:b,showBorderStyle:!1,totals:b&&k?{enabled:E,onEnabledChange:D,onStyleChange:O}:void 0,extraSection:_,onReset:b?Y:void 0})}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:w?e.jsx(n.TableColumnVisibilitySettings,{columns:M,columnVisibility:c==null?void 0:c.columnVisibility,onColumnVisibilityChange:R,onShowAllColumns:B}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Column visibility is available for table cards."})}),e.jsx(t.TabsContent,{value:"conditional-formatting",className:"mt-0",children:N?F?e.jsx(n.DataTableConditionalFormattingSettings,{columnId:F,availableColumns:v,conditionalRules:S.rules,onConditionalRulesChange:P,startRulesWithNoTrigger:!0}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Run the query to configure conditional formatting."}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Conditional formatting is available for table cards."})})]})})}function Il(){var d;const s=t.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=t.useEditorStore(l=>l.actions),r=(d=s==null?void 0:s.textVisualOptions)!=null&&d.isDynamicText?"dynamic":"static";function o(l){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsx(t.Tabs,{value:r,onValueChange:o,children:e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"static",children:"Static"}),e.jsx(t.TabsTrigger,{value:"dynamic",children:"Dynamic"})]})})}function Dl(){return e.jsxs("div",{className:"space-y-2 px-6 py-4",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Text mode"}),e.jsx(Il,{}),e.jsx("p",{className:"pt-1 text-[12px] leading-[1.55] text-muted-foreground",children:"Static text is authored inline. Dynamic text reads from the first cell of the card's query."})]})}function kl({color:s,onColorChange:a,onClose:r}){const[o,d]=C.useState(0),[l,i]=C.useState(100),[c,u]=C.useState(50),[m,x]=C.useState(s);C.useEffect(()=>{const N=Jn(s);if(N){const b=Xn(N.r,N.g,N.b);d(b.h),i(b.s),u(b.l),x(s)}},[s]);const g=N=>{d(N),h(N,l,c)},p=N=>{const b=N.currentTarget.getBoundingClientRect(),w=Math.max(0,Math.min(1,(N.clientX-b.left)/b.width)),F=Math.max(0,Math.min(1,(N.clientY-b.top)/b.height)),S=w*100,y=(1-F)*100;i(S),u(y),h(o,S,y)},h=(N,b,w)=>{const F=Al(N,b,w),S=Ml(F.r,F.g,F.b);x(S)},v=N=>{if(x(N),/^#[0-9A-Fa-f]{6}$/.test(N)){const b=Jn(N);if(b){const w=Xn(b.r,b.g,b.b);d(w.h),i(w.s),u(w.l)}}},M=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(a(m),r())};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(${o}, 100%, 50%)`},onClick:p,onMouseMove:N=>{N.buttons===1&&p(N)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${l}%`,top:`${100-c}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:N=>g(Number(N.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:m,onChange:N=>v(N.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:m}}),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:r,children:"Cancel"}),e.jsx(t.Button,{onClick:M,children:"OK"})]})]})}function Jn(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 Ml(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function Xn(s,a,r){s/=255,a/=255,r/=255;const o=Math.max(s,a,r),d=Math.min(s,a,r);let l=0,i=0;const c=(o+d)/2;if(o!==d){const u=o-d;switch(i=c>.5?u/(2-o-d):u/(o+d),o){case s:l=((a-r)/u+(a<r?6:0))/6;break;case a:l=((r-s)/u+2)/6;break;case r:l=((s-a)/u+4)/6;break}}return{h:Math.round(l*360),s:Math.round(i*100),l:Math.round(c*100)}}function Al(s,a,r){s/=360,a/=100,r/=100;let o,d,l;if(a===0)o=d=l=r;else{const i=(m,x,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(x-m)*6*g:g<.5?x:g<.6666666666666666?m+(x-m)*(.6666666666666666-g)*6:m),c=r<.5?r*(1+a):r+a-r*a,u=2*r-c;o=i(u,c,s+1/3),d=i(u,c,s),l=i(u,c,s-1/3)}return{r:Math.round(o*255),g:Math.round(d*255),b:Math.round(l*255)}}const Ll=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Fl(){var y,k,E,A,T,I,L,j,P,V;const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var O;return(O=f.card)==null?void 0:O.preferences}),r=n.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions(),l=C.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:i}=n.useEditorCardQuery(l),[c,u]=C.useState({}),[m,x]=C.useState(null),[g,p]=C.useState(null),h=C.useMemo(()=>{var R,B,Y,_,z,U,G;if(!(i!=null&&i.records)||i.records.length===0)return[];const f=r==="stackedBar"||r==="stackedLine",O=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",D=((R=s==null?void 0:s.config)==null?void 0:R.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||O)&&D){if(i.pivotSchema&&Array.isArray(i.pivotSchema)){const q=new Set;return i.pivotSchema.forEach(Q=>{Q.alias&&q.add(Q.alias)}),Array.from(q)}if(i.records.length>0){const q=i.records[0],Q=Object.keys(q),H=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(ge=>{H.add(ge.label||ge.name),H.add(ge.alias||ge.name)});const se=new Set;return(Y=s==null?void 0:s.config)!=null&&Y.metricColumns&&s.config.metricColumns.forEach(ge=>{const fe=ge.alias||ge.name;se.add(fe),se.add(`${fe}_count`),se.add(`${fe}_sum`),se.add(`${fe}_avg`),se.add(`${fe}_min`),se.add(`${fe}_max`);const Te=ge.entityName||ge.qualifiedEntityName;Te&&(se.add(`${Te}_${fe}`),se.add(`${Te}_${fe}_count`))}),Q.filter(ge=>!H.has(ge)&&!se.has(ge))}}if((O||f)&&!D&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(q=>q.alias||q.label||q.name);if((G=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&G.length){const q=s.config.groupByColumns[0],Q=q.label||q.name,H=new Set;return i.records.forEach(se=>{const ce=se[Q];ce!=null&&H.add(String(ce))}),Array.from(H)}return[]},[i,(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns,(k=s==null?void 0:s.config)==null?void 0:k.pivotByColumns,(E=s==null?void 0:s.config)==null?void 0:E.metricColumns,r]),v=C.useMemo(()=>n.getDefaultChartColors(),[]);C.useEffect(()=>{const f={};h.forEach((O,D)=>{f[O]=n.getColorForValue(O,D,a==null?void 0:a.colorConfig)}),u(f)},[h,a==null?void 0:a.colorConfig,v]);const M=(f,O)=>{const D={...c,[f]:O};u(D);const R={...a||{},colorConfig:{segments:D}};o(R);const B={...s,preferences:R};d(B)},N=(f,O)=>{var z;const D=v[O%v.length],{[f]:R,...B}=((z=a==null?void 0:a.colorConfig)==null?void 0:z.segments)||{},Y={...a||{},colorConfig:{segments:B}};o(Y);const _={...s,preferences:Y};d(_),u(U=>({...U,[f]:D}))};if(!h.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((T=(A=s==null?void 0:s.config)==null?void 0:A.groupByColumns)==null?void 0:T.length)||((L=(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns)==null?void 0:L.length):(P=(j=s==null?void 0:s.config)==null?void 0:j.groupByColumns)==null?void 0:P.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const F=()=>{const f={...a||{},colorConfig:{segments:{}}};o(f);const O={...s,preferences:f};d(O);const D={};h.forEach((R,B)=>{D[R]=n.getColorForValue(R,B,void 0)}),u(D)},S=Object.keys(((V=a==null?void 0:a.colorConfig)==null?void 0:V.segments)||{}).length>0;return e.jsxs(n.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(n.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:F,children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((f,O)=>{const D=n.isDefaultColor(c[f],O),R=!D;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===f,onOpenChange:B=>x(B?f:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:c[f]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:v.slice(0,10).map((B,Y)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[f]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{M(f,B),x(null)},children:[Y===O%v.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:B})]},`default-${Y}`))})]}),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((B,Y)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[f]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{M(f,B),x(null)},children:e.jsx("span",{className:"sr-only",children:B})},`preset-${Y}`))})]}),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:()=>{p({value:f,color:c[f]}),x(null)},children:"Custom color"}),!D&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{N(f,O),x(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},f)})}),g&&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:()=>p(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(kl,{color:g.color,onColorChange:f=>{M(g.value,f),p(null)},onClose:()=>p(null)})})]})]})})]})}function ct({value:s,onSave:a,placeholder:r="",type:o="text",className:d=""}){const[l,i]=C.useState(s??""),[c,u]=C.useState(!1);C.useEffect(()=>{i(s??"")},[s]);const m=()=>{a(l),u(!1)},x=()=>{i(s??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:c?l:s??"",onChange:g=>{i(g.target.value),u(!0)},onFocus:()=>u(!0),onClick:g=>g.stopPropagation(),className:"h-8 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&c&&l!==s?m():g.key==="Escape"&&x()},"aria-label":r||"Edit field"}),c&&l!==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:m,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:x,children:e.jsx(oe.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Ss({axis:s,label:a,type:r,config:o,onChange:d,defaultTitle:l,hidePosition:i}){var v,M,N,b,w,F,S,y,k,E,A,T,I,L;const c=n.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),u=(j,P)=>{d({...o??{},[j]:P})},m=(j,P)=>{var D,R,B,Y;const V=j==="enabled"&&P===!0,f=(D=o==null?void 0:o.name)==null?void 0:D.text,O=V&&!f&&l;d({...o??{},name:{...o==null?void 0:o.name,enabled:j==="enabled"?P:((R=o==null?void 0:o.name)==null?void 0:R.enabled)??!1,text:j==="text"?P:O?l:f,fontSize:j==="fontSize"?P:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:j==="fontWeight"?P:(Y=o==null?void 0:o.name)==null?void 0:Y.fontWeight}})},x=(j,P)=>{var V,f;d({...o??{},labels:{enabled:j==="enabled"?P:((V=o==null?void 0:o.labels)==null?void 0:V.enabled)??!0,rotation:j==="rotation"?P:(f=o==null?void 0:o.labels)==null?void 0:f.rotation}})},g=(j,P)=>{d({...o??{},scale:{...o==null?void 0:o.scale,[j]:P===""?"auto":Number(P)}})},p=s==="x"?["auto","top","bottom"]:["auto","left","right"],h=["auto","0","45","90","-45","-90"];return e.jsxs(n.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(n.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-[12px] 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:(o==null?void 0:o.enabled)!==!1,onCheckedChange:j=>u("enabled",j),onClick:j=>j.stopPropagation()})]}),e.jsxs(n.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(n.Checkbox,{id:`${s}-title-enabled`,checked:((v=o==null?void 0:o.name)==null?void 0:v.enabled)??!1,onCheckedChange:j=>m("enabled",j===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((M=o==null?void 0:o.name)==null?void 0:M.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(ct,{placeholder:`${a} title`,value:((N=o==null?void 0:o.name)==null?void 0:N.text)||"",onSave:j=>m("text",j),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(ct,{type:"number",placeholder:"12",value:String(((b=o==null?void 0:o.name)==null?void 0:b.fontSize)||12),onSave:j=>m("fontSize",Number(j)||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:((w=o==null?void 0:o.name)==null?void 0:w.fontWeight)||"normal",onValueChange:j=>m("fontWeight",j),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"})]})]})]})]})]})]}),!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(o==null?void 0:o.position)||"auto",onValueChange:j=>u("position",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":t.titleCase(j)},j))})]})]}),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:((F=o==null?void 0:o.labels)==null?void 0:F.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((S=o==null?void 0:o.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(((y=o==null?void 0:o.labels)==null?void 0:y.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),r==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:c==="override",onCheckedChange:j=>d({...o,formatMode:j?"override":"inherit"})})]}),c==="override"&&e.jsx(Xt,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:j=>d({...o,formatMode:"override",formatOptions:j}),showTitle:!1})]}),r==="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(ct,{type:"number",placeholder:"auto",value:((k=o==null?void 0:o.scale)==null?void 0:k.min)==="auto"||((E=o==null?void 0:o.scale)==null?void 0:E.min)===void 0?"":String(o.scale.min),onSave:j=>g("min",j),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(ct,{type:"number",placeholder:"auto",value:((A=o==null?void 0:o.scale)==null?void 0:A.max)==="auto"||((T=o==null?void 0:o.scale)==null?void 0:T.max)===void 0?"":String(o.scale.max),onSave:j=>g("max",j),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(ct,{type:"number",placeholder:"auto",value:((I=o==null?void 0:o.scale)==null?void 0:I.stepSize)==="auto"||((L=o==null?void 0:o.scale)==null?void 0:L.stepSize)===void 0?"":String(o.scale.stepSize),onSave:j=>g("stepSize",j),className:""})})]})]})]})]})]})}function ws(s,a,r){var l,i,c;if(s==="x"){const u=(i=(l=a==null?void 0:a.config)==null?void 0:l.groupByColumns)==null?void 0:i[0];return(u==null?void 0:u.label)||(u==null?void 0:u.name)||""}const o=((c=a==null?void 0:a.config)==null?void 0:c.metricColumns)||[],d=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const u=o.filter((m,x)=>{const g=d.find(p=>p.idx===x);return!g||g.yAxisId!=="y2"});return u.length===1&&(u[0].label||u[0].name)||""}if(s==="y2"){const u=o.filter((m,x)=>{const g=d.find(p=>p.idx===x);return(g==null?void 0:g.yAxisId)==="y2"});return u.length===1&&(u[0].label||u[0].name)||""}return""}function Rl(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),d=n.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const l=n.AxisConfigurator.getAxisInfo(d,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const i=(u,m)=>{let x;u==="x"?x="xAxisConfig":u==="y"?x="yAxisConfig":x="secondaryYAxisConfig";const g={...a||{},[x]:m};r(g);const p={...s,preferences:g};o(p)},c=l.hasY2Axis&&d==="combo";return e.jsxs(n.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] 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(n.AccordionContent,{className:"pt-2",children:e.jsxs(n.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Ss,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"x"),a==null?void 0:a.xAxisConfig),onChange:u=>i("x",u),defaultTitle:ws("x",s,a)}),l.hasYAxis&&e.jsx(Ss,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:l.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"y"),a==null?void 0:a.yAxisConfig),onChange:u=>i("y",u),defaultTitle:ws("y",s,a)}),c&&e.jsx(Ss,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:u=>i("y2",u),defaultTitle:ws("y2",s,a),hidePosition:!0})]})})]})}function Pl(){const s=t.useEditorStore(g=>g.card),a=n.useEffectiveEditorCardType(),r=t.useEditorStore(g=>{var p,h,v,M;return(M=(v=(h=(p=g.card)==null?void 0:p.preferences)==null?void 0:h.chartOptions)==null?void 0:v.plugins)==null?void 0:M.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const d=n.getDefaultLegendConfig(a),l=(d==null?void 0:d.display)??!0,i=(d==null?void 0:d.position)??"top",c=(d==null?void 0:d.align)??"center",u=(g,p)=>{const h={...r,[g]:p};o(h)},m=["top","bottom","left","right"],x=["start","center","end"];return e.jsxs(n.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(n.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:(r==null?void 0:r.display)??l,onCheckedChange:g=>u("display",g)})]}),((r==null?void 0:r.display)??l)&&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:(r==null?void 0:r.position)||i,onValueChange:g=>u("position",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(r==null?void 0:r.align)||c,onValueChange:g=>u("align",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]})]})]})})]})}function Ol(){var P,V,f,O,D,R,B;const s=t.useEditorStore(Y=>Y.card),a=n.useEffectiveEditorCardType(),r=t.useEditorStore(Y=>{var _,z;return(z=(_=Y.card)==null?void 0:_.preferences)==null?void 0:z.dataLabelsConfig}),o=t.useEditorStore(Y=>{var _;return(_=Y.card)==null?void 0:_.preferences}),{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const i=a==="bullet"?((P=o==null?void 0:o.bulletConfig)==null?void 0:P.orientation)??(((V=o==null?void 0:o.chartOptions)==null?void 0:V.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=i!=null?i==="horizontal":((f=o==null?void 0:o.chartOptions)==null?void 0:f.indexAxis)==="y",u=a==="stackedBar"||a==="stackedLine",m=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",x=a==="bubble"||a==="scatter",g=(D=(O=o==null?void 0:o.chartOptions)==null?void 0:O.plugins)==null?void 0:D.datalabels,p=(g==null?void 0:g.display)!==!1&&((g==null?void 0:g.anchor)||(g==null?void 0:g.align)),h=n.getDefaultDataLabelsConfig(a,s.preferences),v=r??h,M=(h==null?void 0:h.enabled)??p??!1,N=(r==null?void 0:r.enabled)!==void 0?r.enabled:M,b=(Y,_)=>{const G={...h??{},...r??{},[Y]:_};Y==="enabled"&&(G.display=_,_&&x&&!G.position&&(G.position="bottom")),Y==="position"&&x&&(G.position="bottom"),Y==="formatMode"&&_==="inherit"&&(G.format=void 0,G.formatOptions=void 0);const q={...s.preferences||{},dataLabelsConfig:G};d(q);const Q={...s,preferences:q};l(Q)},w=(Y,_)=>{const z=r??{},G={...h??{},...z,font:{...z.font||{},[Y]:_}},q={...s.preferences||{},dataLabelsConfig:G};d(q);const Q={...s,preferences:q};l(Q)},F=()=>{const Y=a;return Y==="stackedBar"||Y==="stackedLine"||Y==="pie"||Y==="doughnut"?"center":c?"right":"top"},S=a!=="treemap"&&a!=="heatmap",y=a!=="treemap",k=F();let E=[];if(S)if(x)E=["bottom"];else if(u||m)E=["center"];else{const Y=c?["center","left","right"]:["center","top","bottom"];E=["auto",...a==="bullet"?Y:Y.filter(z=>z!==k),"custom"]}const A=()=>t.titleCase(k),T=["center","start","end"],I=["center","start","end","top","bottom"],L=(v==null?void 0:v.formatMode)||(v!=null&&v.format&&!["auto"].includes(v.format)?"override":"inherit"),j=(v==null?void 0:v.format)==="none";return e.jsxs(n.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(n.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,onCheckedChange:Y=>b("enabled",Y)})]}),N&&e.jsxs(e.Fragment,{children:[S&&!u&&!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:x?(v==null?void 0:v.position)||"bottom":(v==null?void 0:v.position)||"auto",onValueChange:Y=>b("position",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:Y==="auto"?A():Y==="custom"?"Custom (Advanced)":t.titleCase(Y)},Y))})]})]}),u&&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:(r==null?void 0:r.showTotal)??!1,onCheckedChange:Y=>b("showTotal",Y)})]}),(v==null?void 0:v.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:(v==null?void 0:v.anchor)||"center",onValueChange:Y=>b("anchor",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:t.titleCase(Y)},Y))})]})]}),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((v==null?void 0:v.align)||"center"),onValueChange:Y=>b("align",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:I.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:t.titleCase(Y)},Y))})]})]})]}),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:L==="override",onCheckedChange:Y=>b("formatMode",Y?"override":"inherit")})]}),L==="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:j,onCheckedChange:Y=>{const _=r??{},U={...h??{},..._,formatMode:"override",format:Y?"none":void 0,formatOptions:Y?void 0:_.formatOptions},G={...s.preferences||{},dataLabelsConfig:U};d(G),l({...s,preferences:G})}})]}),!j&&e.jsx(Xt,{formatOptions:(v==null?void 0:v.formatOptions)||{},onFormatOptionsChange:Y=>{const U={...h??{},...r??{},formatMode:"override",format:Y.type&&Y.type!=="auto"?Y.type:void 0,formatOptions:Y},G={...s.preferences||{},dataLabelsConfig:U};d(G),l({...s,preferences:G})},showTitle:!1})]})]}),y&&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(ct,{type:"number",placeholder:"12",value:String(((R=v==null?void 0:v.font)==null?void 0:R.size)||12),onSave:Y=>w("size",Number(Y)),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:((B=v==null?void 0:v.font)==null?void 0:B.weight)||"normal",onValueChange:Y=>w("weight",Y),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:(v==null?void 0:v.color)==="auto"||!(v!=null&&v.color)?"auto":"custom",onValueChange:Y=>{Y==="auto"&&b("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(ct,{type:"number",placeholder:"0",value:String((v==null?void 0:v.rotation)||0),onSave:Y=>b("rotation",Number(Y)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Bl(){var l;const s=t.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=t.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((l=a==null?void 0:a.chartOptions)==null?void 0:l.treemapColorMode)??"branch",d=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};r(c)};return e.jsxs(n.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(n.RadioGroup,{value:o,onValueChange:i=>d(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.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(n.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 Vl=Object.keys(n.HEATMAP_PRESET_PALETTES);function _l(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",d=(a==null?void 0:a.heatmapConfig)||{},l=d.colorPalette??"green",i=d.legendPosition??"bottom",c=C.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),u=p=>{const h={...d,...p};h.colorPalette!=="custom"?delete h.colorRange:(!h.colorRange||!h.colorRange[0]||!h.colorRange[1])&&(h.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:h})},m=p=>{u({colorPalette:p,colorRange:p==="custom"?d.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,h)=>{const v=[...c];v[p]=h,u({colorPalette:"custom",colorRange:v})},g=p=>{u({legendPosition:p})};return o?e.jsxs(n.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(n.RadioGroup,{value:l,onValueChange:p=>m(p??"blue"),className:"space-y-3",children:[Vl.map(p=>{const h=n.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(t.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${h.start}, ${h.end})`}})]})]},p)}),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(n.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),l==="custom"&&e.jsxs("div",{className:"flex flex-col gap-2 pl-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[0],onChange:p=>x(0,p??"#000000"),ariaLabel:"Start color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Start color"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[1],onChange:p=>x(1,p??"#000000"),ariaLabel:"End color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"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:i,onValueChange:p=>g(p??"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(p=>e.jsx(t.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}const Zn=["poor","satisfactory","good"];function ea(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 Yl(){var P,V;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.card),r=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:o,setChartOrientation:d}=t.useEditorActions(),l=C.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=Ke.hasValidCardConfig(a==null?void 0:a.config)&&!r,[u,m]=C.useState(l.showRanges??!1),[x,g]=C.useState(l.rangesArePercentages??!1),p=l.disableAutoComparative?!1:l.comparativeMetricKey!==void 0||!c,[h,v]=C.useState(p);C.useEffect(()=>{m(l.showRanges??!1)},[l.showRanges]),C.useEffect(()=>{g(l.rangesArePercentages??!1)},[l.rangesArePercentages]);const M=l.targetValue===void 0?"":String(l.targetValue);C.useEffect(()=>{const f=l.disableAutoComparative?!1:l.comparativeMetricKey!==void 0||!c;v(f)},[l.disableAutoComparative,l.comparativeMetricKey,c]);const N=C.useMemo(()=>{var f,O;return((O=(f=a==null?void 0:a.config)==null?void 0:f.metricColumns)==null?void 0:O.map(D=>{const R=D.label||D.name||D.alias||"";return{value:R,label:R}}))||[]},[(P=a==null?void 0:a.config)==null?void 0:P.metricColumns]);C.useEffect(()=>{var z,U;if(!s||N.length===0)return;const f={};let O=!1;const D=(z=N[1])==null?void 0:z.value;!l.targetMetricKey&&D&&(f.targetMetricKey=D,O=!0);const R=(U=N[2])==null?void 0:U.value;!l.comparativeMetricKey&&!l.disableAutoComparative&&R&&(f.comparativeMetricKey=R,O=!0);const B=N.slice(3),Y={...l.rangeKeys||{}};let _=!1;if(Zn.forEach((G,q)=>{!Y[G]&&B[q]&&(Y[G]=B[q].value,_=!0)}),_&&(f.rangeKeys=Y,O=!0,l.showRanges===void 0&&(f.showRanges=!0)),O){const G=ea({...l,...f});o({...s,bulletConfig:G})}},[N,l,s,o]);const b=f=>{const O=ea({...l,...f});o({...s,bulletConfig:O})},w=(f,O)=>{const D={...l.rangeKeys||{},[f]:O.trim()};O.trim()||delete D[f],b({rangeKeys:Object.keys(D).length>0?D:void 0})},F=(f,O)=>{const D=O===""?void 0:Number(O),R={...l.ranges||{}};D===void 0||Number.isNaN(D)?delete R[f]:R[f]=D,b({ranges:Object.keys(R).length?R:void 0})},S=f=>{if(f===""){b({targetValue:void 0});return}const O=Number(f);b({targetValue:Number.isNaN(O)?void 0:O})},y=(f,O)=>{const D=O.trim(),R={...l.rangeLabels||{}};D?R[f]=D:delete R[f],b({rangeLabels:Object.keys(R).length>0?R:void 0})},k=f=>{m(f),b({showRanges:f})},E=f=>{g(f),b({rangesArePercentages:f})},A=l.orientation||(((V=s==null?void 0:s.chartOptions)==null?void 0:V.indexAxis)==="y"?"horizontal":"vertical"),T=f=>{b({orientation:f}),d(f==="horizontal"?"y":"x")},I=[{value:"__none",label:"None"},...N.map(f=>({value:f.value,label:f.label}))],L=I,j=f=>{if(v(f),!f){b({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){b({disableAutoComparative:!1});return}if(l.comparativeMetricKey)b({disableAutoComparative:!1});else{const O=N.find(D=>D.value!==l.targetMetricKey);b({comparativeMetricKey:O==null?void 0:O.value,disableAutoComparative:!1})}};return e.jsxs(n.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(n.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:A,onValueChange:f=>T(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:l.targetMetricKey||"__none",onValueChange:f=>b({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"}),N.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:l.comparativeMetricKey||"__none",onValueChange:f=>b({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:I.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:h,onCheckedChange:f=>j(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(at,{type:"number",className:"h-8 text-xs",value:M,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:u,onCheckedChange:k})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!u,onChange:f=>E(f.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),u&&e.jsx("div",{className:"space-y-3",children:Zn.map(f=>{var O,D,R,B,Y;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(at,{placeholder:`Display label (${f})`,value:((O=l.rangeLabels)==null?void 0:O[f])||"",onCommit:_=>y(f,_),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((D=l.rangeKeys)==null?void 0:D[f])||"__none",onValueChange:_=>{_==="__none"?w(f,""):w(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:L.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(at,{placeholder:"Column key",value:((R=l.rangeKeys)==null?void 0:R[f])||"",onCommit:_=>w(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(at,{type:"number",placeholder:x?"0.80":"Static value",value:((B=l.ranges)==null?void 0:B[f])===void 0?"":String((Y=l.ranges)==null?void 0:Y[f]),onCommit:_=>F(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ta(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 zl(){var y,k,E,A,T,I,L,j,P,V,f,O;const s=t.useEditorStore(D=>D.card.preferences),a=t.useEditorStore(D=>D.card),r=n.useEffectiveEditorCardType(),o=t.useEditorStore(D=>D.isDevMode),{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions(),i=r==="bubble",c=r==="scatter",u=C.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),x=Ke.hasValidCardConfig(a==null?void 0:a.config)&&!o,g=C.useMemo(()=>{var D,R;return((R=(D=a==null?void 0:a.config)==null?void 0:D.metricColumns)==null?void 0:R.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(y=a==null?void 0:a.config)==null?void 0:y.metricColumns]),p=C.useMemo(()=>{var D,R;return((R=(D=a==null?void 0:a.config)==null?void 0:D.groupByColumns)==null?void 0:R.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns]),h=C.useMemo(()=>u.enableGrouping!==void 0?u.enableGrouping:!o&&p.length>=2,[u.enableGrouping,o,p.length]),[v,M]=C.useState(h);C.useEffect(()=>{M(h)},[h]);const N=D=>{const R={...s||{},bubbleScatterConfig:D};d(R),a&&l({...a,preferences:R})},b=D=>{d(D),a&&l({...a,preferences:D})};C.useEffect(()=>{if(!s||g.length===0)return;const D={};let R=!1;if(!u.xMetricKey&&g[0]&&(D.xMetricKey=g[0].value,R=!0),!u.yMetricKey&&g[1]&&(D.yMetricKey=g[1].value,R=!0),i&&!u.radiusMetricKey&&g[2]&&(D.radiusMetricKey=g[2].value,R=!0),!u.labelKey&&p[0]&&(D.labelKey=p[0].value,R=!0),h&&!u.groupKey&&p[1]&&(D.groupKey=p[1].value,D.enableGrouping=!0,R=!0),R){const B=ta({...u,...D});N(B)}},[g,p,u,s,d,i,h]);const w=D=>{const R=ta({...u,...D});N(R)},F=D=>{M(D),w({enableGrouping:D,groupKey:D?u.groupKey:void 0})};if(!i&&!c)return null;const S=i?n.Circle:n.ChartScatter;return e.jsxs(n.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(n.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"}),x?e.jsxs(t.Select,{value:u.labelKey||"",onValueChange:D=>w({labelKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:p.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for labels",value:u.labelKey||"",onCommit:D=>w({labelKey:D})})]}),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:v,onCheckedChange:F})]}),v&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(t.Select,{value:u.groupKey||"",onValueChange:D=>w({groupKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:p.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:u.groupKey||"",onCommit:D=>w({groupKey:D})})]})]}),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"}),x?e.jsxs(t.Select,{value:u.xMetricKey||"",onValueChange:D=>w({xMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:u.xMetricKey||"",onCommit:D=>w({xMetricKey:D})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(t.Select,{value:u.yMetricKey||"",onValueChange:D=>w({yMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:u.yMetricKey||"",onCommit:D=>w({yMetricKey:D})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(t.Select,{value:u.radiusMetricKey||"",onValueChange:D=>w({radiusMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for radius",value:u.radiusMetricKey||"",onCommit:D=>w({radiusMetricKey:D})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:u.radiusScale||"sqrt",onValueChange:D=>w({radiusScale:D}),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"})]})]})]}),u.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(at,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((E=u.minRadius)==null?void 0:E.toString())||"",onCommit:D=>w({minRadius:D?Number(D):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(at,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((A=u.maxRadius)==null?void 0:A.toString())||"",onCommit:D=>w({maxRadius:D?Number(D):void 0})})]})]}),u.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",u.fixedRadius||10]}),e.jsx(n.Slider,{value:[u.fixedRadius||10],onValueChange:([D])=>w({fixedRadius:D}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",u.fixedRadius||5]}),e.jsx(n.Slider,{value:[u.fixedRadius||5],onValueChange:([D])=>w({fixedRadius:D}),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:((I=(T=s==null?void 0:s.xAxisConfig)==null?void 0:T.name)==null?void 0:I.enabled)??!1,onCheckedChange:D=>{var Y,_,z,U;const R=u.xMetricKey||"X Axis",B=u.yMetricKey||"Y Axis";b({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:D,text:((_=(Y=s==null?void 0:s.xAxisConfig)==null?void 0:Y.name)==null?void 0:_.text)||R}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:D,text:((U=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:U.text)||B}}})}})]}),((j=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:j.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(at,{className:"h-8 text-xs",placeholder:u.xMetricKey||"X Axis",value:((V=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:V.text)||"",onCommit:D=>{var R;b({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name,enabled:!0,text:D||u.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(at,{className:"h-8 text-xs",placeholder:u.yMetricKey||"Y Axis",value:((O=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:O.text)||"",onCommit:D=>{var R;b({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(R=s==null?void 0:s.yAxisConfig)==null?void 0:R.name,enabled:!0,text:D||u.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const ql=[{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 $l(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",d=(a==null?void 0:a.funnelConfig)||{},l=d.percentMode??"percentOfTotal",i=d.shrinkFraction??1,c=d.labelThreshold??0,u=p=>{const h={...d,...p};r({...a||{},funnelConfig:h})},m=p=>{u({percentMode:p})},x=p=>{u({shrinkFraction:p[0]})},g=p=>{u({labelThreshold:p[0]})};return o?e.jsxs(n.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(n.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(n.RadioGroup,{value:l,onValueChange:p=>m(p),className:"space-y-2",children:ql.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.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(n.Slider,{value:[i],onValueChange:x,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(i*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(n.Slider,{value:[c],onValueChange:g,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function ds(){const s=t.useEditorStore(i=>i.card),{data:a,comparisonMetadata:r}=n.useEditorCardQuery(s),{keys:o}=n.getKeys((a==null?void 0:a.records)||[],r),d=o.slice(1).filter(i=>!Ke.METADATA_KEYS.includes(i));let l=d;if(["stackedBar","stackedLine"].includes(s.type)){const i=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:o[0],pivotKey:o[1],valueKey:o[2]}),{keys:c}=n.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:o.slice(0,1),keys:o,defaultMetricKeys:d}}const Kl=[{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"}],Ul=[{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)"}],Hl=["center","start","end"],Gl=["center","start","end","top","bottom"];function us({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:d,showAppearance:l=!0}){var v,M,N,b,w,F;const i=d??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],u=(S,y)=>{const k={...s,[S]:y};a(k)},m=(S,y)=>{const k={...s,font:{...(s==null?void 0:s.font)||{},[S]:y}};a(k)},x=(S,y)=>{const k={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:y}};a(k)},g=()=>r?"Right":"Top",p=s||{},h=p.format||(o?"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:p.position||"auto",onValueChange:S=>u("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?g():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),p.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:p.anchor||"center",onValueChange:S=>u("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.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(p.align||"center"),onValueChange:S=>u("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.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:h,onValueChange:S=>u("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&o?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["auto","none"].includes(h)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(h)&&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(ct,{type:"number",placeholder:"0",value:String(((v=p.formatOptions)==null?void 0:v.decimalPlaces)??(h==="currency"?2:h==="percent"?1:0)),onSave:S=>x("decimalPlaces",Number(S)),className:""})})]}),h==="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:((M=p.formatOptions)==null?void 0:M.currency)||"USD",onValueChange:S=>x("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]}),["number","currency"].includes(h)&&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:((N=p.formatOptions)==null?void 0:N.useSuffix)??!1,onCheckedChange:S=>x("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:((b=p.formatOptions)==null?void 0:b.locale)||"en-US",onValueChange:S=>x("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]})]}),l&&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(ct,{type:"number",placeholder:"12",value:String(((w=p.font)==null?void 0:w.size)||12),onSave:S=>m("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:((F=p.font)==null?void 0:F.weight)||"normal",onValueChange:S=>m("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:p.color==="auto"||!p.color?"auto":"custom",onValueChange:S=>{S==="auto"&&u("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(ct,{type:"number",placeholder:"0",value:String(p.rotation||0),onSave:S=>u("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Ql=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Wl=[0,1,2,3,4,5,6,8,10],Jl=[{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 │"}],Xl=[{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 r;return(r=a.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(n.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(ei,{})})]})}function ei(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(ti,{metricKey:a,idx:r},a))})}function ti({metricKey:s,idx:a}){var b;const[r,o]=C.useState(!1),d=t.useEditorStore(w=>{var F;return(F=w.card)==null?void 0:F.preferences}),l=t.useEditorStore(w=>{var F,S;return(S=(F=w.card)==null?void 0:F.preferences)==null?void 0:S.datasetOptions}),i=l==null?void 0:l.find(w=>w.idx===a),{setCardPreferences:c}=t.useEditorStore(w=>w.actions),u=(i==null?void 0:i.type)||"bar",m=(i==null?void 0:i.yAxisId)||"y",x=((b=i==null?void 0:i.dataLabels)==null?void 0:b.enabled)??!1,g=u==="line"?n.ChartLine:n.ChartColumnIncreasing;function p(w){const F={idx:a,type:u,yAxisId:m,dataLabels:i==null?void 0:i.dataLabels,...w};if(!i)c({...d||{},datasetOptions:[...l||[],F]});else{const S=l==null?void 0:l.map(y=>y.idx===a?{...y,...F}:y);c({...d||{},datasetOptions:S})}}function h(w){p({type:w})}function v(w){p({yAxisId:w})}function M(w){p({dataLabels:{...i==null?void 0:i.dataLabels,enabled:w}})}function N(w){p({dataLabels:w})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(g,{className:"h-3 w-3"}),u==="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:m==="y2"?"Y2":"Y1"})]})]})}),e.jsx(n.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:Ql.map(({type:w,icon:F,label:S})=>{const y=u===w;return e.jsxs("button",{onClick:()=>h(w),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",y?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(F,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:S})]},w)})})]}),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:m,onValueChange:w=>v(w),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)"})]})]})]})]}),u==="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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:w=>p({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(({value:w,label:F})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:F},w))})]})]}),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((i==null?void 0:i.pointRadius)??3),onValueChange:w=>p({pointRadius:Number(w)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(w=>e.jsx(t.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:w=>p({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:w,label:F})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:F},w))})]})]})]})]}),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:M})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:N,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ts=[{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"}],si=[0,1,2,3,4,5,6,8,10],ni=[{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 │"}],ai=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ri(s){return s==null?"origin":s===!1?"false":s}function oi(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(n.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(li,{})})]})}function li(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(ii,{metricKey:a,idx:r},a))})}function ii({metricKey:s,idx:a}){var M;const[r,o]=C.useState(!1),d=t.useEditorStore(N=>{var b;return(b=N.card)==null?void 0:b.preferences}),l=t.useEditorStore(N=>{var b,w;return(w=(b=N.card)==null?void 0:b.preferences)==null?void 0:w.datasetOptions}),i=l==null?void 0:l.find(N=>N.idx===a),{setCardPreferences:c}=t.useEditorStore(N=>N.actions),u=ri(i==null?void 0:i.fill),m=((M=i==null?void 0:i.dataLabels)==null?void 0:M.enabled)??!1,x=Ts.find(N=>N.value===u)||Ts[0];function g(N){const b={idx:a,fill:u,dataLabels:i==null?void 0:i.dataLabels,...N};if(!i)c({...d||{},datasetOptions:[...l||[],b]});else{const w=l==null?void 0:l.map(F=>F.idx===a?{...F,...b}:F);c({...d||{},datasetOptions:w})}}function p(N){g({fill:N==="false"?!1:N})}function h(N){g({dataLabels:{...i==null?void 0:i.dataLabels,enabled:N}})}function v(N){g({dataLabels:N})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(n.ChartArea,{className:"h-3 w-3"}),x.label.split(" ")[0]]})})]})}),e.jsx(n.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:u,onValueChange:N=>p(N),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ts.map(N=>e.jsx(t.SelectItem,{value:N.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:N.label})})},N.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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:N=>g({lineStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ai.map(({value:N,label:b})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:b},N))})]})]}),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((i==null?void 0:i.pointRadius)??3),onValueChange:N=>g({pointRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:si.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":N},N))})]})]}),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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:N=>g({pointStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ni.map(({value:N,label:b})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:b},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 text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:h})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ci=[0,1,2,3,4,5,6,8,10],di=[{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 │"}],Es=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ui(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="line"?null:e.jsxs(n.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(mi,{})})]})}function mi(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(xi,{metricKey:a,idx:r},a))})}function xi({metricKey:s,idx:a}){var N;const[r,o]=C.useState(!1),d=t.useEditorStore(b=>{var w;return(w=b.card)==null?void 0:w.preferences}),l=t.useEditorStore(b=>{var w,F;return(F=(w=b.card)==null?void 0:w.preferences)==null?void 0:F.datasetOptions}),i=l==null?void 0:l.find(b=>b.idx===a),{setCardPreferences:c}=t.useEditorStore(b=>b.actions),u=(i==null?void 0:i.lineStyle)||"solid",m=(i==null?void 0:i.pointRadius)??3,x=(i==null?void 0:i.pointStyle)||"circle",g=((N=i==null?void 0:i.dataLabels)==null?void 0:N.enabled)??!1,p=Es.find(b=>b.value===u)||Es[0];function h(b){const w={idx:a,lineStyle:u,pointRadius:m,pointStyle:x,dataLabels:i==null?void 0:i.dataLabels,...b};if(!i)c({...d||{},datasetOptions:[...l||[],w]});else{const F=l==null?void 0:l.map(S=>S.idx===a?{...S,...w}:S);c({...d||{},datasetOptions:F})}}function v(b){h({dataLabels:{...i==null?void 0:i.dataLabels,enabled:b}})}function M(b){h({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(Rr,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(n.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:u,onValueChange:b=>h({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Es.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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(m),onValueChange:b=>h({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:ci.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:x,onValueChange:b=>h({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:di.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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:g,onCheckedChange:v})]}),g&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:M,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const hi=[0,2,4,6,8,10,12,16,20];function pi(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(n.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(fi,{})})]})}function fi(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(gi,{metricKey:a,idx:r},a))})}function gi({metricKey:s,idx:a}){var v;const[r,o]=C.useState(!1),d=t.useEditorStore(M=>{var N;return(N=M.card)==null?void 0:N.type}),l=t.useEditorStore(M=>{var N;return(N=M.card)==null?void 0:N.preferences}),i=t.useEditorStore(M=>{var N,b;return(b=(N=M.card)==null?void 0:N.preferences)==null?void 0:b.datasetOptions}),c=i==null?void 0:i.find(M=>M.idx===a),{setCardPreferences:u}=t.useEditorStore(M=>M.actions),m=(c==null?void 0:c.borderRadius)??0,x=((v=c==null?void 0:c.dataLabels)==null?void 0:v.enabled)??!1;function g(M){const N={idx:a,borderRadius:m,dataLabels:c==null?void 0:c.dataLabels,...M};if(!c)u({...l||{},datasetOptions:[...i||[],N]});else{const b=i==null?void 0:i.map(w=>w.idx===a?{...w,...N}:w);u({...l||{},datasetOptions:b})}}function p(M){g({dataLabels:{...c==null?void 0:c.dataLabels,enabled:M}})}function h(M){g({dataLabels:M})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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:m>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:",m]})})]})}),e.jsx(n.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(m),onValueChange:M=>g({borderRadius:Number(M)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hi.map(M=>e.jsx(t.SelectItem,{value:String(M),className:"text-xs",children:M===0?"None":`${M}px`},M))})]})]})})]}),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:p})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:c==null?void 0:c.dataLabels,onChange:h,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const bi=[0,1,2,3,4,5,6,8,10],ji=[{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 │"}],vi=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function yi(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.preferences}),r=n.useEffectiveEditorCardType(),o=a==null?void 0:a.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const i=(c,u)=>{const m={...a||{},lineStyleConfig:{...o,[c]:u}};d(m),l({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(n.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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:c=>i("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vi.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:c=>i("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bi.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:c=>i("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ji.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]})]})})]})}const Ci=[0,2,4,6,8,10,12,16,20],Ni=[{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%"}],Si=[{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 wi(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.preferences}),r=n.useEffectiveEditorCardType(),o=a==null?void 0:a.barStyleConfig,{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const i=(c,u)=>{const m={...a||{},barStyleConfig:{...o,[c]:u}};d(m),l({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] 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(n.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((o==null?void 0:o.borderRadius)??0),onValueChange:c=>i("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ci.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.barPercentage)??.9),onValueChange:c=>i("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ni.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.categoryPercentage)??.8),onValueChange:c=>i("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Si.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]})]})})]})}function Ti(){const s=t.useEditorStore(r=>{var o,d;return(d=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(n.AccordionItem,{value:"stacked-sort",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(n.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(Ct,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})})]})}const Ei=["kpi"],Is=2;function Dt(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 Ii(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 Di(s){return{...s,role:"groupby"}}function ki(){var w,F;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),r=n.useEffectiveEditorCardType(),{scopedFields:o}=n.useScopedFields(),d=((w=s.config)==null?void 0:w.metricColumns)||[],l=((F=s.config)==null?void 0:F.summary)||{},i=l.breakdownDimensions||[],c=i.length>0,u=Ei.includes(r),m=d.length>0,x=l.enabled===!0,g=u&&m,p=Array.from(new Map(o.filter(Ii).map(S=>[Dt(S),Di(S)])).values()),h=new Set(p.map(S=>Dt(S))),v=new Set(i.map(S=>Dt(S)).filter(S=>S&&h.has(S)));if(!u)return null;const M=S=>{a(s.id,{summary:{...l,...S}})},N=(S,y)=>{const k=Dt(S),E=p.filter(T=>v.has(Dt(T))),A=y?v.has(k)?E:[...E,S].slice(0,Is):E.filter(T=>Dt(T)!==k);M({breakdownDimensions:A,...A.length>0?{showOnCard:!0}:{}})},b=S=>{if(!S){M({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}M({enabled:!0,showOnCard:l.showOnCard??!0,includeInDashboardSummary:l.includeInDashboardSummary??!0})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:[e.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]}),e.jsx(t.Switch,{size:"xs",checked:x,disabled:!g,onClick:S=>S.stopPropagation(),onPointerDown:S=>S.stopPropagation(),onCheckedChange:b,"aria-label":"Enable summary"})]}),e.jsx(n.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!x&&"opacity-60"),children:[!g&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:m?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-show-on-card",checked:l.showOnCard===!0,disabled:!x,onCheckedChange:S=>M({showOnCard:S===!0})}),e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"cursor-pointer text-xs",children:"Show summary on card"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-include-rollup",checked:l.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:S=>M({includeInDashboardSummary:S===!0})}),e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"cursor-pointer text-xs",children:"Include in dashboard summary"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[i.length,"/",Is]})]}),p.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("ul",{className:"max-h-40 space-y-1 overflow-y-auto",children:p.map(S=>{const y=Dt(S),k=v.has(y),E=v.size>=Is,A=!x||!k&&E;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${y}`,checked:k,disabled:A,onCheckedChange:T=>N(S,T===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${y}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},y)})})]})]})})]})}const Mi=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Ai(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),r=n.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions();if(!s||!Mi.has(r||""))return null;const l=a==null?void 0:a.tooltipConfig,i=(l==null?void 0:l.formatMode)||(l==null?void 0:l.mode)||"inherit",c=u=>{const m={...a||{},tooltipConfig:{...l||{},...u}};o(m),d({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(n.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:i==="override",onCheckedChange:u=>c({formatMode:u?"override":"inherit",mode:u?"override":"inherit"})})]}),i==="override"&&e.jsx(Xt,{formatOptions:(l==null?void 0:l.formatOptions)||{},onFormatOptionsChange:u=>c({formatMode:"override",mode:"override",formatOptions:u}),showTitle:!1})]})]})}function Oa({mode:s}){const a=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return t.isTableChartType(a)?null:e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Zl,{}),(a==="area"||a==="stackedArea")&&e.jsx(oi,{}),a==="line"&&e.jsx(ui,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(pi,{}),e.jsx(yi,{}),e.jsx(wi,{}),e.jsx(Bl,{}),s==="config"&&e.jsx(El,{}),s==="config"&&e.jsx(ki,{}),e.jsx(_l,{}),a==="bullet"&&e.jsx(Yl,{}),a==="funnel"&&e.jsx($l,{}),(a==="bubble"||a==="scatter")&&e.jsx(zl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(Ti,{}),e.jsx(Fl,{}),e.jsx(Rl,{}),e.jsx(Pl,{}),e.jsx(Ol,{}),e.jsx(Ai,{})]})}function Li(){const s=t.useEditorStore(r=>r.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Vs,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Oa,{mode:"dev"})})]}):null}function Fi({focusSection:s,focusRequestId:a}){const r=t.useEditorStore(i=>i.card),o=r.type;if(t.getVisualizationMode(r)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(n.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(n.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(n.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 l(){if(t.supportsRegularTableSettings(o))return e.jsx(Pa,{cardType:o,focusSection:s,focusRequestId:a});switch(o){case"kpi":return e.jsx(jl,{});case"map":return e.jsx(Sl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ma,{})});case"text":return e.jsx(Dl,{});default:return e.jsx(Li,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[l(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}const sa=32;function Ri(){const s=C.useRef(null),a=C.useRef(null),r=t.useEditorStore(b=>b.isShowingVisual),o=t.useEditorStore(b=>b.isDevMode),d=t.useEditorStore(b=>b.showAIDialog),[l,i]=C.useState(!1),[c,u]=C.useState({section:null,id:0}),m=r&&!d,x=m&&(!o||l),g=o&&m,p=()=>i(b=>!b),h=b=>{b&&u(w=>({section:b,id:w.id+1})),o&&i(!0)};C.useEffect(()=>{var b,w,F,S;d?((b=s.current)==null||b.resize(0),(w=a.current)==null||w.resize(0)):((F=s.current)==null||F.resize(sa),(S=a.current)==null||S.resize(25))},[d]);const[v,M]=C.useState(!1),N=m?{show:g,isOpen:x,onToggle:p,onOpen:h}:void 0;return e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(n.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:50,children:e.jsx("div",{className:"flex min-w-0 flex-1 flex-col",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(uo,{renderCommandBarEnd:b=>e.jsx(ys,{mode:"toolbar",inlineToolbar:!0,overflowActions:b,visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})})})})}),e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:x?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ys,{mode:"canvas",visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})}),!d&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:sa,maxSize:45,children:e.jsx(Fi,{focusSection:c.section,focusRequestId:c.id})})]}):e.jsx(ys,{mode:"canvas",visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})})]})}function Pi(s){var Ie;t.useAIInteractionStore($=>$.currentAIContext);const[a,r]=C.useState(""),[o,d]=C.useState(null),{authToken:l,tokenProps:i}=n.useSemaphorContext(),c=t.useEditorStore($=>$.card.id),u=t.useEditorStore($=>{var xe;return(xe=$==null?void 0:$.card)==null?void 0:xe.sql}),m=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>{var xe;return(xe=$==null?void 0:$.card)==null?void 0:xe.python}),{setCardPython:g,setCardSql:p,setRunSql:h,switchCardType:v,setQueryConfig:M}=t.useEditorActions(),N=t.useEditorStore($=>$.currentAssitantScope)||[],b=t.useEditorStore($=>$.userInputForAI),w=t.useEditorStore($=>$.triggerAIRun),F=t.useEditorStore($=>$.card),S=t.useEditorStore($=>$.selectedDatabaseName),y=t.useEditorStore($=>$.selectedTableName),k=t.useEditorStore($=>$.selectedConnectionId),E=t.useEditorStore($=>$.selectedSchemaName),A=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:T,refetch:I,data:L}=n.useEditorCardQuery(F),{setTriggerAIRun:j,setCurrentAssitantScope:P,setCardConfig:V}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:O,selectedDatamodelId:D}=n.useEditorAside(),R=(Ie=n.useDashboardQuery().data)==null?void 0:Ie.assistantProfileId,B=C.useRef(n.createAssistantConversationId()),Y=C.useRef(null),_=C.useRef(c),z=C.useRef(!1),U=()=>{const $=Y.current;$&&(Y.current=null,B.current=n.createAssistantConversationId(),$==="clear"&&q([]))},{messages:G,setMessages:q,regenerate:Q,error:H,sendMessage:se,status:ce,addToolResult:ge,stop:fe,clearError:Te}=n.useChat({transport:new n.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${l==null?void 0:l.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:R,conversationId:B.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:m,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:xe})=>({body:{...xe,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var xe;if(z.current=!1,$.name==="AbortError"||(xe=$.message)!=null&&xe.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",$),U()},onToolCall:Ee,onFinish({isAbort:$,isDisconnect:xe,isError:Ce}){z.current=!1,r(""),console.log($?"[Editor Assistant] Stream aborted by user":xe?"[Editor Assistant] Stream disconnected (network error)":Ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),Ve=C.useCallback($=>{z.current=!0;try{const xe=se($);return n.isPromiseLike(xe)?xe.catch(Ce=>{throw z.current=!1,Ce}):xe}catch(xe){throw z.current=!1,xe}},[se]),Ue=C.useCallback(()=>{z.current=!0;try{const $=Q();return n.isPromiseLike($)?$.catch(xe=>{throw z.current=!1,xe}):$}catch($){throw z.current=!1,$}},[Q]),Me=$=>{let xe=!1;q(Ce=>{const ae=typeof $=="function"?$(Ce):$;if(ae.length===0){if(z.current)return Y.current="clear",xe=!0,Ce;Y.current=null,B.current=n.createAssistantConversationId()}return ae}),xe&&fe()};C.useEffect(()=>{if(_.current!==c){if(_.current=c,z.current){Y.current!=="clear"&&(Y.current="rotate"),fe();return}Y.current=null,B.current=n.createAssistantConversationId()}},[c,fe]),C.useEffect(()=>{w&&b&&(Ve({role:"user",parts:[{type:"text",text:b}]}),j(!1))},[w,b,Ve,j]);async function Ee({toolCall:$}){var xe,Ce,ae,ie,Re,Z,Ae,ze,We,_e,Xe,Ze,et,re,J,pe;if(["createChartFromSql","createForecast"].includes($.toolName)){const ue=((xe=$.input)==null?void 0:xe.sql)??((Ce=$.args)==null?void 0:Ce.sql),ne=((ae=$.input)==null?void 0:ae.python)??((ie=$.args)==null?void 0:ie.python),me=((Re=$.input)==null?void 0:Re.chartType)??((Z=$.args)==null?void 0:Z.chartType);v(me),p(ue),g(ne),h(!0),ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!u){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:u,python:x||""}})}else if($.toolName==="generateQueryConfig"){r("Generating query config...");const ue=((Ae=$.input)==null?void 0:Ae.chartType)??((ze=$.args)==null?void 0:ze.chartType),ne=((We=$.input)==null?void 0:We.queryConfig)??((_e=$.args)==null?void 0:_e.queryConfig);((Xe=$.input)==null?void 0:Xe.cardConfig)??((Ze=$.args)==null||Ze.cardConfig),v(ue),V(ne),p(void 0),g(void 0);const me=await I();if((et=me==null?void 0:me.data)!=null&&et.error){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ne,message:(re=me==null?void 0:me.data)==null?void 0:re.error.message}});return}if((J=me==null?void 0:me.data)!=null&&J.records){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(pe=me==null?void 0:me.data)==null?void 0:pe.records}})}else r("Analyzing...")}function Fe($){const xe=n.removeFromScopeArray(N,$);Oe(xe)}function Oe($){const xe=n.sanitizeAIScope($);P(xe),q(Ce=>[...Ce,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(xe)}`}]}])}function Pe(){const $={databaseName:S||"",schemaName:E||"",tableName:y||"",datamodelId:D||"",datamodelName:t.resolveDatamodelName(f),connectionId:k||"",connectionType:O||""},xe=n.dedup([...N,$]);Oe(xe)}function le(){const $={databaseName:S||"",schemaName:E||"",tableName:y||"",datamodelName:t.resolveDatamodelName(f),connectionId:k||"",connectionType:O||"",datamodelId:D||""};if(!n.isInAiScopeArray([...A||[],...N],$)||N.length===0){const Ce=n.dedup([...A||[],...N,$]).filter(ae=>ae.connectionId===$.connectionId);Oe(Ce)}}const De=!["ready","error"].includes(ce),ve=n.getErrorMessage(H);return{messages:G,setMessages:Me,sendMessage:Ve,regenerate:Ue,isLoading:De,handleSetAIScope:le,handleAddCurrentTableToScope:Pe,removeFromCurrentSelections:Fe,currentAssitantScope:N,setCurrentAssitantScope:P,stop:fe,status:ce,toolStatus:a,llmUsage:o,onFinish:s,errorMessage:ve,clearError:Te}}const Oi=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function na({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const o=C.useRef(null),d=C.useRef(!1),[l,i]=C.useState(!1),[c,u]=C.useState(Ke.isDevEnv),[m,x]=C.useState(!1),[g,p]=C.useState(!1),[h,v]=C.useState(!1),[M,N]=C.useState(0),b=s??h,w=t.useCurrentAIContext(),{setCurrentAIContext:F,setHasEditorEntitySelectionOverride:S}=t.useAIActions(),{clearQueue:y}=t.useQueueActions(),{clearFileAttachments:k}=t.useFileActions(),E=t.useFileAttachments("editor"),{selectedEntities:A}=n.useAssistantContextEntities("editor"),T=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),L=t.useEditorStore(ae=>{var ie;return(ie=ae.card.dataSource)==null?void 0:ie.selectedEntities}),j=t.useEditorStore(ae=>ae.actions.setCardSql),P=t.useEditorStore(ae=>ae.actions.setRunSql),V=t.useEditorStore(ae=>ae.showAIDialog),f=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:O,setCardPython:D}=t.useEditorActions(),{assistantProfile:R}=n.useAssistantProfile(),{messages:B,setMessages:Y,sendMessage:_,isLoading:z,stop:U,status:G,llmUsage:q,errorMessage:Q,clearError:H}=Pi(),[se,ce]=C.useState(""),ge=ae=>{ce(ae.target.value)},fe=ae=>{ae.preventDefault();const ie=se.trim();if(!ie&&E.length===0)return;const Re=[];ie&&Re.push({type:"text",text:ie}),E.forEach(Z=>{Z.data&&Re.push({type:"file",mediaType:Z.type,filename:Z.name,url:`data:${Z.type};base64,${Z.data}`})}),_({role:"user",parts:Re}),ce(""),k("editor"),Te()},Te=C.useCallback(()=>{N(ae=>ae+1)},[]);C.useEffect(()=>{var ae;V&&!d.current&&((ae=o.current)==null||ae.focus()),d.current=V},[V]),C.useEffect(()=>{V&&(S(!1),F({selectedEntities:L||[]}))},[T,L,F,S,V]),n.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:z,sendMessage:_});const{hasActiveTools:Ve,activeToolText:Ue}=n.useActiveToolStatus(B),Me=C.useCallback(ae=>{a==null||a(ae),s===void 0&&v(ae)},[s,a]);C.useEffect(()=>{if(!b)return;function ae(ie){ie.key==="Escape"&&Me(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[b,Me]);const Ee=C.useCallback(ae=>{_({role:"user",parts:[{type:"text",text:ae}]}),Te()},[Te,_]),Fe=C.useCallback(async()=>{const ae=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),n.ue.success("Conversation copied")}catch(ie){console.error("Failed to copy conversation",ie),n.ue.error("Unable to copy conversation")}},[B]),Oe=C.useCallback(()=>{Me(!b)},[b,Me]);function Pe(ae,ie){ie==="sql"?(j(ae),P(!0)):ie==="python"&&(D(ae),P(!0))}function le(){w.selectedEntities.length===0&&F({selectedEntities:A})}function De(ae){le();const ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};_(ie),Te()}function ve(ae){le(),_({role:"user",parts:[{type:"text",text:ae}]}),Te()}function Ie(){return e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",size:"xs",variant:"ghost","aria-label":"Assistant options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",children:[e.jsx(n.DropdownMenuLabel,{children:"Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:i,children:"Token usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:u,children:"Tool invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:x,children:"System message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",className:"flex min-w-0 items-center",children:e.jsx("div",{className:"truncate text-[13px] font-medium",children:"Assistant"})})}const xe=(se==null?void 0:se.length)===0&&(B==null?void 0:B.filter(ae=>ae.role==="user").length)===0,Ce=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-card 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-center justify-between gap-2",children:[$(),f&&e.jsx(t.Button,{variant:"outline",size:"xs",className:"min-w-0 shrink",onClick:f,children:e.jsx("span",{className:"truncate",children:(R==null?void 0:R.name)||"Default profile"})}),e.jsxs("div",{"data-role":"header-actions",className:"flex shrink-0 items-center gap-1.5",children:[Ie(),c&&e.jsx(t.Button,{variant:"ghost",size:"xs",className:"text-muted-foreground hover:text-foreground",onClick:Fe,children:"Copy conversation"}),e.jsx(n.IconButton,{tooltip:b?"Exit fullscreen":"Expand",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:Oe,children:b?e.jsx(Ye.Minimize2,{className:"h-3.5 w-3.5"}):e.jsx(Ye.Maximize2,{className:"h-3.5 w-3.5"})}),e.jsx(n.IconButton,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",tooltip:"New chat",onClick:()=>{Y([]),y("editor"),H()},children:e.jsx(n.SquarePen,{className:"h-3.5 w-3.5"})}),e.jsx(n.IconButton,{tooltip:"Close",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>{O(!1)},children:e.jsx(oe.X,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(n.AssistantVirtualizedMessages,{messages:B,showTools:c,handleRun:Pe,showSystemMessage:m,onQuickReply:Ee,disableQuickReplies:z,status:G,errorMessage:Q,activeToolText:z&&Ve?Ue:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:V?"bottom-24 right-8":"hidden",scrollToEndSignal:M}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[xe&&!R&&e.jsx(n.Placeholders,{onClick:De,placeholders:Oi}),e.jsx("div",{children:xe&&R&&e.jsx(n.SeedQuestions,{seedQuestions:R.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:o,setInput:ce,stop:U,input:se,handleInputChange:ge,handleSubmit:ae=>{le(),fe(ae)},isLoading:z,status:G,assistantType:"editor",onFocus:()=>{}})]}),q&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",q.inputTokens," prompt tokens, ",q.outputTokens," ","completion tokens, ",q.totalTokens," total tokens"]})}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:A,open:g,onOpenChange:p,dataSource:I||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{S(!0),F({...w,selectedEntities:ae})}})]});return b&&r?dr.createPortal(e.jsx(n.SemaphorStyleWrapper,{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:Ce})}),r):Ce}function Ba(s,a,r){if(!a)return!1;const o=a.qualifiedFieldName,d=a.qualifiedEntityName,l=d&&a.name?`${d}.${a.name}`:o;return s.some(i=>{if(!(t.getDataType(i.dataType||"")==="date"))return!1;const u=n.getSelectedDateFilterColumn(i,r),m=u.split("."),x=m[m.length-1]||u,g=m.length>1?m.slice(0,-1).join("."):void 0,p=i.qualifiedTableName||g,h=p?`${p}.${x}`:void 0;return o?h?h===l||h.endsWith(`.${o}`):x===a.name:h?h===l:x===a.name})}function Bi({dashboard:s,dateGroupByField:a,dashboardInputValues:r,sheetId:o,card:d,timezone:l}){var m;if(!s||!a)return!1;const i=(m=s.inputs)==null?void 0:m.filter(x=>x.kind==="filter"&&!x.compatibility);if(!(i!=null&&i.length))return!1;const c={...s,inputs:i,controls:[]};return n.resolveDashboardInputContext({dashboard:c,sheetId:o,card:d,sheetKind:"dashboard",runtimeValues:{dashboardInputValues:r},mode:"editor",timezone:l}).resolvedInputs.some(x=>x.kind!=="filter"||!x.filter||!x.filterValue?!1:Ba([x.filter],a,[x.filterValue]))}function Vi(s){switch(s){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function _i({aliasTemplate:s,onAliasTemplateChange:a}){var u;const[r,o]=C.useState(s),[d,l]=C.useState(!1),i=(u=t.useEditorStore(m=>{var x;return(x=m.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:u[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:d?r:s,onChange:m=>{o(m.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&d&&r!==s?(a(r),l(!1)):m.key==="Escape"&&(o(s),l(!1))},"aria-label":"Edit alias template"}),d&&r!==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(r),l(!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:()=>{o(s),l(!1)},children:e.jsx(oe.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Yi({valueAliases:s,onValueAliasesChange:a}){const[r,o]=C.useState(null),[d,l]=C.useState(""),[i,c]=C.useState(""),u=()=>{a({...s,"":""})},m=g=>{const p={...s};delete p[g],a(p)},x=g=>{const p={...s};delete p[g],p[d]=i,a(p),o(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(([g,p],h)=>e.jsx("div",{className:"flex items-center gap-2",children:r===g?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:v=>l(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?x(g):v.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:i,onChange:v=>c(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?x(g):v.key==="Escape"&&o(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:()=>x(g),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:()=>o(null),children:e.jsx(oe.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),l(g),c(p)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),l(g),c(p)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(g),"aria-label":"Remove value alias",children:e.jsx(oe.X,{className:"h-3 w-3"})})]})},g+h)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function zi({idx:s}){var c;const a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),r=t.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.datasetOptions}),o=t.useEditorStore(u=>u.actions.setCardPreferences),d=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,l=r==null?void 0:r.find(u=>u.idx===s);function i(u,m){(u==="end"||u==="start")&&Ke.getContrastColor(Ke.getCanvasBackgroundColor());const x={display:u!=="none",align:u,anchor:u,clamp:!0};if(!l)o({...a,datasetOptions:[...r||[],{idx:m,datalabels:x}]});else{const g={...l};g.datalabels=x;const p=r==null?void 0:r.map(h=>h.idx===m?g:h);o({...a,datasetOptions:p})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(n.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:()=>i("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(oe.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function _s({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 qi(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function $i({col:s,idx:a,className:r,iconClassName:o,children:d}){const l=t.useEditorStore(x=>{var g;return(g=x.card)==null?void 0:g.preferences}),i=t.useEditorStore(x=>{var g,p;return(p=(g=x.card)==null?void 0:g.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:u}=t.useEditorStore(x=>x.actions);function m(x){if(!c)u({...l,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const g={...c};g.type=x==="area"?"line":x,g.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(h=>h.idx===a?g:h);u({...l,datasetOptions:p})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[d||e.jsx(_s,{className:"max-w-[100px]",title:s,children:qi(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartLine,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartArea,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(zi,{idx:a})]})]})}function Ki(){const s=t.useEditorStore(c=>c.card.type),a=t.useEditorStore(c=>c.isDevMode),r=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:o}=t.useEditorStore(c=>c.actions);function d(c){var x;const u={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},m={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(x=r==null?void 0:r.chartOptions)==null?void 0:x.plugins,...u}}};o(m)}function l(){var c,u,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(u=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:u.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,u,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(u=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:u.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?l():i()})}function Ui({column:s}){const a=t.useEditorStore(u=>u.card.type),r=t.useEditorStore(u=>{var m,x;return(x=(m=u.card)==null?void 0:m.config)==null?void 0:x.metricColumns}),o=(r==null?void 0:r.map(u=>u.label))||[],d=o==null?void 0:o.find(u=>u===s.label||u===s.name),l=d?o.indexOf(d):-1;function i(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx($i,{idx:l,col:d,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ki,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Hi({field:s,searchQuery:a="",limit:r=500}){const{authToken:o,tokenProps:d}=n.useSemaphorContext(),l=t.useDashboardStore(x=>{var g;return((g=x.reportContext)==null?void 0:g.calendar)??null}),i=t.useEditorStore(x=>x.card),c=i==null?void 0:i.dataSource,u=["attribute-values",s.entityName,s.name,a,r,l],m=n.useQuery({queryKey:u,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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:r},g={connection_id:c.connectionId,cardConfig:x,cardDataSource:c,cache_config:t.getCacheConfig({card:i}),calendarContext:l};console.log("requestBody",g);const p=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",g);if(p!=null&&p.error)return console.error("Error fetching attribute values:",p.error),[];const h=s.name;return((p==null?void 0:p.records)||[]).map(M=>{const N=M[h]||M[s.alias||h]||M[s.label];return{id:N||"",value:N||"",label:String(N||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(c!=null&&c.connectionId)&&!!l,staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:m.data||[],isLoading:m.isLoading,isFetching:m.isFetching,isError:m.isError,error:m.error,refetch:m.refetch}}function Va({open:s,onOpenChange:a,availableFields:r,existingFilters:o,editingCondition:d,onSave:l}){var F,S;const i=!!d,[c,u]=C.useState(i?"values":"fields"),[m,x]=C.useState(""),[g,p]=C.useState({id:(d==null?void 0:d.id)||Ke.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),h=r.filter(y=>{var E;return i?!1:!((E=o==null?void 0:o.conditions)==null?void 0:E.some(A=>A.field.id===y.id))&&y.label.toLowerCase().includes(m.toLowerCase())}),v=y=>{p({...g,field:y}),u("values")},M=()=>{if(g.field&&g.selectedValues.length>0){const y={id:g.id,field:g.field,operator:"in",value:g.selectedValues};let k;if(i){const E=((o==null?void 0:o.conditions)||[]).map(A=>A.id===d.id?y:A);k={...o,conditions:E}}else{const E=(o==null?void 0:o.conditions)||[];k={id:(o==null?void 0:o.id)||Ke.v4(),logicalOperator:"AND",negate:!1,conditions:[...E,y],groups:[]}}l(k),a(!1)}},N=()=>{if(!i||!d)return;const y=((o==null?void 0:o.conditions)||[]).filter(k=>k.id!==d.id);if(y.length>0){const k={...o,conditions:y};l(k)}else l(void 0);a(!1)},b=y=>{p({...g,selectedValues:y})},w=()=>{i&&d?(p({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),u("values")):(p({id:Ke.v4(),field:null,selectedValues:[]}),u("fields")),x("")};return C.useEffect(()=>{s&&w()},[s,i,d]),e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-2xl",children:[e.jsx(n.DialogHeader,{children:e.jsx(n.DialogTitle,{children:i?`Edit Filter: ${(F=g.field)==null?void 0:F.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(S=g.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:o.conditions.map(y=>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:[y.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(y.value)?`${y.value.length} values`:String(y.value)})]},y.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(Ye.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:m,onChange:y=>x(y.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),m&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>x(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(oe.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:h.map(y=>e.jsxs("button",{type:"button",onClick:()=>v(y),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(n.IconForFieldType,{dataType:t.getDataType(y.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:y.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[y.entityName,".",y.name]})]})]},y.id))}),h.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),h.length===0&&!m&&r.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Gi,{field:g.field,selectedValues:g.selectedValues,onValuesChange:b,onBack:i?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(t.Button,{variant:"destructive",onClick:N,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:w,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:M,disabled:!g.field||g.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Gi({field:s,selectedValues:a,onValuesChange:r,onBack:o}){const[d,l]=C.useState(""),{values:i,isLoading:c,isFetching:u}=Hi({field:s,searchQuery:d,limit:500}),m=d?i.filter(p=>String(p.value).toLowerCase().includes(d.toLowerCase())):i,x=p=>{const h=a.includes(p);r(h?a.filter(v=>v!==p):[...a,p])},g=()=>{a.length===m.length&&m.length>0?r([]):r(m.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:o,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(Ye.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:d,onChange:p=>l(p.target.value),className:"pl-10"})]}),c||u?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(n.Checkbox,{checked:a.length===m.length&&m.length>0,onCheckedChange:g}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(n.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(_s,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qi({value:s,onChange:a,cardType:r,showTitle:o=!0,title:d="NUMBER FORMAT"}){const l=n.supportsLiveNumericPresentation(r),i=n.useResolvedValueFormatLocale(),c=n.useResolvedDefaultCurrency(),u=t.toTFormatOptions(t.fromSemanticFormat(s,{preserveOmittedProperties:!0}),{preserveOmittedProperties:!0})||{},m=x=>{a(t.fromTFormatOptions(x,{preserveOmittedProperties:!0}))};return e.jsx(Xt,{formatOptions:u,onFormatOptionsChange:m,showTitle:o,title:d,reportDefaults:l?{currency:c??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,locale:i??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale}:void 0})}function Wi(s,a){return s==="pivotBy"&&(a==="table"||a==="pivotTable")}const Ji=[];function Xi({field:s,zone:a,index:r,sortDirection:o,onSortDirectionChange:d,hasPivotColumns:l=!1,cardType:i}){var Ws,Js,Xs,Zs,en,tn,sn,nn,an,rn,on,ln,cn,dn,un,mn,xn,hn,pn,fn,gn,bn,jn,vn,yn,Cn,Nn,Sn,wn,Tn,En,In,Dn,kn;const{attributes:c,listeners:u,setNodeRef:m,transform:x,transition:g,isDragging:p}=n.useSortable({id:s.id}),h=t.useEditorStore(K=>K.card),v=t.useEditorStore(K=>K.frame),M=t.useDashboardStore(K=>K.isVisualEditing),N=t.useDashboardStore(K=>K.selectedSheetId),b=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),w=t.useDashboardStore(K=>K.actions.updateDashboardCalculatedFields),S=t.useDashboardStore(K=>{var be;return K.visualEditPendingDashboardCalculatedFields??((be=K.dashboard)==null?void 0:be.calculatedFields)})??Ji,{scopedFields:y,valuePickFilterableFields:k}=n.useFilterableFields(),{userContext:E}=n.useCurrentUserInfo(),{tokenProps:A}=n.useSemaphorContext(),T=(E==null?void 0:E.type)==="organization",I=n.useTimezone()??void 0,L=n.useResolvedTemporalStylePreferences()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES,{updateLabel:j,handleAggregationChange:P,handleDetailDateFormatChange:V,handleTemporalBucketFormatChange:f,handleGranularityChange:O,handleAliasTemplateChange:D,handlePivotMemberOrderChange:R,handleValueAliasesChange:B,handleMetricFormatChange:Y,removeField:_,handleMetricComparisonChange:z,handleMetricComparisonSpecChange:U,handleMetricComparisonPolarityChange:G,handleMetricWindowTransformChange:q,handleMetricWindowOrderByChange:Q,handleMetricWindowDirectionChange:H,handleMetricWindowPartitionToggle:se,handleMetricMovingAverageWindowSizeChange:ce,handleMetricMovingAverageMinPeriodsChange:ge,handleMetricPreviousPeriodDeltaModeChange:fe,handleMetricPercentOfTotalScopeChange:Te,handleMetricPercentOfTotalOutputChange:Ve,handleMetricTargetValueChange:Ue}=n.useFieldManagement(h),[Me,Ee]=C.useState(!1),[Fe,Oe]=C.useState(()=>{var K;return!!((K=s.parameters)!=null&&K.windowTransform)}),[Pe,le]=C.useState(!1),[De,ve]=C.useState(!1),[Ie,$]=C.useState(null),xe=C.useMemo(()=>{const K=de=>de!=null&&de.startsWith("card-source-")?de.replace("card-source-",""):de,be=K(s.id),X=y.find(de=>{if(s.qualifiedFieldName&&de.qualifiedFieldName&&de.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&de.qualifiedEntityName&&de.qualifiedEntityName===s.qualifiedEntityName&&de.name===s.name)return!0;const we=K(de.id);return!!(be&&we&&be===we)});return{dataType:(X==null?void 0:X.dataType)||s.dataType,resolvedFromScopedField:!!X}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,y]),Ce=n.getGranularityOptionsForFieldType(xe.dataType),ae=C.useMemo(()=>t.readTemporalBucketAuthoringState({fieldId:s.id,dataType:s.dataType,granularity:s.granularity,format:s.format,dateFormat:s.dateFormat,customFormat:s.customFormat,semanticTemporalPresentation:s.semanticTemporalPresentation}),[s.customFormat,s.dataType,s.dateFormat,s.format,s.id,s.granularity,s.semanticTemporalPresentation]),ie=a==="groupBy"?ae.ok&&Ce.includes(ae.granularity)?ae.granularity:void 0:Ce.includes(s.granularity)?s.granularity:"day",Re=ae.ok?ae.selection:{value:"auto",customPattern:"",format:It.AUTOMATIC_TEMPORAL_BUCKET_FORMAT},[Z,Ae]=C.useState(a==="groupBy"?Re.value:s.dateFormat||"YYYY-MM-DD"),[ze,We]=C.useState(a==="groupBy"?Re.customPattern:s.customFormat||""),_e=Z==="custom",[Xe,Ze]=C.useState(s.aliasTemplate||""),[et,re]=C.useState(s.valueAliases||{}),[J,pe]=C.useState((Ws=s.parameters)==null?void 0:Ws.filters),ue=K=>{var X;if(a==="groupBy"&&!ie)return;const be=ie??"day";if(K==="custom"){const de=a==="groupBy"?It.getTemporalBucketAuthoringOptions(be,Re.format,L).find(Qe=>Qe.value==="custom"):void 0,we=a==="groupBy"?ze||(((X=de==null?void 0:de.format)==null?void 0:X.presentation.mode)==="pattern"?de.format.presentation.pattern:""):ze;Ae(K),We(we),a==="groupBy"&&f(r,It.resolveTemporalBucketAuthoringFormat(be,K,we))}else Ae(K),a==="groupBy"?f(r,It.resolveTemporalBucketAuthoringFormat(be,K)):a==="detailColumns"&&V(r,K,"")},ne=K=>{if(a==="groupBy"&&!ie)return;const be=ie??"day";We(K),a==="groupBy"?f(r,It.resolveTemporalBucketAuthoringFormat(be,"custom",K)):a==="detailColumns"&&V(r,"custom",K)},me=K=>{if(a==="groupBy"){const be=It.reconcileTemporalBucketAuthoringFormat(Re.format,K),X=t.readTemporalBucketAuthoringSelection({fieldId:s.id,dataType:s.dataType,granularity:K,format:be,semanticTemporalPresentation:s.semanticTemporalPresentation});Ae(X.value),We(X.customPattern),O(r,K)}},qe=K=>{Ze(K),a==="metrics"&&D(r,K)},$e=K=>{a==="pivotBy"&&R(r,K)},Je=K=>{re(K),a==="metrics"&&B(r,K)},Ge=K=>{j(a,r,K)},st=n.getExpressionFieldKind(s),St=n.getFieldExpressionAnnotation(s),dt=n.isManagedCalculatedExpressionField(s),pt=s.role==="metric"&&dt,wt=dt&&(st==="user_calculated"||st==="inline_expression"&&s.fieldScope!=="domain"),lt=wt?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(v==null?void 0:v.calculatedFields)||[],dashboardFields:S}):void 0,Zt=wt&&(lt==null?void 0:lt.scope)==="sheet",Ot=wt&&(lt==null?void 0:lt.scope)==="dashboard",ft=st==="domain_calculated"||s.fieldScope==="domain",Bt=ft?n.resolveDomainCalculatedFieldForEdit(s,y):void 0,ut=ft?"domain":Zt?"sheet":Ot?"dashboard":"card",gt=ft?Bt||s:(Zt||Ot)&&(lt!=null&<.matchedField)?lt.matchedField:s,bt=K=>{var be;if(pe(K),a==="metrics"){const X={...s,parameters:{...s.parameters,filters:K}},de=[...((be=h.config)==null?void 0:be.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:de})}le(!1)},qs=()=>{_(a,r)},es={transform:n.CSS.Transform.toString(x),transition:g},ts=t.getDataType(xe.dataType||s.dataType),Vt=ts==="date",_t=i==="kpi",ms=a==="detailColumns",ss=(Js=h.config)==null?void 0:Js.metricColumns,jt=(Xs=h.config)==null?void 0:Xs.groupByColumns,Yt=t.useDashboardStore(K=>K.dashboard),ns=t.useDashboardStore(K=>{var be;return(be=K.dashboard)==null?void 0:be.filters}),Tt=t.useDashboardStore(K=>K.filterValues),zt=t.useDashboardStore(K=>K.dashboardInputValues),qt=t.useDashboardStore(K=>K.semanticExecutionPayload),W=a==="groupBy"&&ie?It.getTemporalBucketAuthoringOptions(ie,Re.format,L):a==="detailColumns"?Vi(ie??"day"):[],te=_e?"custom":!ie&&a==="groupBy"?void 0:W.some(K=>K.value===Z)?Z:((Zs=W[0])==null?void 0:Zs.value)??"YYYY-MM-DD",ee=!!i&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(i),Ne=!!i&&t.COMPARISON_TARGET_SUPPORTED_CHART_TYPES.includes(i),ye=C.useMemo(()=>jt==null?void 0:jt.find(K=>t.getDataType(K.dataType||"")==="date"),[jt]),je=C.useMemo(()=>t.resolveCardPrimaryDateField({card:h,cardConfig:h.config||{},semanticExecutionPayload:qt}),[h,qt]),Se=C.useMemo(()=>ye||(je?{...je,id:`semantic-primary:${je.entityId}:${je.name}`,label:je.name,role:"groupby",granularity:je.defaultGranularity||"day"}:void 0),[ye,je]),tt=C.useMemo(()=>{var de;if(!Se)return!1;const K=(de=h.config)==null?void 0:de.filters;if(!K)return!1;const be=we=>{const Qe=we.field;return Qe?Se.id&&Qe.id===Se.id||Se.qualifiedFieldName&&Qe.qualifiedFieldName===Se.qualifiedFieldName?!0:Qe.name===Se.name:!1},X=we=>we.conditions.some(He=>t.getDataType(He.field.dataType||"")==="date"&&be(He))?!0:we.groups.some(He=>X(He));return X(K)},[(en=h.config)==null?void 0:en.filters,Se]),mt=C.useMemo(()=>Ba(ns||[],Se,Tt)||Bi({dashboard:Yt,dateGroupByField:Se,dashboardInputValues:zt,sheetId:N,card:h,timezone:I}),[h,Yt,ns,Tt,zt,Se,N,I]),Et=tt||mt,ke=s,Le=((tn=ke.comparison)==null?void 0:tn.mode)==="explicit"?ke.comparison.spec:void 0,vt=((nn=(sn=ke.parameters)==null?void 0:sn.windowTransform)==null?void 0:nn.function)||"none",rt=n.isMetricTransformEnabled(ke),ot=rt?vt:null,xs=n.supportsMetricTransformForMetric({cardType:i||"table",cardConfig:h.config||{},metric:ke,transformMode:ot||"running_total"}),$t=((an=ke.comparison)==null?void 0:an.mode)==="explicit",$s=n.getRunningTotalOrderByCandidates(jt||[]),Mt=((ln=(on=(rn=ke.parameters)==null?void 0:rn.windowTransform)==null?void 0:on.orderBy)==null?void 0:ln.fieldId)||"",Ya=((un=(dn=(cn=ke.parameters)==null?void 0:cn.windowTransform)==null?void 0:dn.orderBy)==null?void 0:un.direction)||"asc",Ks=$s.find(K=>K.id===Mt),hs=ot==="running_total"||ot==="moving_average"||ot==="previous_period_delta",za=rt&&hs&&!!Ks&&t.getDataType(Ks.dataType||"")!=="date",qa=n.getDefaultRunningTotalPartitionByFieldIds({cardType:i||"table",cardConfig:h.config||{},orderByFieldId:Mt||void 0}),$a=new Set(((xn=(mn=ke.parameters)==null?void 0:mn.windowTransform)==null?void 0:xn.partitionByFieldIds)||qa),Ka=i==="pivotTable"||n.isSubtotalEnabledAggregateTable(i||"table",h.config||{}),Us=[...(jt||[]).filter(K=>K.id&&(!hs||K.id!==Mt)),...Ka?(((hn=h.config)==null?void 0:hn.pivotByColumns)||[]).filter(K=>K.id):[]],Hs=((gn=(fn=(pn=ke.parameters)==null?void 0:pn.windowTransform)==null?void 0:fn.movingAverage)==null?void 0:gn.windowSize)||7,Ua=((vn=(jn=(bn=ke.parameters)==null?void 0:bn.windowTransform)==null?void 0:jn.movingAverage)==null?void 0:vn.minPeriods)||1,Ha=((Nn=(Cn=(yn=ke.parameters)==null?void 0:yn.windowTransform)==null?void 0:Cn.previousPeriodDelta)==null?void 0:Nn.mode)||"absolute",Gs=((Tn=(wn=(Sn=ke.parameters)==null?void 0:Sn.windowTransform)==null?void 0:wn.percentOfTotal)==null?void 0:Tn.scope)||"grand_total",Ga=((Dn=(In=(En=ke.parameters)==null?void 0:En.windowTransform)==null?void 0:In.percentOfTotal)==null?void 0:Dn.output)||"percent",Qa=C.useMemo(()=>(ss||[]).some(()=>!1),[ss]);C.useEffect(()=>{rt&&Oe(!0)},[rt]);const Wa=a!=="pivotBy"&&a!=="sortBy",Ja=Wi(a,i),Xa=s.memberOrder??"auto",Za=Vt&&a==="groupBy"&&(!_t||Qa),er=!_t&&Vt&&(a==="groupBy"||ms),tr=a==="metrics",as=ee&&!h.sql&&!h.python&&a==="metrics",sr=()=>{const K=s,be=a==="metrics"&&pt;return e.jsxs("div",{className:"space-y-1",children:[!be&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:X=>{X.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}`}),be&&K.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(K.calculatedFormula),onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",n.formatDisplayFormula(K.calculatedFormula)]})]})},nr=()=>Wa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(ct,{value:s.label??"",onSave:Ge,placeholder:"Display label...",type:"text"})]}):null,ar=()=>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:o||"asc",onValueChange:K=>d(K),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"})]})]})]}),rr=()=>Ja?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot column order"}),e.jsxs(t.Select,{value:Xa,onValueChange:K=>$e(K),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:"auto",children:"Auto"}),e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}):null,Qs=()=>Za?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:ie,onValueChange:me,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:Ce.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K,children:t.toTitleCase(K)},K))})]})]}):null,or=()=>er?e.jsxs(e.Fragment,{children:[Qs(),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:te,onValueChange:ue,disabled:a==="groupBy"&&!ie,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:W.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),_e&&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:ze,onChange:K=>{K.stopPropagation(),ne(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,lr=()=>{var be;if(!tr)return null;const K=pt;return e.jsxs(e.Fragment,{children:[K&&T&&!ft&&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:()=>ve(!0),children:[e.jsx(n.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:X=>{P(r,X)},disabled:K,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(Qi,{value:ke.format,onChange:X=>Y(r,X),cardType:i,showTitle:!1})]}),e.jsx(n.Collapsible,{open:Fe,onOpenChange:Oe,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(n.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:[!Fe&&e.jsx("span",{className:"mr-2",children:rt?t.toTitleCase(vt.replace(/_/g," ")):"None"}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Fe?"rotate-180":"")})]})]})}),e.jsxs(n.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:rt?vt:"none",onValueChange:X=>q(r,X),disabled:!xs.supported&&!rt,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:$t,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:$t,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:$t,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:$t,children:"Percent of Total"})]})]}),!xs.supported&&!rt&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xs.reason}),$t&&!rt&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),rt&&e.jsxs(e.Fragment,{children:[hs&&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:Mt,onValueChange:X=>Q(r,X),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:$s.filter(X=>!!X.id).map(X=>e.jsx(t.SelectItem,{value:X.id,className:"text-xs",children:X.label||X.name},X.id))})]}),!Mt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),za&&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:Ya,onValueChange:X=>H(r,X),disabled:!Mt,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"})]})]})]})]}),ot==="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:Hs,onChange:X=>ce(r,Number(X.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:Hs,className:"h-8 text-xs",value:Ua,onChange:X=>ge(r,Number(X.target.value))})]}),ot==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:X=>fe(r,X),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"})]})]})]}),ot==="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:Gs,onValueChange:X=>Te(r,X),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:Ga,onValueChange:X=>Ve(r,X),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"})]})]})]})]}),(ot==="running_total"||ot==="moving_average"||ot==="previous_period_delta"||ot==="percent_of_total"&&Gs==="partition_total")&&Us.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:Us.map(X=>{const de=!!X.id&&$a.has(X.id);return e.jsxs("button",{type:"button",onClick:()=>X.id&&se(r,X.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:X.label||X.name}),de?e.jsx(t.Check,{className:"h-3 w-3"}):null]},X.id)})})]})]})]})]})}),as&&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:ke.comparison?ke.comparison.mode==="off"?"off":ke.comparison.spec.kind:"inherit",disabled:rt,onValueChange:X=>z(r,X),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:"inherit",children:"Inherit dashboard comparison (default)"}),e.jsx(t.SelectItem,{value:"off",children:"Off"}),(()=>{const X=!Se||!Et,de=Se?Et?void 0:"Add a date filter to enable":"Configure a semantic primary date or add a date axis",we=(Qe,He)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Qe,disabled:X,title:de,children:He})}),X&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[we("previous_period","Previous Period"),we("previous_year","Previous Year")]})})(),Ne&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]}),!ke.comparison&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Dashboard comparison is not available yet. This metric will follow it when a viewer sets it."})]}),as&&Le&&(Le.kind==="previous_period"||Le.kind==="previous_year")&&e.jsxs("div",{className:"space-y-2 rounded border border-border/60 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:Le.kind==="previous_year"?"Years back":"Periods back"}),e.jsx(t.Input,{type:"number",min:1,step:1,value:Le.kind==="previous_year"?Le.offsetYears||1:Le.offsetPeriods||1,onChange:X=>{const de=Number(X.target.value);!Number.isSafeInteger(de)||de<=0||(Le.kind==="previous_year"?U(r,{...Le,offsetYears:de===1?void 0:de}):U(r,{...Le,offsetPeriods:de===1?void 0:de}))},className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Alignment"}),e.jsxs(t.Select,{value:Le.alignment||"calendar",onValueChange:X=>U(r,{...Le,alignment:X==="calendar"?void 0:X}),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,{value:"calendar",children:"Calendar"}),e.jsx(t.SelectItem,{value:"weekday",children:"Match weekdays"})]})]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"To date"}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Match the elapsed portion of an incomplete current window."})]}),e.jsx(t.Switch,{size:"xs",checked:Le.toDate===!0,onCheckedChange:X=>U(r,{...Le,toDate:X?!0:void 0})})]}),e.jsxs("p",{className:"text-[11px] leading-4 text-muted-foreground",children:["Anchored to"," ",e.jsx("span",{className:"text-foreground",children:(Se==null?void 0:Se.label)||(Se==null?void 0:Se.name)}),". The resolved comparison dates appear after the card runs."]})]}),as&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Favorable direction"}),e.jsxs(t.Select,{value:t.getMetricComparisonPolarity(ke),disabled:!!ke.semanticComparisonPolarity,onValueChange:X=>G(r,X),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,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),ke.semanticComparisonPolarity&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Governed by this metric's semantic definition."})]}),as&&((be=ke.comparison)==null?void 0:be.mode)==="explicit"&&ke.comparison.spec.kind==="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:ke.comparison.spec.targetValue!==void 0&&ke.comparison.spec.targetValue!==null?String(ke.comparison.spec.targetValue):"",onChange:X=>{const de=X.target.value;if(de===""){Ue(r,void 0);return}const we=Number(de);Ue(r,Number.isFinite(we)?we: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"}),(J==null?void 0:J.conditions)&&J.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:J.conditions.map(X=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{$(X),le(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.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(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.value.length>1&&e.jsx(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 (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((de,we)=>e.jsx("div",{children:String(de)},we))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var Qe;de.stopPropagation();const we=J.conditions.filter(He=>He.id!==X.id);if(we.length>0){const He={...J,conditions:we};bt(He)}else if(pe(void 0),a==="metrics"){const He={...s,parameters:{...s.parameters,filters:void 0}},nt=[...((Qe=h.config)==null?void 0:Qe.metricColumns)||[]];nt[r]=He,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:nt})}},children:e.jsx(oe.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{$(null),le(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Ui,{column:s}),l&&e.jsxs(e.Fragment,{children:[e.jsx(_i,{aliasTemplate:Xe,onAliasTemplateChange:qe}),e.jsx(Yi,{valueAliases:et,onValueAliasesChange:Je})]})]})};J!=null&&J.conditions&&J.conditions.length>0;const ir=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{modal:!0,open:Me,onOpenChange:Ee,children:[e.jsxs("div",{ref:m,style:es,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",Me?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",p&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...c,...u,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${n.getMetricDisplayLabel(s)}`,onClick:K=>{K.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:ts,calculated:!!St}),e.jsx(_s,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((kn=J==null?void 0:J.conditions)==null?void 0:kn.length)&&!Me&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(n.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:J.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:J.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":o==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:K=>{K.stopPropagation(),d(o==="asc"?"desc":"asc")},children:o==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),ir&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:K=>K.stopPropagation(),children:e.jsx(n.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:K=>{K.stopPropagation(),qs()},children:e.jsx(oe.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[sr(),ar(),rr(),nr(),i==="kpi"&&Qs(),or(),lr()]})})]}),Pe&&e.jsx(Va,{open:Pe,onOpenChange:K=>{le(K),K||$(null)},availableFields:k,existingFilters:J,editingCondition:Ie,onSave:K=>{var be;if(K)bt(K);else if(pe(void 0),a==="metrics"){const X={...s,parameters:{...s.parameters,filters:void 0}},de=[...((be=h.config)==null?void 0:be.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:de})}$(null)}}),De&&a==="metrics"&&pt&&e.jsx(n.CalculatedFieldEditor,{open:De,onOpenChange:ve,availableFields:y,existingField:gt,existingFieldScope:ut,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var At,xt;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=((At=be.config)==null?void 0:At.metricColumns)||[],Qe=((xt=be.config)==null?void 0:xt.sortByColumns)||[],He=ut==="dashboard"?S:X.calculatedFields||[],{nextActiveFields:nt,nextSortByFields:it,nextStoredFields:ht,nextSharedFields:yt}=n.saveCalculatedFieldToCardScope({activeFields:we,sortByFields:Qe,storedFields:be.calculatedFields||[],sharedFields:He,updatedField:K,editingField:gt,previousScope:ut});(nt||it)&&de.updateCardConfig(h.id,{...nt?{metricColumns:nt}:{},...it?{sortByColumns:it}:{}}),de.updateCard(h.id,{calculatedFields:ht}),ut==="dashboard"&&yt!==He?w(yt):yt!==He&&n.commitSharedCalculatedFields({nextSharedFields:yt,currentSharedFields:He,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b})},onSaveToSheet:K=>{var Kt,Ut;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=s,Qe=((Kt=be.config)==null?void 0:Kt.metricColumns)||[],He=((Ut=be.config)==null?void 0:Ut.sortByColumns)||[],nt=X.calculatedFields||[],{nextActiveFields:it,nextSortByFields:ht,nextStoredFields:yt,nextSheetFields:At,nextDashboardFields:xt}=n.saveCalculatedFieldToSheetScope({activeFields:Qe,sortByFields:He,storedFields:be.calculatedFields||[],sheetFields:nt,dashboardFields:S,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:gt,previousScope:ut});n.commitSharedCalculatedFields({nextSharedFields:At,currentSharedFields:nt,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),xt&&xt!==S&&w(xt),(it||ht)&&de.updateCardConfig(h.id,{...it?{metricColumns:it}:{},...ht?{sortByColumns:ht}:{}}),de.updateCard(h.id,{calculatedFields:yt})},onSaveToDashboard:K=>{var Kt,Ut;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=s,Qe=((Kt=be.config)==null?void 0:Kt.metricColumns)||[],He=((Ut=be.config)==null?void 0:Ut.sortByColumns)||[],nt=X.calculatedFields||[],{nextActiveFields:it,nextSortByFields:ht,nextStoredFields:yt,nextSharedFields:At,nextSheetFields:xt}=n.saveCalculatedFieldToSharedScope({activeFields:Qe,sortByFields:He,storedFields:be.calculatedFields||[],sharedFields:S,sheetFields:nt,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:gt,previousScope:ut});w(At),xt&&xt!==nt&&n.commitSharedCalculatedFields({nextSharedFields:xt,currentSharedFields:nt,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),(it||ht)&&de.updateCardConfig(h.id,{...it?{metricColumns:it}:{},...ht?{sortByColumns:ht}:{}}),de.updateCard(h.id,{calculatedFields:yt})},cardId:h.id})]})}function Zi({concept:s}){const{title:a,description:r}=ec[s];return e.jsxs(n.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(n.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(n.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-control border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(tc,{highlight:s})]})]})}const ec={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function tc({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",o=s==="metrics",d="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-control border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(l=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&d),children:l},l))]})}),e.jsx("tbody",{children:aa.map((l,i)=>e.jsxs("tr",{className:t.cn(i!==aa.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",r&&d),children:l.label}),l.values.map((c,u)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&d),children:c},u))]},l.label))})]})})}const aa=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],sc={groupBy:n.Rows3,pivotBy:As,metrics:kr,detailColumns:t.Table2,sortBy:la};function Gt({zone:s,fields:a,label:r,placeholder:o,shouldShow:d,hasPivotColumns:l=!1,activeField:i=null}){const{isOver:c,setNodeRef:u}=n.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),x=t.useEditorStore(b=>b.card),g=t.useEditorStore(b=>b.card.type),p=a.length>0,h=C.useMemo(()=>!i||!c?!0:n.validateFieldForChartType(i,s,g).isValid,[i,c,s,g]),v=(b,w)=>{var S;!((S=x.config)!=null&&S.sortByColumns)||x.config.sortByColumns.findIndex(y=>y.id===b)===-1||m(x.id,b,{direction:w})};if(s==="sortBy"&&d===!1)return null;const M=s!=="sortBy"&&g!=="kpi",N=sc[s]||n.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r}),e.jsx("div",{ref:u,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":c&&h,"border border-destructive/40 bg-destructive/5":c&&!h,"border border-dashed border-border/50 bg-background":!c&&!p}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(N,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:o}),M&&e.jsx(Zi,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(b=>b.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((b,w)=>{const S=b.direction;return e.jsx(Xi,{field:b,zone:s,index:w,sortDirection:S,onSortDirectionChange:y=>v(b.id,y),hasPivotColumns:l,cardType:g},b.id)})})})})]})}const nc=[];function ac({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:o,detailFields:d,activeField:l}){var G,q,Q;const[i,c]=C.useState(!1);t.useEditorStore(H=>{var se;return!!((se=H.card.customCardPreferences)!=null&&se.url)});const u=t.useEditorStore(H=>H.card),m=t.useEditorStore(H=>H.frame),x=he.findCustomVisualConfigCard(m,u),{manifest:g}=n.useCustomVisual(((G=x==null?void 0:x.customCardPreferences)==null?void 0:G.url)||""),p=(q=g==null?void 0:g.visuals)==null?void 0:q.find(H=>{var se;return H.name===((se=x==null?void 0:x.customCardPreferences)==null?void 0:se.componentName)}),h=he.resolveMultiInputType(x,p)==="multiple";h&&((Q=x==null?void 0:x.customCardPreferences)!=null&&Q.url);const v=he.getConfigSlotExpectedType(p==null?void 0:p.slots),M=t.useEditorStore(H=>H.actions.updateCardConfig),N=t.useEditorStore(H=>H.actions.updateCard),b=t.useEditorStore(H=>H.actions.updateFrame),w=t.useDashboardStore(H=>H.isVisualEditing),F=t.useDashboardStore(H=>H.selectedSheetId),S=t.useDashboardStore(H=>H.actions.updateSheetCalculatedFields),y=t.useDashboardStore(H=>H.actions.updateDashboardCalculatedFields),E=t.useDashboardStore(H=>{var se;return H.visualEditPendingDashboardCalculatedFields??((se=H.dashboard)==null?void 0:se.calculatedFields)})??nc,{scopedFields:A}=n.useScopedFields(),{userContext:T}=n.useCurrentUserInfo(),I=h&&(x==null?void 0:x.id)===u.id&&v?v:u==null?void 0:u.type,L=I==="detailTable",j=s.length>0||r.length>0||d.length>0,P=!L&&(I!=="kpi"||r.length<=2),V=!L,f=!L&&I!=="kpi",O=I!=="kpi"&&j,D=L,R="Drop sort fields here",B=(T==null?void 0:T.type)==="organization",Y=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),_=f&&!Y,z=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},U=()=>I==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),j&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{M(u.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[P&&e.jsx(Gt,{zone:"groupBy",fields:s,label:z().label,placeholder:z().placeholder,activeField:l}),_&&e.jsx(Gt,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:l}),V&&e.jsx(Gt,{zone:"metrics",fields:r,label:U().label,placeholder:U().placeholder,hasPivotColumns:a.length>0,activeField:l}),D&&e.jsx(Gt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&B&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),O&&e.jsx(Gt,{zone:"sortBy",fields:o,label:"Sort By",placeholder:R,activeField:l})]}),e.jsx(n.CalculatedFieldEditor,{open:i,onOpenChange:c,availableFields:A,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:H=>{if(H.role!=="metric")return;const{nextStoredFields:se}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:m.calculatedFields||[],updatedField:H,previousScope:"card"});N(u.id,{calculatedFields:se})},onSaveToSheet:H=>{if(H.role!=="metric")return;const se=m.calculatedFields||[],{nextSheetFields:ce}=n.saveCalculatedFieldToSheetScope({activeFields:r,storedFields:u.calculatedFields||[],sheetFields:se,updatedField:H,previousScope:"sheet"});n.commitSharedCalculatedFields({nextSharedFields:ce,currentSharedFields:se,isVisualEditing:w,selectedSheetId:F,updateFrame:b,updateSheetCalculatedFields:S})},onSaveToDashboard:H=>{if(H.role!=="metric")return;const{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:E,updatedField:H,previousScope:"dashboard"});y(se)},cardId:u.id})]})}function rc(){var w,F,S;const s=t.useEditorStore(y=>{var k;return(k=y.card)==null?void 0:k.type}),a=s==="kpi",[r,o]=C.useState(a),[d,l]=C.useState(!1),i=t.useEditorStore(y=>{var k;return!!((k=y.card.customCardPreferences)!=null&&k.url)}),c=t.useEditorStore(y=>y.card),u=t.useEditorStore(y=>y.frame),m=he.findCustomVisualConfigCard(u,c),{manifest:x}=n.useCustomVisual(((w=m==null?void 0:m.customCardPreferences)==null?void 0:w.url)||""),g=(F=x==null?void 0:x.visuals)==null?void 0:F.find(y=>{var k;return y.name===((k=m==null?void 0:m.customCardPreferences)==null?void 0:k.componentName)}),h=he.resolveMultiInputType(m,g)==="multiple"&&!!((S=m==null?void 0:m.customCardPreferences)!=null&&S.url),v=!i||h,M=i||h,N=a?"KPI Settings":"Chart Settings",b=v&&!t.isTableChartType(s);return C.useEffect(()=>{a&&o(!0)},[a]),!b&&!M?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[b&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",a?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60 [&_h3]:sticky [&_h3]:top-0 [&_h3]:z-10 [&_h3]:bg-background",children:e.jsx(Oa,{mode:"config"})})}),b&&e.jsxs("button",{type:"button",onClick:()=>o(y=>!y),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:N})]}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),M&&d&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Ma,{})}),M&&e.jsxs("button",{type:"button",onClick:()=>l(y=>!y),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",b&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ia,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",d&&"rotate-180"),strokeWidth:1.75})]})]})}function oc({onEditJoins:s}){const a=t.useEditorStore(u=>u.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,d=(o==null?void 0:o.joins)||[];if(d.length===0)return null;const l=u=>!u||u.length===0?"No conditions":u.map(m=>{var h,v,M,N;const x=`${(h=m.source)==null?void 0:h.entityName}.${(v=m.source)==null?void 0:v.name}`,g=`${(M=m.target)==null?void 0:M.entityName}.${(N=m.target)==null?void 0:N.name}`,p=m.operator||"=";return`${x} ${p} ${g}`}).join(" AND "),i=u=>!u.joinKeyGroups||u.joinKeyGroups.length===0?"No conditions defined":u.joinKeyGroups.length===1?l(u.joinKeyGroups[0].keys):u.joinKeyGroups.map((m,x)=>({id:x,operator:m.operator,condition:l(m.keys)})),c=e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"shrink-0 cursor-help rounded-control px-1 font-mono text-[10px] tabular-nums text-muted-foreground/70 transition-colors hover:bg-muted hover:text-foreground","aria-label":`${d.length} resolved ${d.length===1?"join":"joins"}`,children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md border border-border bg-popover p-2 text-popover-foreground shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsx("div",{className:"space-y-2",children:d.map((u,m)=>{const x=i(u),g=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2 text-foreground",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:u.source.name}),e.jsx(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:u.target.name})]}),e.jsx("span",{className:"shrink-0 rounded-[3px] border border-border px-1 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:u.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:g?x.map(p=>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:p.condition}),p.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",p.operator,")"]})]},p.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:x})})})]},u.id||m)})})})]})});return e.jsxs("div",{className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:"Resolved joins"}),c,s&&e.jsx("button",{type:"button",onClick:s,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:border-ring","aria-label":"Edit resolved joins",children:e.jsx(n.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function lc({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:o,groupByFields:d,pivotByFields:l,metricsFields:i,sortByFields:c,detailFields:u,activeField:m}){var E,A;const[x,g]=C.useState(!1),p=t.useEditorStore(T=>T.card),h=t.useEditorStore(T=>T.editorContext),v=t.useEditorStore(T=>T.actions.updateCardConfig),M=(h==null?void 0:h.type)==="documentSection",{autoJoinMetadata:N}=n.useEditorCardQuery(p),b=((E=p==null?void 0:p.config)==null?void 0:E.joinPlan)||(N!=null&&N.autoResolved?N.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),w=((A=p==null?void 0:p.dataSource)==null?void 0:A.selectedEntities)||[],F=T=>{v(p.id,{...p==null?void 0:p.config,joinPlan:T}),g(!1)},S=()=>{v(p.id,{...p==null?void 0:p.config,joinPlan:void 0}),g(!1)},y=()=>{g(!1)},k=()=>{g(!0)};return r?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!M&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Vo,{selectedChart:s,onChartChange:a})}),o&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:o,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx(oc,{onEditJoins:k})}),e.jsx(ac,{groupByFields:d,pivotByFields:l,metricsFields:i,sortByFields:c,detailFields:u,activeField:m})]}),e.jsx(rc,{}),e.jsx(ua,{open:x,onOpenChange:g,joinPlan:b,availableDataSources:w,onSave:F,onCancel:y,onRemove:S,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:o&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:o,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(Ye.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function ic({initialFilters:s,availableFields:a}={}){const[r,o]=C.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:d,isLoading:l}=n.useFilterableFields(),i=a||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=S=>{const y=k=>{if(k.id===S){const E=i[0]||c,A=t.getDataType(E.dataType)==="date";return{...k,conditions:[...k.conditions,{id:`condition-${Date.now()}`,field:E,operator:A?"between":"=",value:A?[]:""}]}}return{...k,groups:k.groups.map(y)}};o(y(r))},m=S=>{const y=k=>{if(k.id===S){const E=i[0]||c,A=t.getDataType(E.dataType)==="date";return{...k,groups:[...k.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:A?"between":"=",value:A?[]:""}],groups:[]}]}}return{...k,groups:k.groups.map(y)}};o(y(r))},x=(S,y)=>{const k=E=>E.id===S?{...E,conditions:E.conditions.filter(A=>A.id!==y)}:{...E,groups:E.groups.map(k)};o(k(r))},g=(S,y)=>{const k=E=>E.id===S?{...E,groups:E.groups.filter(A=>A.id!==y)}:{...E,groups:E.groups.map(k)};o(k(r))},p=(S,y,k,E)=>{if(k==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const A=T=>T.id===S?{...T,conditions:T.conditions.map(I=>I.id===y?{...I,[k]:E}:I)}:{...T,groups:T.groups.map(A)};o(A(r))},h=(S,y,k)=>{const E=A=>A.id===S?{...A,conditions:A.conditions.map(T=>T.id===y?{...T,...k}:T)}:{...A,groups:A.groups.map(E)};o(E(r))},v=(S,y)=>{const k=E=>E.id===S?{...E,logicalOperator:y}:{...E,groups:E.groups.map(k)};o(k(r))},M=(S,y)=>{const k=E=>E.id===S?{...E,negate:y}:{...E,groups:E.groups.map(k)};o(k(r))},N=(S,y,k)=>{const E=A=>A.id===S?{...A,conditions:n.arrayMove(A.conditions,y,k)}:{...A,groups:A.groups.map(E)};o(E(r))},b=(S,y,k)=>{const E=A=>A.id===S?{...A,groups:n.arrayMove(A.groups,y,k)}:{...A,groups:A.groups.map(E)};o(E(r))},w=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const y=E=>{let A="";typeof E.field=="object"?A=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:A=String(E.field);const T=E.operator;let I=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(I)&&I.length===2){const L=I[0]?`'${I[0]}'`:"NULL",j=I[1]?`'${I[1]}'`:"NULL";return`${A} BETWEEN ${L} AND ${j}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(I)){const L=I.map(j=>j?`'${j}'`:"NULL").join(", ");return`${A} ${T} (${L})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(E.operator)){let L=[];Array.isArray(I)?L=I.map(j=>typeof j=="string"?`'${j}'`:String(j)):typeof I=="string"?L=I.split(",").map(j=>{const P=j.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof I=="number"&&(L=[String(I)]),I=`(${L.join(", ")})`}switch(T){case"contains":return typeof I=="string"?`${A} LIKE '%${I.replace(/'/g,"")}'`:`${A} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${A} LIKE '${I.replace(/'/g,"")}%'`:`${A} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${A} LIKE '%${I.replace(/'/g,"")}'`:`${A} LIKE '%${String(I)}'`;case"isNull":return`${A} IS NULL`;case"isNotNull":return`${A} IS NOT NULL`;default:return`${A} ${T} ${I}`}},k=E=>{const A=E.conditions.map(y),T=E.groups.map(P=>k(P)),I=[...A,...T].filter(Boolean);if(I.length===0)return"";const L=I.join(` ${E.logicalOperator} `),j=I.length>1?`(${L})`:L;return E.negate?`NOT ${j}`:j};return k(S)},F=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:h,updateGroupOperator:v,updateGroupNegate:M,reorderConditions:N,reorderGroups:b,generateSQLPreview:w,hasAnyFilters:F}}function cc({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 dc=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function uc({value:s,onValueChange:a,availableFields:r,placeholder:o="Select field",className:d="w-64"}){const[l,i]=C.useState(!1),c=C.useMemo(()=>{const u={};return r.forEach(m=>{const x=dc(m);u[x]||(u[x]={}),u[x][m.entityId]||(u[x][m.entityId]=[]),u[x][m.entityId].push(m)}),u},[r]);return e.jsxs(t.Popover,{modal:!0,open:l,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:t.cn("justify-between",!s&&"text-muted-foreground",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(cc,{children:[s.entityName,".",s.name]})}):o,e.jsx(n.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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(n.CommandEmpty,{children:"No fields found."}),e.jsx(n.CommandList,{className:"max-h-80",children:Object.entries(c).map(([u,m])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(m).map(([x,g])=>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:[n.getEntityIcon(g[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:g[0].entityName})]}),g.map((p,h)=>e.jsxs(n.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!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)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+h))]},`${u}-${x}`))},u))})]})})]})}function Ys(s){var N;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:o}=n.useSemaphorContext(),d=t.useDashboardStore(b=>{var w;return((w=b.reportContext)==null?void 0:w.calendar)??null}),l=t.useEditorStore(b=>b.card.config),i=l==null?void 0:l.joinPlan,c={...s,alias:s.name,label:"value",role:"groupby"},u={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},m={...c,role:"sortby",direction:"asc"},x={joinPlan:i,groupByColumns:[c],metricColumns:[u],sortByColumns:[m]},g=((N=a.dataSource)==null?void 0:N.connectionId)||a.connectionId,{data:p,isPending:h,error:v}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName,d],queryFn:async()=>{try{return await t.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:g,cardConfig:x,cardDataSource:a.dataSource,calendarContext:d})}catch(b){console.log(s),console.error("error",b)}},enabled:!!g&&!!d,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((p==null?void 0:p.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:h,error:v}}function mc({field:s,selected:a,onChange:r,placeholder:o="Select items...",className:d}){const[l,i]=hr.useState(!1),{filterValues:c}=Ys(s),u=x=>{r(a.filter(g=>g!==x))},m=x=>{a.includes(x)?r(a.filter(g=>g!==x)):r([...a,x])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:l,onOpenChange:i,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const g=c.find(p=>p.value===x);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[g==null?void 0:g.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&u(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),u(x)},children:e.jsx(oe.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:o})}),e.jsx(oe.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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No results found."}),e.jsx(n.CommandGroup,{children:c.map((x,g)=>e.jsxs(n.CommandItem,{onSelect:()=>m(x.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+g))})]})]})})]})})}function xc({field:s,value:a,onChange:r,placeholder:o="Select value...",className:d}){const{filterValues:l,isPending:i,error:c}=Ys(s);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:o,children:a})}),e.jsx(t.SelectContent,{children:l.map((u,m)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+m))})]})}function hc({value:s,operator:a,onChange:r,className:o}){const d=n.useTimezone(),l=a==="between"||a==="not between",i=C.useMemo(()=>{if(!(!s||!l)&&Array.isArray(s)&&s.length===2){const g=s[0]?new Date(s[0]):void 0,p=s[1]?new Date(s[1]):void 0;if(g&&p)return{from:g,to:p}}},[s,l]),c=C.useMemo(()=>{if(!s||l)return;const g=Array.isArray(s)?s[0]:s;if(!g)return;const p=new Date(g);if(!isNaN(p.getTime()))return p},[s,l]),u=g=>a==="<="||a===">"?t.endOfDayInTimezone(g,d):t.startOfDayInTimezone(g,d),m=g=>{if(!g){r([]);return}if(g.from&&g.to){r([g.from.toISOString(),g.to.toISOString()]);return}r([])},x=g=>{if(!g){r("");return}const p=u(g);r(p.toISOString())};return e.jsx(n.DateRangePicker,{value:l?i:void 0,selectionMode:l?"range":"single",singleValue:l?void 0:c,onChange:m,onSingleChange:x,timezone:d,showRelativeTab:l,className:o,placeholder:"Select date..."})}const zs=["contains","startsWith","endsWith","like","not like"],pc=["=","!=",">",">=","<","<=",...zs,"in","not in","isNull","isNotNull"],fc=["=","!=",...zs,"in","not in","isNull","isNotNull"],gc=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],bc=["=","!=","isNull","isNotNull"],jc=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],vc={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",like:"Like","not like":"Not Like",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function ra(s){return vc[s]||t.titleCase(s)}function yc(s){switch(s){case"string":return fc;case"number":return gc;case"boolean":return bc;case"date":return jc;default:return pc}}function _a({condition:s,index:a,groupId:r,groupLogicalOperator:o,onUpdateCondition:d,onRemoveCondition:l,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:u}){const{attributes:m,listeners:x,setNodeRef:g,transform:p,transition:h,isDragging:v}=n.useSortable({id:s.id}),{isPending:M,error:N}=Ys(s.field),b={transform:n.CSS.Transform.toString(p),transition:h};return e.jsxs("div",{ref:g,style:b,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${v?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:o,onValueChange:w=>i(r,w),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(uc,{value:s.field,onValueChange:w=>{const F=w,S=t.getDataType(F.dataType)==="date";u(r,s.id,{field:F,value:"",operator:S?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:w=>{w==="in"||w==="not in"?u(r,s.id,{operator:w,value:[]}):w==="isNull"||w==="isNotNull"?u(r,s.id,{operator:w,value:null}):w==="between"||w==="not between"?u(r,s.id,{operator:w,value:[]}):u(r,s.id,{operator:w,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?ra(s.operator):""})}),e.jsx(t.SelectContent,{children:yc(t.getDataType(s.field.dataType)).map(w=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:w,children:ra(w)},w))})]}),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"?M?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..."]}):N?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(mc,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(w=>typeof w=="string")?s.value:[],onChange:w=>u(r,s.id,{value:w}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):zs.includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:w=>u(r,s.id,{value:w.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(xc,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:w=>u(r,s.id,{value:w}),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:w=>u(r,s.id,{value:w==="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(hc,{value:s.value,operator:s.operator,onChange:w=>u(r,s.id,{value:w}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:w=>d(r,s.id,"value",w.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:()=>l(r,s.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]})}function Cc({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:d,onRemoveGroup:l,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:u,onReorderConditions:m,onReorderGroups:x,onAddCondition:g,onAddGroup:p,availableFields:h,renderFilterGroup:v,updateConditionFields:M}){const{attributes:N,listeners:b,setNodeRef:w,transform:F,transition:S,isDragging:y}=n.useSortable({id:s.id}),k={transform:n.CSS.Transform.toString(F),transition:S},E=T=>{const{active:I,over:L}=T;if(L&&I.id!==L.id){const j=s.conditions.findIndex(V=>V.id===I.id),P=s.conditions.findIndex(V=>V.id===L.id);j!==-1&&P!==-1&&m(s.id,j,P)}},A=T=>{const{active:I,over:L}=T;if(L&&I.id!==L.id&&r){const j=s.groups.findIndex(V=>V.id===I.id),P=s.groups.findIndex(V=>V.id===L.id);j!==-1&&P!==-1&&x(r,j,P)}};return e.jsxs("div",{ref:w,style:k,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${y?"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",{...N,...b,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:T=>o(s.id,T),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:()=>r&&l(r,s.id),children:e.jsx(n.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:E,children:e.jsx(n.SortableContext,{items:s.conditions.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((T,I)=>e.jsx(_a,{condition:T,index:I,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:u,onUpdateGroupOperator:o,availableFields:h,updateConditionFields:M},T.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:A,children:e.jsx(n.SortableContext,{items:s.groups.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(T=>v(T,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:()=>g(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Nc({filters:s,availableFields:a,onSave:r,onClearAll:o,onCancel:d}){const{currentFilters:l,availableFields:i,isLoading:c,addCondition:u,addGroup:m,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:h,updateGroupOperator:v,updateGroupNegate:M,reorderConditions:N,reorderGroups:b,generateSQLPreview:w,hasAnyFilters:F,setCurrentFilters:S}=ic({initialFilters:s,availableFields:a}),y=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[k,E]=C.useState(!1),A=(L,j,P)=>{const V=f=>f.id===L?{...f,conditions:f.conditions.map(O=>O.id===j?{...O,field:P,dataType:P.dataType}:O)}:{...f,groups:f.groups.map(V)};S(V(l))},T=(L,j=0,P)=>j===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:y,collisionDetection:n.closestCenter,onDragEnd:V=>{const{active:f,over:O}=V;if(O&&f.id!==O.id){const D=L.conditions.findIndex(B=>B.id===f.id),R=L.conditions.findIndex(B=>B.id===O.id);D!==-1&&R!==-1&&N(L.id,D,R)}},children:e.jsx(n.SortableContext,{items:L.conditions.map(V=>V.id),strategy:n.verticalListSortingStrategy,children:L.conditions.map((V,f)=>e.jsx(_a,{condition:V,index:f,groupId:L.id,groupLogicalOperator:L.logicalOperator,onUpdateCondition:p,onUpdateField:A,onRemoveCondition:x,onUpdateGroupOperator:v,availableFields:i,updateConditionFields:h},V.id))})}),e.jsx(n.DndContext,{sensors:y,collisionDetection:n.closestCenter,onDragEnd:V=>{const{active:f,over:O}=V;if(O&&f.id!==O.id){const D=L.groups.findIndex(B=>B.id===f.id),R=L.groups.findIndex(B=>B.id===O.id);D!==-1&&R!==-1&&b(L.id,D,R)}},children:e.jsx(n.SortableContext,{items:L.groups.map(V=>V.id),strategy:n.verticalListSortingStrategy,children:L.groups.map(V=>T(V,j+1,L.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:()=>u(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),k&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},L.id):e.jsx(Cc,{group:L,depth:j,parentGroupId:P,onUpdateGroupOperator:v,onUpdateGroupNegate:M,onRemoveGroup:g,onUpdateCondition:p,onUpdateField:A,onRemoveCondition:x,onReorderConditions:N,onReorderGroups:b,onAddCondition:u,onAddGroup:m,availableFields:i,renderFilterGroup:T,updateConditionFields:h},L.id),I=n.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(n.Card,{children:e.jsx(n.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:k,onCheckedChange:L=>E(L)}),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)"})]})}),F&&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:w(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),I>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(F?l:null),children:"Apply Filters"})]})]})}function Sc({cardId:s,filters:a,onFiltersChange:r,onClearFilters:o,availableFields:d,isOpen:l,onOpenChange:i}){const c=m=>{r(s,m),i(!1)},u=()=>{o(s),i(!1)};return e.jsxs(n.Dialog,{modal:!1,open:l,onOpenChange:i,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(n.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.preventDefault()},children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Card Filters"}),e.jsx(n.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Nc,{filters:a,availableFields:d,onSave:c,onCancel:()=>i(!1),onClearAll:u})]})]})}function wc({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:o}){var w,F;const[d,l]=C.useState(null),i=t.useEditorStore(S=>S.card),c=t.useEditorStore(S=>S.actions.updateCardConfig),u=t.useEditorStore(S=>S.actions.setCardPreferences),m=(w=i==null?void 0:i.config)==null?void 0:w.joinPlan,x=C.useCallback(S=>S.entityName===mr.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),g=(F=i==null?void 0:i.dataSource)==null?void 0:F.semanticDomainId,{data:p}=n.useJoinabilityMap(g),h=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],v=C.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(y=>y.id===S)?"source":r("groupBy").find(y=>y.id===S)?"groupBy":r("metrics").find(y=>y.id===S)?"metrics":r("pivotBy").find(y=>y.id===S)?"pivotBy":r("sortBy").find(y=>y.id===S)?"sortBy":r("detailColumns").find(y=>y.id===S)?"detailColumns":null,[a,r]),M=C.useCallback(S=>{l(S.active.id)},[]),N=C.useCallback(S=>{var L;const{active:y,over:k}=S;if(!k||!s){l(null);return}const E=y.id,A=k.id,T=v(E),I=v(A)||A;if(I==="sortBy"){if(T==="source"){const j=a.find(V=>V.id===E);if(!j){l(null);return}if(!(r("groupBy").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName)||r("metrics").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName)||r("detailColumns").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName))){l(null);return}}else if(T==="pivotBy"){l(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"&&T!=="detailColumns"){l(null);return}}if(T==="source"&&I==="sortBy"){const j=[...a].find(O=>O.id===E);if(!j){l(null);return}const P=r("sortBy");if(n.fieldAlreadyExists(j,P)){l(null);return}const V=n.validateFieldForChartType(j,"sortBy",i.type);if(!V.isValid){n.ue.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3}),l(null);return}const f=n.getNewField(j,"sortBy",P);l(null),o("sortBy",[...P,f]);return}if(T==="source"&&I!=="source"&&I!=="sortBy"){const j=[...a].find(B=>B.id===E);if(!j){l(null);return}const P=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],V=P.filter(B=>!x(B));if(V.length>0){const B=V[0].qualifiedEntityName;if(!B){l(null);return}if(B!==j.qualifiedEntityName&&!x(j)&&j.qualifiedEntityName)if(g&&(p!=null&&p.joinabilityMap)){if(n.calculateFieldState(j,{joinabilityMap:p.joinabilityMap,selectedFields:P,baseEntityName:(L=m==null?void 0:m.baseEntity)==null?void 0:L.name,datasetAliases:p.datasets}).state==="unreachable"){n.showJoinRequiredNotification(),l(null);return}}else{if(!m){n.showJoinRequiredNotification(),l(null);return}if(!n.areEntitiesJoined(B,j.qualifiedEntityName,m)){n.showJoinRequiredNotification(),l(null);return}}}const f=r(I);if(n.fieldAlreadyExists(j,f)){l(null);return}const O=n.validateFieldForChartType(j,I,i.type);if(!O.isValid){n.ue.error("Invalid Field Type",{description:O.reason,position:"top-center",duration:3e3}),l(null);return}const D=n.getNewField(j,I,f),R=[...f,D];if(l(null),o(I,R),I==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,D,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,c,s,R)}return}if(T&&I&&T!=="source"&&I!=="source"&&T!==I){const j=r(T),P=r(I),V=j.find(B=>B.id===E);if(!V){l(null);return}const f=n.validateFieldForChartType(V,I,i.type);if(!f.isValid){n.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),l(null);return}const O=n.getNewField(V,I,P);if(l(null),I==="sortBy"){n.fieldAlreadyExists(V,P)||o(I,[...P,O]);return}const D=j.filter(B=>B.id!==E),R=[...P,O];if(o(T,D),o(I,R),I==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,O,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,c,s,R)}return}if(T&&I&&T===I&&T!=="source"){const j=r(T),P=j.findIndex(f=>f.id===E),V=j.findIndex(f=>f.id===A);if(P!==V){const f=n.arrayMove(j,P,V);o(T,f)}}l(null)},[s,a,r,o,v,m,g,p,x,i,c,u]),b=d?h.find(S=>S.id===d):null;return{activeId:d,activeField:b,handleDragStart:M,handleDragEnd:N}}function Tc({activeView:s,onViewChange:a,splitViewEnabled:r,hasQueryError:o=!1}){const d=t.useEditorStore(m=>m.card),{config:l}=C.useContext(n.SemaphorContext).tokenProps,i=(l==null?void 0:l.showInfoTab)!==!1,c=()=>r?!1:t.getVisualizationMode(d)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(d.type),u=[{id:"chart",label:"Chart"}];return c()&&u.push({id:"table",label:"Results"}),i&&u.push({id:"info",label:o?"Error":"Info",isError:o}),e.jsx(t.Tabs,{value:s,onValueChange:m=>a(m),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:u.map(m=>e.jsx(t.TabsTrigger,{value:m.id,className:t.cn("px-0 text-[13px]",m.isError&&"text-destructive hover:text-destructive focus-visible:text-destructive data-[state=active]:border-destructive data-[state=active]:text-destructive"),children:m.label},m.id))})})}const Ec=[{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 Ic(){var u,m;const s=t.useEditorStore(x=>x.card),{updateRowLimit:a}=t.useEditorActions(),[r,o]=C.useState(!1),[d,l]=C.useState(""),i=x=>{if(x==="custom"){o(!0);return}o(!1),a(s.id,parseInt(x))},c=x=>{const g=x.target.value;l(g),g&&!isNaN(parseInt(g))&&a(s.id,parseInt(g))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(u=s.config)==null?void 0:u.rowLimit)==null?void 0:m.toString())||"100",onValueChange:i,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(n.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:Ec.map(x=>e.jsx(t.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Dc({card:s,queryData:a,isLoading:r,isFetching:o,pagination:d,onPaginationChange:l,onSortChange:i,sortState:c,splitViewEnabled:u,isDynamicInspectorOpen:m,onDynamicInspectorOpenChange:x}){var v,M;const g=C.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),p=t.getVisualizationMode(s)==="dynamic",h=e.jsx(kt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ia,{fallbackPreview:e.jsx(kt,{}),records:g,title:s.title,isInspectorOpen:m,onInspectorOpenChange:x})});return p?u?e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:h}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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 px-4 py-4",children:[(r||o)&&(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(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,resultColumns:a==null?void 0:a.columns,columnKeyMap:a==null?void 0:a.columnKeyMap,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,comparisonMetadata:(v=a==null?void 0:a.metadata)==null?void 0:v.comparisonMetadata,paginationMetadata:d,onPaginationChange:l,isLoading:r||o,onSortChange:i,sortState:c})]})})]}):h:!u||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(kt,{}):e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(kt,{})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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:[(r||o)&&(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(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,resultColumns:a==null?void 0:a.columns,columnKeyMap:a==null?void 0:a.columnKeyMap,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,comparisonMetadata:(M=a==null?void 0:a.metadata)==null?void 0:M.comparisonMetadata,paginationMetadata:d,onPaginationChange:l,isLoading:r||o,onSortChange:i,sortState:c})]})})]})}function kc(s,a){const[r,o]=C.useState(()=>{const d=localStorage.getItem(s);return d?JSON.parse(d):a});return C.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const Mc="semaphor-split-view-enabled";function Ac(){return kc(Mc,!0)}function Lc({showInfoTab:s}){return e.jsx(n.VisualErrorState,{className:"min-h-[240px]",description:s?"See the Error tab for details and troubleshooting options.":"Contact your administrator for help resolving this issue."})}function Fc({card:s,effectiveCardType:a=s.type,queryResultColumns:r}){return t.supportsRegularTableSettings(a)?e.jsxs(n.Sheet,{modal:!1,children:[e.jsx(n.SheetTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"Table settings",className:"h-7 w-7 rounded-[5px] p-0",buttonProps:{type:"button","aria-label":"Table settings"},children:e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),e.jsxs(n.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(n.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(n.SheetDescription,{className:"sr-only",children:"Configure table presentation and conditional formatting."}),e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:"Table settings"}),e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Settings apply to this table and document exports that reuse it."})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(Pa,{cardType:a,queryResultColumns:r,focusSection:"style"})})]})]}):null}function Rc({className:s,visible:a}){const r=t.useDashboardStore(c=>c.selectedFrameId),o=n.useManagementStore(c=>c.selectedVisual),d=t.useEditorStore(c=>c.frame),i=!!!(d!=null&&d.visualId||o!=null&&o.id)&&!!r;return!a||i?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(Nt.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Pc({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:o,columns:d}){var Fe,Oe,Pe;const l=t.useEditorStore(le=>le.card),i=t.useEditorStore(le=>le.editorContext),c=t.useEditorStore(le=>le.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),u=t.useEditorStore(le=>le.actions.removeCardInlineFilterValue),m=t.useDashboardStore(le=>le.filterValues),x=t.useDashboardStore(le=>le.selectedSheetId),{updateCardConfig:g,setCard:p,updateCardInFrame:h,setShowAIDialog:v}=t.useEditorActions(),M=t.useEditorStore(le=>le.showAIDialog),N=t.useEditorStore(le=>le.isDevMode),b=t.useDashboardStore(le=>le.isVisualEditing),[w,F]=C.useState(!1),[S,y]=C.useState(!1),[k,E]=C.useState(!1),[A,T]=C.useState(null),{config:I}=C.useContext(n.SemaphorContext).tokenProps,L=(I==null?void 0:I.showInfoTab)!==!1,j=(I==null?void 0:I.showQueryDebugTools)!==!1,[P,V]=Ac();t.useEditorStore(le=>{var De;return!!((De=le.card.customCardPreferences)!=null&&De.url)});const O=t.getVisualizationMode(l)==="dynamic",D=(i==null?void 0:i.type)==="documentSection",R=n.useEffectiveEditorCardType(),{data:B,errorMessage:Y,isLoading:_,isFetching:z,errorSql:U,pagination:G,refetch:q,comparisonMetadata:Q,queryRequestPayload:H,resolvedPrimaryDateField:se}=n.useEditorCardQuery(o),ce=C.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),ge=C.useMemo(()=>!z&&ce.length>0?Object.keys(ce[0]):[],[z,ce]),[fe,Te]=C.useState(!1);C.useEffect(()=>{z||Te(!1)},[z]);const Ve=()=>{const le=!P;le&&s==="table"&&a("chart"),V(le)},Ue=(le,De)=>{const ve={...o,paginationConfig:{page:le+1,pageSize:De}};p(ve),h(ve)},Me=le=>{if(!l.config)return;const De=n.sortStateToSortByColumns(le,l.config.metricColumns,l.config.groupByColumns,l.config.detailColumns);g(l.id,{...l.config,sortByColumns:De})},Ee=C.useMemo(()=>{var le;return n.sortByColumnsToSortState((le=l.config)==null?void 0:le.sortByColumns)},[(Fe=l.config)==null?void 0:Fe.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":M&&b}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&M&&!D&&!O&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Bo,{variant:N?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(Tc,{activeView:s,onViewChange:a,splitViewEnabled:P,hasQueryError:!!Y}),!n.isTableType(R)&&e.jsx(Ic,{})]}),R==="kpi"&&e.jsx(Rc,{visible:!0,className:"self-center"}),Q&&l.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:Q,variant:"compact"}),M&&e.jsx(Nt.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:o.id,cardFilters:(Oe=o.config)==null?void 0:Oe.filters,cardFilterCount:n.getFilterCount(((Pe=o.config)==null?void 0:Pe.filters)||null),onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:c,sheetId:x||"",removeInlineFilterValue:le=>u(o.id,le),resolvedPrimaryDateField:se}),s==="chart"&&e.jsx(Fc,{card:o,effectiveCardType:R,queryResultColumns:ge}),s==="chart"&&!O&&e.jsx(Ea,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:_||z,onClick:()=>{Te(!0),q()},children:e.jsx(Ds,{className:t.cn("h-3.5 w-3.5",{"animate-spin":fe})})}),s==="chart"&&e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"More Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:Ve,children:[P?e.jsx(vr,{className:"mr-2 h-4 w-4"}):e.jsx(Lr,{className:"mr-2 h-4 w-4"}),P?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Da,{onCustomize:()=>E(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"?Y?e.jsx(Lc,{showInfoTab:L}):e.jsx("div",{className:"flex grow flex-col",children:e.jsx(Dc,{card:o,queryData:B,isLoading:_,isFetching:z,pagination:G,onPaginationChange:Ue,onSortChange:Me,sortState:Ee,splitViewEnabled:P,isDynamicInspectorOpen:k,onDynamicInspectorOpenChange:E})}):null,s==="table"&&(B==null?void 0:B.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(_||z)&&(B==null?void 0:B.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(n.TableVisual,{card:o,data:ce,resultColumns:B.columns,columnKeyMap:B.columnKeyMap,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:Q,paginationMetadata:G,onPaginationChange:Ue,isLoading:_||z,onSortChange:Me,sortState:Ee})]}),s==="info"&&L&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-1",children:Y?e.jsx(So,{error:Y,errorSql:U,showCardDetails:!0,defaultSqlExpanded:!0,debugPayloads:j?{queryRequest:H,queryResponse:B,columns:d,dashboardFilters:m}:void 0,onSendFeedback:()=>{const le=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:l.config,dataSource:o.dataSource,dashboardFilters:m,errorMessage:Y,errorSql:U,generatedSql:B==null?void 0:B.sql});T(le),y(!0)},onOpenInEditor:()=>{v(!0),setTimeout(()=>{const le=t.useEditorStore.getState().actions;le.setIsDevMode(!0),le.setCardSql(U||""),setTimeout(()=>{le.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(ka,{sql:B.sql,showCardDetails:!0,debugPayloads:j?{queryRequest:H,queryResponse:B,columns:d,dashboardFilters:m}:void 0})})})]}),A&&e.jsx(n.FeedbackDialog,{open:S,onOpenChange:y,feedbackData:A})]})})}function Oc({activeField:s}){const[a,r]=C.useState(!0);if(C.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=!!n.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(n.TypeGlyph,{dataType:s.dataType,calculated:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const Bc=()=>{const s=console.error;console.error=(...o)=>{o.length>0&&typeof o[0]=="string"&&o[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,o)};const a=o=>{if(o.message&&(o.message.includes("ResizeObserver loop completed with undelivered notifications")||o.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),o.stopPropagation(),!1},r=o=>{var d;if((d=o.reason)!=null&&d.message&&(o.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||o.reason.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",r,!0)}};function Vc({column:s,isSelected:a,onSelect:r,availableFields:o,width:d,onWidthChange:l}){var B,Y,_;const i=t.useEditorStore(z=>z.card),{updateCardConfig:c,removeGroupByColumn:u,removeMetricColumn:m,updateFilters:x}=t.useEditorActions(),[g,p]=C.useState(!1),[h,v]=C.useState(!1),M=C.useRef(null),N=C.useCallback(z=>{z.preventDefault(),z.stopPropagation(),v(!0),M.current={startX:z.clientX,startWidth:d||150};const U=q=>{if(!M.current)return;const Q=q.clientX-M.current.startX,H=Math.max(80,M.current.startWidth+Q);l==null||l(s.id,H)},G=()=>{v(!1),M.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",G)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",G)},[d,s.id,l]),b=(B=i==null?void 0:i.config)==null?void 0:B.filters,w=(Y=b==null?void 0:b.conditions)==null?void 0:Y.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),F=z=>{z?x(i.id,z):c(i.id,{filters:void 0})},{attributes:S,listeners:y,setNodeRef:k,transform:E,transition:A,isDragging:T}=n.useSortable({id:s.id}),I={transform:n.CSS.Transform.toString(E),transition:A},L=t.getDataType(s.dataType),j=_c(L),P=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.sortByColumns)||[],U=z.findIndex(q=>q.name===s.name);if(U!==-1){const q=[...z];q[U]={...q[U],direction:"asc"},c(i.id,{sortByColumns:q})}else c(i.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},V=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.sortByColumns)||[],U=z.findIndex(q=>q.name===s.name);if(U!==-1){const q=[...z];q[U]={...q[U],direction:"desc"},c(i.id,{sortByColumns:q})}else c(i.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.groupByColumns)||[];if(!z.some(q=>q.name===s.name)){const q={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...z,q]})}},O=z=>{var q;const U=((q=i==null?void 0:i.config)==null?void 0:q.metricColumns)||[];if(!U.some(Q=>Q.name===s.name&&Q.aggregate===z)){const Q={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};c(i.id,{metricColumns:[...U,Q]})}},D=()=>{s.role==="groupby"?u(i.id,s.id):s.role==="metric"&&m(i.id,s.id)},R={...I,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:k,style:R,className:t.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",h&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...y,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(n.GripVertical,{className:"h-3 w-3"})}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:r,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(j,{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,")"]}),w&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(oe.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",w&&"text-primary")}),w?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:P,children:[e.jsx(fr,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:V,children:[e.jsx(pr,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(n.DropdownMenuSubContent,{children:[e.jsx(n.DropdownMenuItem,{onClick:()=>O("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:f,children:[e.jsx(n.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(n.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(n.DropdownMenuItem,{onClick:D,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:N,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",h&&"bg-primary")}),e.jsx(Va,{open:g,onOpenChange:p,availableFields:o.length>0?o:[s],existingFilters:b,editingCondition:w?(_=b==null?void 0:b.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:F})]})}function _c(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function Yc({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:o=[],filterableFields:d=o}){var T,I,L,j;const l=t.useEditorStore(P=>P.card),{updateCardConfig:i}=t.useEditorActions(),[c,u]=C.useState(null),[m,x]=C.useState({}),[g,p]=C.useState(!1),h=C.useMemo(()=>{var f,O;const P=((f=l==null?void 0:l.config)==null?void 0:f.groupByColumns)||[],V=((O=l==null?void 0:l.config)==null?void 0:O.metricColumns)||[];return[...P,...V]},[(T=l==null?void 0:l.config)==null?void 0:T.groupByColumns,(I=l==null?void 0:l.config)==null?void 0:I.metricColumns]),v=C.useMemo(()=>{const P=new Set(h.map(V=>`${V.qualifiedEntityName}.${V.name}`));return o.filter(V=>!P.has(`${V.qualifiedEntityName}.${V.name}`))},[o,h]),{data:M,isLoading:N}=n.useEditorCardQuery(l),b=(M==null?void 0:M.records)||[],w=C.useCallback((P,V)=>{x(f=>({...f,[P]:V}))},[]),F=C.useCallback(P=>{var D,R;const V=t.getDataType(P.dataType),f=((D=l==null?void 0:l.config)==null?void 0:D.groupByColumns)||[],O=((R=l==null?void 0:l.config)==null?void 0:R.metricColumns)||[];if(V==="number"){const B={...P,id:`metric-${P.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};i(l.id,{metricColumns:[...O,B]})}else{const B={...P,id:`groupby-${P.id}-${Date.now()}`,role:"groupby"};i(l.id,{groupByColumns:[...f,B]})}p(!1)},[(L=l==null?void 0:l.config)==null?void 0:L.groupByColumns,(j=l==null?void 0:l.config)==null?void 0:j.metricColumns,l.id,i]),S=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),y=P=>{u(P.active.id)},k=P=>{const{active:V,over:f}=P;if(u(null),!f||V.id===f.id)return;const O=h.findIndex(R=>R.id===V.id),D=h.findIndex(R=>R.id===f.id);if(O!==-1&&D!==-1){const R=n.arrayMove(h,O,D),B=R.filter(_=>_.role==="groupby"),Y=R.filter(_=>_.role==="metric");i(l.id,{groupByColumns:B,metricColumns:Y})}},E=c?h.find(P=>P.id===c):null,A=P=>{let V="";for(;P>=0;)V=String.fromCharCode(P%26+65)+V,P=Math.floor(P/26)-1;return V};return r?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"})}):h.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(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragStart:y,onDragEnd:k,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(n.SortableContext,{items:h.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:h.map((P,V)=>e.jsx("th",{style:{width:m[P.id]?`${m[P.id]}px`:void 0,minWidth:m[P.id]?`${m[P.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:A(V)},`letter-${P.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(n.SortableContext,{items:h.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:h.map(P=>e.jsx(Vc,{column:P,isSelected:(s==null?void 0:s.id)===P.id,onSelect:()=>a(P),availableFields:d,width:m[P.id],onWidthChange:w},P.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:g,onOpenChange:p,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(n.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns available."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:v.map(P=>{const V=t.getDataType(P.dataType),f=V==="number"?n.Hash:V==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:P.label||P.name,onSelect:()=>F(P),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:P.label||P.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:P.entityName})]})]},P.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:N?e.jsx("tr",{children:e.jsx("td",{colSpan:h.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:h.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):b.slice(0,100).map((P,V)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",V%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:V+1}),h.map(f=>{const O=P[f.name]??P[f.label??""];return e.jsx("td",{style:{width:m[f.id]?`${m[f.id]}px`:void 0,minWidth:m[f.id]?`${m[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:zc(O,f)})},`${V}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},V))})]}),e.jsx(n.DragOverlay,{children:E&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:E.label||E.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(b.length,100)," of ",b.length," rows"]}),e.jsxs("span",{children:[h.length," columns"]})]})]})}function zc(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 r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function qc({entityGroups:s,isLoading:a=!1}){var F,S;const r=t.useEditorStore(y=>y.card),{updateCardConfig:o,removeGroupByColumn:d,removeMetricColumn:l}=t.useEditorActions(),[i,c]=C.useState(!0),[u,m]=C.useState(""),[x,g]=C.useState(new Set),p=((F=r==null?void 0:r.config)==null?void 0:F.groupByColumns)||[],h=((S=r==null?void 0:r.config)==null?void 0:S.metricColumns)||[],v=y=>{const k=new Set(x);k.has(y)?k.delete(y):k.add(y),g(k)},M=y=>p.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName)||h.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName),N=(y,k)=>{if(k)if(t.getDataType(y.dataType)==="number"){const A={...y,id:`metric-${y.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(r.id,{metricColumns:[...h,A]})}else{const A={...y,id:`groupby-${y.id}-${Date.now()}`,role:"groupby"};o(r.id,{groupByColumns:[...p,A]})}else{const E=p.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName),A=h.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName);E!==-1&&d(r.id,p[E].id),A!==-1&&l(r.id,h[A].id)}},b=y=>{if(!u)return y;const k=u.toLowerCase();return y.filter(E=>E.name.toLowerCase().includes(k)||E.label&&E.label.toLowerCase().includes(k))},w=y=>{switch(t.getDataType(y)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Er,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ye.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:u,onChange:y=>m(y.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||h.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(Ye.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.Rows3,{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:p.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(y=>{const k=w(y.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(r.id,y.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]},y.id)})})})]}),h.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(Ye.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.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:h.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(y=>{const k=w(y.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.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:()=>l(r.id,y.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]},y.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(y=>{const k=b(y.columns);if(k.length===0)return null;const E=x.has(y.entityId)||u.length>0;return e.jsxs(n.Collapsible,{open:E,onOpenChange:()=>v(y.entityId),children:[e.jsxs(n.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(Ye.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",E&&"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:y.label||y.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:k.map(A=>{const T=w(A.dataType),I=M(A);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",I&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:I,onCheckedChange:L=>N(A,L),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name})]},A.id)})})})]},y.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(Ir,{className:"h-4 w-4"})})})}const $c=[{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 Kc({value:s,onChange:a,onSubmit:r,onCancel:o,selectedColumn:d,availableColumns:l}){const[i,c]=C.useState(!1),[u,m]=C.useState("column"),x=C.useRef(null);C.useEffect(()=>{const v=M=>{M.key==="Escape"&&s?o():M.key==="Enter"&&s&&!i&&r(s)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[s,o,r,i]);const g=v=>{const M=`[${v.label||v.name}]`,N=x.current;if(N){const b=N.selectionStart||0,w=N.selectionEnd||0,F=s.slice(0,b)+M+s.slice(w);a(F),setTimeout(()=>{N.setSelectionRange(b+M.length,b+M.length),N.focus()},0)}else a(s+M);c(!1)},p=v=>{const M=x.current;if(M){const N=M.selectionStart||0,b=M.selectionEnd||0,w=s.slice(0,N)+v.syntax+s.slice(b);a(w),setTimeout(()=>{M.setSelectionRange(N+v.name.length+1,N+v.syntax.length-1),M.focus()},0)}else a(s+v.syntax);c(!1)},h=v=>{switch(t.getDataType(v)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:i&&u==="function",onOpenChange:v=>{c(v),v&&m("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(Ar,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search functions..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No functions found."}),e.jsx(n.CommandGroup,{heading:"Functions",children:$c.map(v=>e.jsx(n.CommandItem,{value:v.name,onSelect:()=>p(v),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:v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:v.syntax})]})},v.name))})]})]})})]}),e.jsxs(t.Popover,{open:i&&u==="column",onOpenChange:v=>{c(v),v&&m("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(oe.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns found."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:l.map(v=>{const M=h(v.dataType);return e.jsxs(n.CommandItem,{value:v.label||v.name,onSelect:()=>g(v),children:[e.jsx(M,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:v.label||v.name})]},v.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:x,value:s,onChange:v=>a(v.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:o,title:"Cancel (Esc)",children:e.jsx(oe.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:()=>r(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function Uc({className:s}){var h,v,M,N;const a=t.useEditorStore(b=>b.card),[r,o]=C.useState(null),[d,l]=C.useState(""),{columns:i=[],columnGroups:c=[],isLoading:u}=n.useColumns(),{valuePickFilterableFields:m=[]}=n.useFilterableFields();(h=a==null?void 0:a.config)!=null&&h.groupByColumns,(v=a==null?void 0:a.config)!=null&&v.metricColumns,(M=a==null?void 0:a.config)!=null&&M.groupByColumns,(N=a==null?void 0:a.config)!=null&&N.pivotByColumns;const x=b=>{o(b),l(b?`[${b.label||b.name}]`:"")},g=b=>{console.log("Formula submitted:",b),l(""),o(null)},p=()=>{l(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Kc,{value:d,onChange:l,onSubmit:g,onCancel:p,selectedColumn:r,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Yc,{selectedColumn:r,onColumnSelect:x,isLoading:u,sourceFields:i,filterableFields:m})}),e.jsx(qc,{entityGroups:c,isLoading:u})]})]})}function Hc(){var B,Y;const[s,a]=C.useState("chart"),[r,o]=C.useState(!1),[d,l]=C.useState(!0),[i,c]=C.useState(!0),u=t.useEditorStore(_=>_.showAIDialog),m=t.useDashboardStore(_=>_.isVisualEditing),{setCardType:x}=t.useEditorActions(),g=t.useEditorStore(_=>_.card.type);C.useEffect(()=>Bc(),[]);const p=_=>{x(_)},h=t.useEditorStore(_=>_.frame),v=t.useEditorStore(_=>_.card);t.useEditorStore(_=>_.activeTabCardId),t.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:M,removeCard:N,updateCard:b,setActiveCard:w,updateFilters:F}=t.useEditorActions(),{columnFields:S=[],scopedFields:y=[],filterableFields:k=[]}=n.useFilterableFields(),E=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),A=v,{getFieldsForContainer:T,setFieldsForContainer:I}=n.useFieldManagement(A),{activeField:L,handleDragStart:j,handleDragEnd:P}=wc({activeCardId:h.activeCardId,sourceFields:y,getFieldsForContainer:T,setFieldsForContainer:I}),V=(_,z)=>{z&&F(_,z)},f=_=>{var z;b(_,{config:{...(z=h.cards.find(U=>U.id===_))==null?void 0:z.config,filters:void 0}})},O=k,D=_=>{if(!_)return 0;let z=_.conditions.length;return _.groups.forEach(U=>{z+=D(U)}),z},R=D(((B=A==null?void 0:A.config)==null?void 0:B.filters)||null);return e.jsxs(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragStart:j,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ma,{isVisible:d,onToggleVisibility:()=>l(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:g==="tableBuilder"?e.jsx(Uc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!u&&e.jsx(lc,{selectedChart:g,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),detailFields:T("detailColumns"),activeField:L,isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx(Pc,{selectedChart:g,activeView:s,onViewChange:a,onFiltersClick:()=>o(!0),filterCount:R,activeCard:A,columns:S,getFieldsForContainer:T,cards:h.cards,activeCardId:h.activeCardId,addCard:M,setActiveCard:w})]})}),!d&&m&&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:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(n.Database,{className:"h-4 w-4"})})})]}),A&&e.jsx(Sc,{cardId:A.id,filters:((Y=A.config)==null?void 0:Y.filters)||null,onFiltersChange:V,onClearFilters:f,availableFields:O,isOpen:r,onOpenChange:o}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(Oc,{activeField:L||null})})]})}function Gc({authToken:s,onSave:a,onClose:r}){const o=C.useRef(null),d=t.useEditorStore(E=>E.showAIDialog),l=t.useEditorStore(E=>E.isDevMode),i=n.useAssistantLayoutStore(E=>E.setFullscreen),c=n.useAssistantLayoutStore(E=>E.setPanelOpen),u=n.useAssistantLayoutStore(E=>E.setContainer),m=n.useAssistantPanel("editor"),x=n.useFullscreenAssistant(),g=n.useAssistantContainer("editor"),p=x==="editor",h=n.useDashboardAppearance(),v=C.useCallback(E=>{u("editor",E)},[u]),{setAuthToken:M}=t.useDashboardActions(),{setShowAIDialog:N,setOnSave:b,setOnClose:w}=t.useEditorActions(),{setActiveAssistantType:F}=t.useAIActions();C.useEffect(()=>{a&&b(a),r&&w(r)},[a,b,r,w]),C.useEffect(()=>{s&&s.accessToken&&M(s)},[s,M]),C.useEffect(()=>{var E,A;d?((E=o.current)==null||E.resize(40),c("editor",!0),F("editor")):((A=o.current)==null||A.resize(0),c("editor",!1),x==="editor"&&i(null),F(null))},[d,c,F,i,x]);function S(E){var A;E<1?(N(!1),c("editor",!1),x==="editor"&&i(null),F(null),(A=o.current)==null||A.resize(0)):(d||(N(!0),F("editor")),m.isOpen||c("editor",!0))}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(ma,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ri,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:S,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(na,{isFullscreen:p,onFullscreenChange:E=>i(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:v,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function k(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hc,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:S,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(na,{isFullscreen:p,onFullscreenChange:E=>i(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:v,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(n.ErrorBoundary,{FallbackComponent:n.Fallback,children:l?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:h.dashboardContainerStyle,children:y()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:h.dashboardContainerStyle,children:k()})})}function Qc(){t.useDashboardStore(h=>h.selectedCardId);const s=t.useDashboardStore(h=>h.selectedSheetId),a=t.useDashboardStore(h=>h.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(h=>h.actions),d=t.useEditorStore(h=>h.editorContext),{clearEditorContext:l}=t.useEditorStore(h=>h.actions),i=n.useDashboardAppearance(),c=t.useDashboardStore(h=>h.isVisualEditing),u=t.useDashboardStore(h=>h.actions.updateFrame),m=t.useDashboardStore(h=>h.actions.updateDocumentSectionCard),x=n.useResolveExistingFrameSemanticExecutionPayload();async function g(h){var w,F,S;if((d==null?void 0:d.type)==="documentSection"){const y=n.getDocumentSectionEditorCard(h,d.cardId);if(!y){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(y)){n.ue.error("Document table sections support Table and Pivot Table");return}m(d.sheetId,d.sectionId,y,{calculatedFields:h.calculatedFields}),l(),r(!1);return}const v=s?(w=a==null?void 0:a.sheets)==null?void 0:w.some(y=>{var k;return y.id===s&&((k=y.frames)==null?void 0:k.some(E=>E.id===h.id))}):!1,M=(S=(F=a==null?void 0:a.sheets)==null?void 0:F.find(y=>{var k;return(k=y.frames)==null?void 0:k.some(E=>E.id===h.id)}))==null?void 0:S.id,N=v?s:M||null;if(!N)return;const b=t.findDashboardFrameById(a,h.id);try{const y=await x(h,{previousFrame:b});u(N,h,{semanticExecutionPayload:y}),s!==N&&o(N),r(!1)}catch(y){console.error("Failed to resolve semantic metadata on save:",y),n.ue.error(y instanceof Error?y.message:"Failed to resolve semantic metadata for this visual")}}function p(){l(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),style:i.dashboardContainerStyle,children:e.jsx(Gc,{onSave:g,onClose:p})})}exports.default=Qc;
|
|
172
|
+
`),qe=new Blob([me],{type:"text/csv"}),$e=URL.createObjectURL(qe),Je=document.createElement("a");Je.href=$e,Je.download=`${m.title}.csv`,Je.click()}if(!m)return e.jsx(e.Fragment,{children:"No Active Card"});const ze=r==="both"||r==="toolbar",We=r==="both"||r==="canvas",_e=!Q&&!H&&!se&&(q!=null&&q.sql)?e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:o?e.jsx(n.IconButton,{className:"h-7 w-7 shrink-0 px-0",buttonProps:{"aria-label":"View executed SQL"},children:e.jsx(br,{className:"h-3.5 w-3.5",strokeWidth:1.75})}):e.jsx("button",{type:"button",className:"cursor-pointer text-[11px] underline-offset-4 hover:text-foreground hover:underline",children:"Executed SQL"})}),e.jsx(n.HoverCardContent,{align:"end",collisionPadding:16,className:"w-[500px] overflow-hidden p-0",children:e.jsx(ka,{sql:q.sql})})]})}):null;return e.jsxs("div",{className:t.cn("relative isolate flex flex-col",o?"ml-auto min-w-0 shrink-0":r==="toolbar"?"h-auto pb-1":t.cn("h-full",!S&&"pt-2")),children:[ze&&e.jsxs("div",{className:t.cn("z-10 mb-0 flex items-center",o?"min-w-0 shrink-0 gap-1.5":"min-h-10 gap-2 px-4"),children:[o?_e:null,h&&e.jsx("div",{className:t.cn("flex items-center",o?"shrink-0":"grow gap-4"),children:e.jsx("div",{className:"flex items-center gap-3",children:!p&&!T&&e.jsx(Ta,{selectedChart:m.type,onChartChange:ne=>U(ne),compactMore:!0,responsiveCompact:o})})}),!h&&!o&&e.jsx("div",{className:"grow"}),e.jsxs("div",{className:t.cn("flex items-center text-muted-foreground",o?"gap-1.5":"gap-2"),children:[s,o?null:_e,Ee&&Ee.length>0&&e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(n.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(n.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:Ee.length})]})}),e.jsxs(n.HoverCardContent,{align:"end",className:"flex max-h-[400px] w-[500px] flex-col overflow-hidden p-0",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-2 text-[13px] font-medium",children:"Active Dashboard Filters"}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(t.CodeEditor,{value:JSON.stringify(Ee,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),!T&&e.jsx("div",{className:o?"hidden @[1250px]:flex":"",children:e.jsx(Ea,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1})}),(a==null?void 0:a.show)&&e.jsxs(t.Button,{type:"button",variant:"ghost",size:"xs","aria-pressed":a.isOpen,onClick:a.onToggle,className:t.cn("h-7 shrink-0 gap-1.5 text-[12px]",o?"hidden w-7 px-0 @[850px]:inline-flex @[1350px]:w-auto @[1350px]:px-2":"px-2",a.isOpen&&"bg-accent text-accent-foreground"),children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{className:o?"hidden @[1350px]:inline":"",children:"Settings"})]}),(x||N)&&y&&e.jsx(tl,{enabled:Pe,selectedPageSize:De,pageSizeOptions:le,onEnabledChange:Ie,onPageSizeChange:$,responsive:o}),e.jsx(n.IconButton,{tooltip:"Refresh",disabled:Q||H,className:t.cn("h-7 w-7 px-0",o&&"hidden @[1150px]:inline-flex"),onClick:ve,children:e.jsx(Ds,{className:t.cn("h-3.5 w-3.5",{"animate-spin":Fe})})}),e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",collisionPadding:8,className:"max-h-[var(--radix-dropdown-menu-content-available-height)] w-56 overflow-y-auto overscroll-contain",children:[(o||(d==null?void 0:d.reset))&&e.jsxs(e.Fragment,{children:[o&&e.jsxs(n.DropdownMenuItem,{disabled:Q||H,onSelect:ve,children:[e.jsx(Ds,{className:"h-3.5 w-3.5"}),"Refresh result"]}),d==null?void 0:d.reset,e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Export"}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Ae,className:"gap-2 text-[13px]",children:[e.jsx(n.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Z,className:"gap-2 text-[13px]",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(n.DropdownMenuItem,{disabled:!ie,onSelect:Re,className:"gap-2 text-[13px]",children:[e.jsx(n.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]}),e.jsx(n.DropdownMenuSeparator,{}),(d==null?void 0:d.query)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"Query"}),d.query,e.jsx(n.DropdownMenuSeparator,{})]}),(o&&(a==null?void 0:a.show)||x||N)&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuLabel,{children:"Output"}),o&&(a==null?void 0:a.show)&&e.jsx(n.DropdownMenuCheckboxItem,{checked:a.isOpen,onCheckedChange:()=>a.onToggle(),children:"Settings"}),(x||N)&&e.jsx(n.DropdownMenuCheckboxItem,{checked:!h,onCheckedChange:ne=>v(ne!==!0),children:"Show raw results"}),o&&(x||N)&&y&&e.jsxs(e.Fragment,{children:[e.jsx(n.DropdownMenuCheckboxItem,{checked:Pe,onCheckedChange:ne=>Ie(ne===!0),children:"Paginate results"}),Pe&&e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:["Page size",e.jsx("span",{className:"ml-auto tabular-nums text-muted-foreground",children:De})]}),e.jsx(n.DropdownMenuSubContent,{children:e.jsx(n.DropdownMenuRadioGroup,{value:String(De),onValueChange:$,children:le.map(ne=>e.jsx(n.DropdownMenuRadioItem,{value:String(ne),children:ne},ne))})})]})]}),e.jsx(n.DropdownMenuSeparator,{})]}),e.jsx(n.DropdownMenuLabel,{children:"Customize"}),!T&&!["table","detailTable","custom"].includes(m.type)&&M&&e.jsx(Mo,{triggerVariant:"menu",className:"w-full"}),e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),E&&e.jsxs(n.DropdownMenuItem,{onSelect:()=>{var ne;return(ne=a==null?void 0:a.onOpen)==null?void 0:ne.call(a,"style")},className:"gap-2 text-[13px]",children:[e.jsx(Tr,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(Da,{onCustomize:()=>P(!0)})]})]})]})]}),We&&(h?T?e.jsx(kt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ia,{fallbackPreview:e.jsx(kt,{}),records:Me,title:m.title,isInspectorOpen:j,onInspectorOpenChange:P})}):e.jsx(kt,{}):e.jsxs(n.ResizablePanelGroup,{className:t.cn(b&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[b&&e.jsxs(e.Fragment,{children:[e.jsx(n.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:b&&e.jsx(el,{})}),e.jsx(n.ResizableHandle,{})]}),e.jsxs(n.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":b}),children:[Array.isArray(q==null?void 0:q.records)&&!se&&(x?e.jsx(fo,{data:q.records,card:G,paginationMetadata:Te,onPaginationChange:xe,onPageSizePreferenceChange:_,onSortChange:Ce,isLoading:Q||H}):q.records.length>0?e.jsx(n.TableVisual,{card:m,data:Me,resultColumns:q==null?void 0:q.columns,columnKeyMap:q==null?void 0:q.columnKeyMap,totalsByColumnId:q==null?void 0:q.tableTotalsByColumnId,comparisonMetadata:(ue=q==null?void 0:q.metadata)==null?void 0:ue.comparisonMetadata,paginationMetadata:Te,onPaginationChange:xe,onSortChange:Ce,isLoading:Q||H}):null),se&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(cs,{error:se,errorSql:ce||m.sql||m.python,onDebugWithAssistant:Ue,showFeedbackButton:!1})})]})]}))]})}function el(){const s=t.useEditorStore(r=>r.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 tl({enabled:s,selectedPageSize:a,pageSizeOptions:r,onEnabledChange:o,onPageSizeChange:d,responsive:l}){return e.jsxs("div",{className:t.cn("items-center gap-2",l?s?"flex":"hidden @[1550px]:flex":"flex"),children:[e.jsx(n.Checkbox,{id:"dev-pagination","aria-label":"Paginate results",title:l&&s?"Pagination enabled":void 0,checked:s,onCheckedChange:i=>o(i===!0)}),e.jsx(t.Label,{htmlFor:"dev-pagination",className:t.cn("cursor-pointer text-[13px]",l&&"hidden @[1550px]:block"),children:"Paginate"}),s&&e.jsxs(t.Select,{value:String(a),onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-7 w-20 rounded-[5px] px-2 text-[12px]",l&&"hidden @[1550px]:flex"),children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:r.map(i=>e.jsx(t.SelectItem,{value:String(i),children:i},i))})]})]})}function at({value:s,onCommit:a,type:r="text",placeholder:o,className:d}){const[l,i]=C.useState(s),c=C.useRef(!1);C.useEffect(()=>{i(s)},[s]);const u=()=>{if(c.current){c.current=!1;return}l!==s&&a(l)},m=x=>{if(x.key==="Enter"){x.currentTarget.blur();return}x.key==="Escape"&&(c.current=!0,i(s),x.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:l,onChange:x=>i(x.target.value),onBlur:u,onKeyDown:m,className:d})}function Ct({defaultValue:s,label:a,options:r,value:o,onValueChange:d,className:l,icon:i,showPlaceholderLabel:c=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:d,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",l),children:e.jsxs("div",{className:"flex items-center gap-2",children:[i&&e.jsx("span",{children:i}),c&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),r.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function sl(s,a){return he.getSlotDefinitionForIndex(s,a)||null}function Ht(s){if(typeof s=="number")return`Tab ${s+1}`;const a=s.match(/^(\d+)-(\d+)$/);if(a){const[,o,d]=a;return`Tabs ${Number(o)+1}-${Number(d)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function nl(s){return s?Array.isArray(s)?s:[s]:[]}function Cs(s){var o,d;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const a=!!((d=s.sql)!=null&&d.trim()),r=Ke.hasValidCardConfig(s.config);return a||r}function al({slots:s,cards:a,minInputs:r}){const o=[],d=a.filter(Boolean).length;return r&&d<r&&o.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(l=>{if(!l.required)return;if(typeof l.position=="number"){const u=a[l.position];Cs(u)||o.push({type:"missing-required",message:`${Ht(l.position)} ("${l.label}") is required but has no data configured.`});return}const i=l.position.match(/^(\d+)-(\d+)$/);if(i){const[,u,m]=i.map(Number);for(let x=u;x<=m;x+=1){const g=a[x];if(!Cs(g)){o.push({type:"missing-required",message:`${Ht(x)} ("${l.label}") is required but has no data configured.`});break}}return}const c=l.position.match(/^(\d+)\+$/);if(c){const u=Number(c[1]);if(a.length<=u){o.push({type:"missing-required",message:`${Ht(u)} ("${l.label}") is required but has no data configured.`});return}for(let m=u;m<a.length;m+=1){const x=a[m];if(!Cs(x)){o.push({type:"missing-required",message:`${Ht(m)} ("${l.label}") is required but has no data configured.`});break}}}}),a.forEach((l,i)=>{if(!l)return;const c=sl(s,i);if(!c||!c.expectedType)return;const u=nl(c.expectedType);u.length!==0&&(u.includes(l.type)||o.push({type:"wrong-type",message:`${Ht(i)} ("${c.label}") expects ${u.join(", ")}, but is configured as ${l.type}.`}))})),o}const rl={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 Ma(){var j,P,V;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=n.usePluginQuery(),r=(a==null?void 0:a.plugins)||[],o=t.useEditorStore(f=>f.card),d=t.useEditorStore(f=>f.frame),{setCustomCardPreferences:l}=t.useEditorActions(),i=C.useMemo(()=>he.findCustomVisualConfigCard(d,o),[d,o]),c=i==null?void 0:i.customCardPreferences,{components:u,manifest:m}=n.useCustomVisual((c==null?void 0:c.url)||(s==null?void 0:s.url)||""),x=(j=m==null?void 0:m.visuals)==null?void 0:j.find(f=>f.name===((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))),p=he.resolveMultiInputType(i||o,x)==="multiple",h=!!i&&i.id===o.id,v=(x==null?void 0:x.minInputs)??((P=i==null?void 0:i.customCardPreferences)==null?void 0:P.minInputs),M=(x==null?void 0:x.maxInputs)??((V=i==null?void 0:i.customCardPreferences)==null?void 0:V.maxInputs),N=C.useMemo(()=>he.getCustomVisualInputCards({frame:d,configCard:i||o,isMultiInputVisual:p}),[d,i,o,p]),b=C.useMemo(()=>he.buildSlotOrderedCards(N),[N]),w=C.useMemo(()=>b.map((f,O)=>{if(!f)return null;const D=he.getSlotIndexForCard(f,O),R=he.getEffectiveCardTypeForSlot(f,D,x==null?void 0:x.slots);return{...f,type:R??f.type}}),[b,x==null?void 0:x.slots]),F=C.useMemo(()=>al({slots:x==null?void 0:x.slots,cards:w,minInputs:v}),[x==null?void 0:x.slots,w,v]),S=C.useMemo(()=>{const f=N.findIndex(O=>(O==null?void 0:O.id)===o.id);return f<0?-1:he.getSlotIndexForCard(o,f)},[N,o]);function y(f){if(typeof f=="number")return`Tab ${f+1}`;const O=f.match(/^(\d+)-(\d+)$/);if(O){const[,R,B]=O;return`Tabs ${Number(R)+1}-${Number(B)+1}`}const D=f.match(/^(\d+)\+$/);return D?`Tabs ${Number(D[1])+1}+`:`Tab ${f}`}function k(f){return f?(Array.isArray(f)?f:[f]).join(", "):null}function E(f,O,D=[],R="",B,Y,_){const z=A({key:O,defaultValue:R,settingsValue:Y,sourceCard:_});return f==="input"?e.jsx(at,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:U=>{T({key:O,value:U,settingsField:B,settingsValue:Y,sourceCard:_})}},O):f==="select"?e.jsx(Ct,{className:"h-8 w-full",label:"",options:D,value:String(z!==void 0?z:R??""),onValueChange:U=>{T({key:O,value:U,settingsField:B,settingsValue:Y,sourceCard:_})}}):null}function A({key:f,defaultValue:O,settingsValue:D,sourceCard:R}){const B=D==null?void 0:D[f];return B!==void 0?B:f==="title"&&(R==null?void 0:R.title)!==void 0?R.title:f==="description"&&(R==null?void 0:R.description)!==void 0?R.description:O}function T({key:f,value:O,settingsField:D,settingsValue:R,sourceCard:B}){const Y={...R||{}},_=f==="title"&&(B==null?void 0:B.title)!==void 0,z=f==="description"&&(B==null?void 0:B.description)!==void 0;_&&O===String((B==null?void 0:B.title)??"")||z&&O===String((B==null?void 0:B.description)??"")?delete Y[f]:Y[f]=O,l({...s||{},[D]:Y})}function I({settingsSchema:f,settingsField:O,settingsValue:D,sourceCard:R,headerLabel:B}){const Y=Object.entries(f||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),Y.map(([_,z])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{children:z.title}),((U=z.docs)==null?void 0:U.description)&&e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:z.docs.description})})]})})]}),E(z.ui,_,z.options,z.defaultValue,O,D,R)]},_)})]})}function L(){return e.jsxs(e.Fragment,{children:[p&&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:x!=null&&x.slots&&x.slots.length>0?e.jsx("div",{className:"space-y-3",children:x.slots.map((f,O)=>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:y(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:[k(f.expectedType)&&e.jsxs("span",{children:["Expected: ",k(f.expectedType)]}),f.required&&e.jsx("span",{children:"Required"})]})]},`${f.label}-${O}`))}):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."}),(v||M)&&e.jsxs("p",{children:[v?`Min ${v} tabs`:"",v&&M?" • ":"",M?`Max ${M} tabs`:""]})]})})]}),p&&F.length>0&&e.jsx(n.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(n.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:F.map((f,O)=>e.jsx("li",{children:f.message},`${f.type}-${O}`))})})}),x&&!p&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:I({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),x&&p&&(x.settings||x.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[h&&x.settings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:x.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:i||o,headerLabel:"Global Settings"})}),x.slotSettings&&e.jsx("div",{className:"px-2",children:I({settingsSchema:x.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const f=o.tabTitle||o.title,O=S>=0?S:0,D=h?"Slot 0":`Slot ${O}`;return f?`${D}: ${f} Settings`:`${D} Settings`})()})})]})]})}return e.jsxs(n.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(n.AccordionItem,{value:"plugin-settings",children:[e.jsx(n.AccordionTrigger,{children:"Plugin"}),e.jsx(n.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:[(!p||h)&&e.jsx(Ct,{icon:e.jsx(ia,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(c==null?void 0:c.url)||"",onValueChange:f=>l({...s||{url:"",componentName:""},url:f})}),p&&!h&&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&&(!p||h)&&e.jsx(e.Fragment,{children:u&&e.jsx(Ct,{icon:e.jsx(gr,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.map(f=>({value:f.name,label:f.name})))||[],value:s.componentName||"",onValueChange:f=>{var R;const O=(R=m==null?void 0:m.visuals)==null?void 0:R.find(B=>B.name===f),D=u==null?void 0:u.find(B=>B.name===f);l({...s,componentName:f,visualType:(O==null?void 0:O.visualType)||(D==null?void 0:D.type)||"single",minInputs:O==null?void 0:O.minInputs,maxInputs:O==null?void 0:O.maxInputs,pluginChartType:O==null?void 0:O.chartType})}})})]})})]}),((c==null?void 0:c.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(n.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(x==null?void 0:x.name)||"Settings"}),(x==null?void 0:x.docs)&&e.jsxs(n.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(n.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(n.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:[x.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.docs.description}),x.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(n.Markdown,{remarkPlugins:[n.remarkGfm],components:rl,children:x.docs.dataSchema})})]}),(()=>{var O;const f=(O=x.docs)==null?void 0:O.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((D,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:D})]},R))})]})})()]})})]})]})}),e.jsx(n.AccordionContent,{children:L()})]})]})}function is(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Aa(s,a,r){if(!a||a==="auto")return{type:"auto"};if(a==="duration")return{type:"duration",multiplyBy:void 0,percentValueMode:void 0,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits};const o={...s,type:a,multiplyBy:a==="percent"?s.multiplyBy:void 0,percentValueMode:a==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return a&&["number","currency","percent","scientific"].includes(a)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0&&!(a==="currency"&&(r!=null&&r.preserveSparseCurrency))?La(o,is(a)):o}function ol(s,a){return{...s,decimalPlaces:void 0,minimumFractionDigits:a,maximumFractionDigits:a}}function Kn(s){const a=s.decimalPlaces;return{...s,currency:void 0,decimalPlaces:void 0,minimumFractionDigits:s.minimumFractionDigits??a,maximumFractionDigits:s.maximumFractionDigits??a}}function ll(s,a){const r=s.type||"auto";return r==="auto"?s:r==="duration"?{type:"duration",prefix:s.prefix,suffix:s.suffix,negativeInParentheses:s.negativeInParentheses,durationInputUnit:s.durationInputUnit||"second",durationDisplayStyle:s.durationDisplayStyle||"compact",durationLargestUnit:s.durationLargestUnit||"day",durationSmallestUnit:s.durationSmallestUnit||"second",durationMaxUnits:s.durationMaxUnits}:Aa(s,r,a)}function La(s,a){return{...s,decimalPlaces:a,minimumFractionDigits:a,maximumFractionDigits:a}}const Ft="__report_default__",il=["auto","number","currency","percent","scientific","date","duration"],Un=[{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"}],Hn=[{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"}],Ns=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],cl=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],dl=s=>s.charAt(0).toUpperCase()+s.slice(1);function ul(s,a){try{return oa.resolveCurrencyFractionDigits(s,a).maximumFractionDigits??is("currency")}catch{return is("currency")}}function Xt({formatOptions:s={},onFormatOptionsChange:a,showTitle:r=!0,title:o="NUMBER FORMAT",maxDecimalPlaces:d=10,reportDefaults:l,showAutoFormat:i=!0}){var I,L;const c=s.type||"auto",u=ll(s,{preserveSparseCurrency:!!l}),m=j=>{j.stopPropagation()},x=(j,P)=>{a({...u,[j]:P})},g=u.decimalPlaces??u.maximumFractionDigits??u.minimumFractionDigits,p=s.currency??(l==null?void 0:l.currency)??"USD",h=s.locale??(l==null?void 0:l.locale)??"en-US",v=c==="currency"?ul(h,p):void 0,M=g??v??is(c),N=c==="currency"&&u.decimalPlaces===void 0&&u.minimumFractionDigits===void 0&&u.maximumFractionDigits===void 0,[b,w]=C.useState(()=>String(M)),[F,S]=C.useState(()=>u.multiplyBy!==void 0?String(u.multiplyBy):""),y=j=>{const P=Aa(s,j,{preserveSparseCurrency:!!l});a(l&&j==="currency"&&s.type!=="currency"?Kn(P):P)},k=j=>l&&c==="currency"?ol(u,j):La(u,j),E=((I=Un.find(j=>j.value===(l==null?void 0:l.currency)))==null?void 0:I.label)??(l==null?void 0:l.currency),A=((L=Hn.find(j=>j.value===(l==null?void 0:l.locale)))==null?void 0:L.label)??(l==null?void 0:l.locale),T=c==="number"||c==="currency"||c==="percent"||c==="scientific";return C.useEffect(()=>{w(String(M))},[M]),C.useEffect(()=>{S(u.multiplyBy!==void 0?String(u.multiplyBy):"")},[u.multiplyBy]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsxs(t.Select,{value:c,onValueChange:j=>y(j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:il.filter(j=>i||j!=="auto").map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":dl(j)},j))})]})]}),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.jsxs("div",{className:"flex-1",children:[e.jsx(t.Input,{type:"text",inputMode:"numeric",min:"0",max:d,placeholder:"0",value:b,onClick:m,onPointerDown:m,onKeyDown:m,onChange:j=>{const P=j.target.value.replace(/[^\d]/g,"");w(P),P!==""&&a(k(Math.max(0,Math.min(d,parseInt(P,10)))))},onBlur:()=>{if(b!=="")return;const j=M;w(String(j)),a(k(j))},className:"h-8 text-xs"}),N&&e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"Currency default"})]})]}),c==="currency"&&e.jsx("div",{className:"space-y-1",children: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||(l?Ft:"USD"),onValueChange:j=>{if(j===Ft){a(Kn(u));return}x("currency",j)},children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[l&&e.jsxs(t.SelectItem,{value:Ft,className:"text-xs",children:["Report default — ",E]}),Un.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:j=>j.stopPropagation(),onCheckedChange:j=>x("useSuffix",j)})]}),c!=="duration"&&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||(l&&T?Ft:"en-US"),onValueChange:j=>x("locale",j===Ft?void 0:j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[l&&T&&e.jsxs(t.SelectItem,{value:Ft,className:"text-xs",children:["Report default — ",A]}),Hn.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("prefix",j.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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("suffix",j.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:j=>j.stopPropagation(),onCheckedChange:j=>x("negativeInParentheses",j)})]}),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:F,onClick:m,onPointerDown:m,onKeyDown:m,onChange:j=>{const P=j.target.value.replace(/[^0-9.]/g,"");S(P),x("multiplyBy",P?parseFloat(P):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:m,onPointerDown:m,onKeyDown:m,onChange:j=>x("dateFormat",j.target.value),className:"h-8 text-xs"})})]}),c==="duration"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Value Is"}),e.jsxs(t.Select,{value:s.durationInputUnit||"second",onValueChange:j=>x("durationInputUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Display"}),e.jsxs(t.Select,{value:s.durationDisplayStyle||"compact",onValueChange:j=>x("durationDisplayStyle",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:cl.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Smallest"}),e.jsxs(t.Select,{value:s.durationSmallestUnit||"second",onValueChange:j=>x("durationSmallestUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"w-20 text-xs text-muted-foreground",children:"Largest"}),e.jsxs(t.Select,{value:s.durationLargestUnit||"day",onValueChange:j=>x("durationLargestUnit",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 flex-1 text-xs",onClick:m,onPointerDown:m,onKeyDown:m,children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(j=>e.jsx(t.SelectItem,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]})]})]})]})}function Gn({colorRanges:s,setColorRanges:a}){const r={start:-1/0,end:100,color:""};function o(i,c,u){const m=[...s];m[i]={...m[i],[c]:u},a(m)}function d(i){const c=[...s];c.splice(i,1),a(c)}function l(){a([...s,r])}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:l,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(n.Plus,{className:"size-3"})})]}),s.map((i,c)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:u=>o(c,"start",u.target.value),value:i.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:i.end,onChange:u=>o(c,"end",u.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:u=>o(c,"color",u.target.value),value:i.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:Ke.colors.green[600]}),e.jsx("option",{children:Ke.colors.red[500]}),e.jsx("option",{children:Ke.colors.yellow[400]}),e.jsx("option",{children:Ke.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>d(c),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(oe.X,{className:"size-3"})})]},c))]})}const ml=[];function xl(s){return(s==null?void 0:s.enabled)===!1||typeof(s==null?void 0:s.enabled)=="string"&&s.enabled.trim().toLowerCase()==="false"}function hl(s){var r;const a=t.fromPersistedKpiFormatOptions((r=s==null?void 0:s.kpiVisualOptions)==null?void 0:r.formatOptions)||(s!=null&&s.formatNumber?t.fromLegacyFormatNumber(s==null?void 0:s.formatNumber):void 0);return t.toTFormatOptions(a,{preserveOmittedProperties:!0})||{type:"number",minimumFractionDigits:0,maximumFractionDigits:0}}function Qn(s){return{enabled:!0,colorRanges:s==null?void 0:s.colorRanges}}function pl(){var p,h,v,M;const s=t.useEditorStore(N=>N.card),a=t.useEditorStore(N=>N.actions.setCardPreferences),r=t.useEditorStore(N=>{var b,w;return((w=(b=N.card.preferences)==null?void 0:b.formatNumber)==null?void 0:w.colorRanges)??ml}),o=t.useEditorStore(N=>N.actions.setColorRanges),d=n.useResolvedValueFormatLocale()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale,l=n.useResolvedDefaultCurrency()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,i=!n.isSqlBackedKpi(s)&&Ke.hasValidCardConfig(s.config),c=hl(s.preferences),u=!!t.fromPersistedKpiFormatOptions((h=(p=s.preferences)==null?void 0:p.kpiVisualOptions)==null?void 0:h.formatOptions),m=!xl((v=s.preferences)==null?void 0:v.formatNumber)&&(u||!!((M=s.preferences)!=null&&M.formatNumber)),x=N=>{const b=t.useEditorStore.getState().card.preferences??{};a({...b,formatNumber:Qn(b.formatNumber),kpiVisualOptions:{...b.kpiVisualOptions,formatOptions:N}})},g=N=>{const b=t.useEditorStore.getState().card.preferences??{};if(N){a({...b,formatNumber:Qn(b.formatNumber),kpiVisualOptions:{...b.kpiVisualOptions,formatOptions:c}});return}a({...b,formatNumber:{...b.formatNumber,enabled:!1}})};return i?e.jsx(Gn,{colorRanges:r,setColorRanges:o}):e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"query-kpi-format-number",checked:m,onCheckedChange:N=>g(N===!0)}),e.jsx(t.Label,{htmlFor:"query-kpi-format-number",className:"text-xs",children:"Format number"})]}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Xt,{formatOptions:c,onFormatOptionsChange:x,showTitle:!1,showAutoFormat:!1,reportDefaults:{currency:l,locale:d}}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(Gn,{colorRanges:r,setColorRanges:o})]})]})}const fl={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 Fa(s){return fl[s]}function gl({chartType:s,showDocsLink:a=!0}){const r=Fa(s);return r?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:r.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:r.fields.map((o,d)=>e.jsxs("tr",{className:d<r.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[o.name,o.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:o.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:o.description||"—"})]},o.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:r.description}),a&&r.docsUrl&&e.jsxs("a",{href:r.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:o=>o.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(n.ExternalLink,{className:"h-3 w-3"})]})]}):null}function bl({chartType:s}){return Fa(s)?e.jsxs(n.HoverCard,{openDelay:200,children:[e.jsx(n.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(n.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(gl,{chartType:s})})]}):null}function Vs({chartType:s,suffix:a="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-medium",children:a}),e.jsx(bl,{chartType:s})]})}function jl(){const s=t.useEditorStore(d=>!Ke.hasValidCardConfig(d.card.config)),a=t.useEditorStore(d=>{var l,i;return((i=(l=d.card.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:i.queryComparisonPolarity)??Mn.DEFAULT_METRIC_COMPARISON_POLARITY}),r=t.useEditorStore(d=>d.actions.setCardPreferences),o=d=>{const l=t.useEditorStore.getState().card.preferences??{},i={...l.kpiVisualOptions,queryComparisonPolarity:d===Mn.DEFAULT_METRIC_COMPARISON_POLARITY?void 0:d};r({...l,kpiVisualOptions:i})};return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Vs,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(pl,{})}),s&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx(t.Label,{htmlFor:"query-kpi-favorable-direction",className:"text-xs",children:"Favorable direction"}),e.jsxs(t.Select,{value:a,onValueChange:d=>o(d),children:[e.jsx(t.SelectTrigger,{id:"query-kpi-favorable-direction",className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Applies when the query returns current and comparison values."})]})]})}function Wn({children:s,summary:a,open:r,className:o}){return e.jsxs("details",{open:r,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",o),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 vl(){const[s,a]=C.useState([]),r=t.useEditorStore(m=>m.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:d}=t.useEditorStore(m=>m.actions),l=t.useEditorStore(m=>m.queryResultColumns);t.useEditorStore(m=>{var x;return(x=m.card.preferences)==null?void 0:x.filterOnClickColumnIndex}),C.useEffect(()=>{l&&a(new Array(l.length).fill(!1))},[l]);function i(m,x){var g,p;x?r!=null&&r.onClickFilter&&((g=r==null?void 0:r.onClickFilter)==null?void 0:g.length)>0?d({...r,onClickFilter:[...r.onClickFilter,{columnIndex:m,expression:""}]}):d({...r,onClickFilter:[{columnIndex:m,expression:""}]}):(d({...r,onClickFilter:(p=r==null?void 0:r.onClickFilter)==null?void 0:p.filter(h=>h.columnIndex!==m)}),a(h=>{const v=[...h];return v[m]=!1,v}))}function c(m,x){var p;const g=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.map(h=>h.columnIndex===m?{...h,expression:x.target.value}:h);d({...r,onClickFilter:g})}function u(m){var x,g,p,h;if(s!=null&&s[m]||(g=(x=r==null?void 0:r.onClickFilter)==null?void 0:x.find(v=>v.columnIndex===m))!=null&&g.expression)return e.jsx(t.Input,{value:(h=(p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(v=>v.columnIndex===m))==null?void 0:h.expression,onChange:v=>c(m,v),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:l==null?void 0:l.map((m,x)=>{var g,p;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(n.Checkbox,{checked:!!((g=r==null?void 0:r.onClickFilter)!=null&&g.find(h=>h.columnIndex===x)),onCheckedChange:h=>i(x,h)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:m}),e.jsx("div",{className:"flex items-center gap-2",children:((p=r==null?void 0:r.onClickFilter)==null?void 0:p.find(h=>h.columnIndex===x))&&e.jsx(n.Pencil,{onClick:()=>{a(h=>{const v=[...h];return v[x]=!h[x],v})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(x)]})},m)})})}const yl=[{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"}],Cl=["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"],Nl=Cl.map(s=>({label:s,value:s}));function Sl(){var u,m,x,g,p,h,v,M,N,b,w,F,S,y,k,E,A,T;const s=t.useEditorStore(I=>I.card),a=(m=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:m.topoJsonUrl,[r,o]=C.useState(((g=(x=s==null?void 0:s.preferences)==null?void 0:x.mapVisualOptions)==null?void 0:g.customTopoJsonUrl)||""),{setCardPreferences:d}=t.useEditorActions(),{data:l}=n.useTopoJson(s),i=Object.keys((l==null?void 0:l.objects)||{}).map(I=>({label:I,value:I}))||[],c=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Vs,{chartType:"map"}),e.jsx(Wn,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(Ct,{className:"h-9",options:c,onValueChange:I=>{console.log("value",I),d({...s.preferences,mapVisualOptions:{topoJsonUrl:I}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:I=>{o(I.target.value)},onBlur:()=>{var I;console.log("onBlur",r),d({...s.preferences,mapVisualOptions:{...(I=s.preferences)==null?void 0:I.mapVisualOptions,customTopoJsonUrl:r}})},value:r,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(Ct,{className:"h-9",options:i,value:((h=(p=s.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:h.objectKey)||"",label:"Map Object",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,objectKey:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(Ct,{className:"h-9",options:yl,value:((M=(v=s.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:M.projection)||"",label:"Projection",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projection:I}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(Ct,{className:"h-9",options:Nl,value:((b=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:b.colorScale)||"",label:"Select Color Scale",onValueChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,colorScale:I}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(Wn,{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:((F=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:F.projectionScale)||1,onChange:I=>{var L;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionScale:Number(I.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((k=(y=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:y.projectionOffset)==null?void 0:k[0])||0,onChange:I=>{var L,j,P,V;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[Number(I.target.value),((V=(P=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:P.projectionOffset)==null?void 0:V[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((T=(A=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:T[1])||0,onChange:I=>{var L,j,P,V;d({...s.preferences,mapVisualOptions:{...(L=s.preferences)==null?void 0:L.mapVisualOptions,projectionOffset:[((V=(P=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:P.projectionOffset)==null?void 0:V[0])||0,Number(I.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(vl,{})]})}const wl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function Tl(s){return s&&(wl[s]??s)}function Ra({value:s,onChange:a,showPosition:r=!1}){const o=s.colors||{};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Calculated as"}),e.jsxs(t.Select,{value:s.displayMode||"difference",onValueChange:d=>a({displayMode:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"difference",children:"Difference"}),e.jsx(t.SelectItem,{value:"percent_change",children:"Percent change"}),e.jsx(t.SelectItem,{value:"both",children:"Both"}),e.jsx(t.SelectItem,{value:"ratio",children:"Ratio (current ÷ comparison)"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"comparison-precision",className:"text-xs",children:"Percent/ratio precision"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"0 through 6 decimals"})]}),e.jsx(t.Input,{id:"comparison-precision",type:"number",min:0,max:6,step:1,value:s.precision??"",placeholder:"Default",onChange:d=>{if(d.target.value===""){a({precision:void 0});return}const l=Number(d.target.value);Number.isInteger(l)&&l>=0&&l<=6&&a({precision:l})},className:"h-7 w-16 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Indicator"}),e.jsxs(t.Select,{value:s.indicatorStyle||"arrow_badge",onValueChange:d=>a({indicatorStyle:d}),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"arrow_badge",children:"Arrow + badge"}),e.jsx(t.SelectItem,{value:"arrow",children:"Arrow"}),e.jsx(t.SelectItem,{value:"badge",children:"Badge"}),e.jsx(t.SelectItem,{value:"none",children:"None"})]})]})]}),r&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Position"}),e.jsxs(t.Select,{value:s.position||"right",onValueChange:d=>a({position:d}),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:"right",children:"Right"}),e.jsx(t.SelectItem,{value:"left",children:"Left"}),e.jsx(t.SelectItem,{value:"top",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-color",className:"text-xs",children:"Use sentiment color"}),e.jsx(t.Switch,{id:"comparison-color",size:"xs",checked:s.showColor!==!1,onCheckedChange:d=>a({showColor:d})})]}),s.showColor!==!1&&e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase","#16a34a"],["decrease","Decrease","#dc2626"],["neutral","No change","#6b7280"]].map(([d,l,i])=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:l}),e.jsx(n.ColorField,{value:Tl(o[d]||i),onChange:c=>a({colors:{...o,[d]:c||i}}),defaultValue:i,ariaLabel:`${l} color`,allowEmpty:!1})]},d))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"comparison-conditional-label",className:"text-xs",children:"Different label per direction"}),e.jsx(t.Switch,{id:"comparison-conditional-label",size:"xs",checked:s.conditionalLabel===!0,onCheckedChange:d=>a({conditionalLabel:d})})]}),s.conditionalLabel?e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase"],["decrease","Decrease"],["neutral","No change"]].map(([d,l])=>{var i;return e.jsx(t.Input,{"aria-label":`${l} label`,value:((i=s.conditionalLabels)==null?void 0:i[d])||l,onChange:c=>a({conditionalLabels:{...s.conditionalLabels,[d]:c.target.value}}),className:"h-7 text-xs"},d)})}):e.jsx(t.Input,{"aria-label":"Comparison label",value:s.labelName||"",onChange:d=>a({labelName:d.target.value}),placeholder:"Previous",className:"h-7 text-xs"})]})}function El(){var g,p,h,v,M;const s=t.useEditorStore(N=>N.card),{setCardPreferences:a}=t.useEditorActions(),r=n.useEffectiveEditorCardType(),o=((g=s.config)==null?void 0:g.metricColumns)||[],d=o.length===2&&(((p=s.config)==null?void 0:p.groupByColumns)||[]).length===0,l=o.some(N=>{var b;return((b=N.comparison)==null?void 0:b.mode)==="explicit"});if(!t.COMPARISON_PRESENTATION_SUPPORTED_CHART_TYPES.includes(r))return null;const c=((h=s.preferences)==null?void 0:h.comparisonPresentation)||{},u=N=>a({...s.preferences,comparisonPresentation:{...c,...N}}),m=r==="kpi"&&((v=s.preferences)==null?void 0:v.metricPairComparisonEnabled)===!0,x=l||m;return e.jsxs(n.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{htmlFor:"inherit-global-date-comparison",className:"text-xs",children:"Inherit Global Date comparison"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Author-set metric comparisons still take precedence."})]}),e.jsx(t.Switch,{id:"inherit-global-date-comparison",size:"xs",checked:((M=s.preferences)==null?void 0:M.inheritGlobalComparison)!==!1,onCheckedChange:N=>{const b={...s.preferences};N?delete b.inheritGlobalComparison:b.inheritGlobalComparison=!1,a(b)}})]}),r==="kpi"&&d&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"enable-metric-pair-comparison",className:"text-xs",children:"Enable metric comparison"}),e.jsx(t.Switch,{id:"enable-metric-pair-comparison",size:"xs",checked:m,onCheckedChange:N=>a({...s.preferences,metricPairComparisonEnabled:N})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{htmlFor:"show-explicit-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-explicit-comparison",size:"xs",checked:c.showComparison!==!1,onCheckedChange:N=>u({showComparison:N})})]}),x&&e.jsx(Ra,{value:c,onChange:u,showPosition:r==="kpi"&&d})]})]})}function Pa({cardType:s,queryResultColumns:a,focusSection:r,focusRequestId:o}){var z,U,G;const d=t.useEditorStore(q=>q.card),l=t.useEditorStore(q=>q.queryResultColumns),i=t.useEditorStore(q=>{var Q;return(Q=q.card)==null?void 0:Q.preferences}),c=i==null?void 0:i.tablePrefs,u=t.useEditorStore(q=>q.actions.setCardPreferences),m=t.useEditorStore(q=>q.actions.updateTableConditionalFormatting),x=((z=d.config)==null?void 0:z.metricColumns)||[],g=s??d.type,p=a??l,h=d.type===g?d:{...d,type:g},v=n.getTableConditionalFormattingColumnOptions(h,p),M=n.getTableOutputColumnOptions(h,p),N=n.supportsTableConditionalFormatting(g),b=g==="table",w=g==="table",F=((U=v[0])==null?void 0:U.value)||"",S=n.normalizeConditionalFormatting((G=i==null?void 0:i.tablePrefs)==null?void 0:G.conditionalFormatting),y=n.resolveTablePresentationStyle(c),k=n.isEligibleFlatTableTotalsCard(h),E=n.hasFlatTableTotalsBehavior(h),[A,T]=C.useState("style");C.useEffect(()=>{if(r==="style"){T("style");return}if(r==="columns"&&w){T("columns");return}r==="conditional-formatting"&&N&&T("conditional-formatting")},[w,N,o,r]);const I=x.some(q=>{var Q;return((Q=q.comparison)==null?void 0:Q.mode)==="explicit"}),L=(i==null?void 0:i.comparisonPresentation)||{},j=q=>{u({...i,comparisonPresentation:{...L,...q}})},P=q=>{m({version:1,rules:q})},V=q=>{u({...i,tablePrefs:{...c,density:q}})},f=q=>{u({...i,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,...q}}})},O=q=>{var Q;f({totals:{...(Q=c==null?void 0:c.tableStyle)==null?void 0:Q.totals,...q}})},D=q=>{var Q;u({...i,tablePrefs:{...c,tableStyle:{...c==null?void 0:c.tableStyle,totals:{...(Q=c==null?void 0:c.tableStyle)==null?void 0:Q.totals,enabled:q}}}})},R=(q,Q)=>{u({...i,tablePrefs:{...c,columnVisibility:n.setTableColumnVisibility(c==null?void 0:c.columnVisibility,q,Q)}})},B=()=>{u({...i,tablePrefs:{...c,columnVisibility:n.showAllTableColumns()}})},Y=()=>{u({...i,tablePrefs:{...c,density:n.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:n.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:n.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:k?E:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:n.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},_=I?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Comparison"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(t.Label,{htmlFor:"show-table-comparison",className:"text-xs",children:"Show comparison"}),e.jsx(t.Switch,{id:"show-table-comparison",size:"xs",checked:L.showComparison!==!1,onCheckedChange:q=>j({showComparison:q})})]}),e.jsx(Ra,{value:L,onChange:j})]}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:A,onValueChange:q=>T(q),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),w?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!N,children:"Conditional formatting"})]}),e.jsx(t.TabsContent,{value:"style",className:"mt-0",children:e.jsx(n.TablePresentationSettings,{style:y,onDensityChange:V,onStyleChange:f,showFullStyle:b,showBorderStyle:!1,totals:b&&k?{enabled:E,onEnabledChange:D,onStyleChange:O}:void 0,extraSection:_,onReset:b?Y:void 0})}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:w?e.jsx(n.TableColumnVisibilitySettings,{columns:M,columnVisibility:c==null?void 0:c.columnVisibility,onColumnVisibilityChange:R,onShowAllColumns:B}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Column visibility is available for table cards."})}),e.jsx(t.TabsContent,{value:"conditional-formatting",className:"mt-0",children:N?F?e.jsx(n.DataTableConditionalFormattingSettings,{columnId:F,availableColumns:v,conditionalRules:S.rules,onConditionalRulesChange:P,startRulesWithNoTrigger:!0}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Run the query to configure conditional formatting."}):e.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"Conditional formatting is available for table cards."})})]})})}function Il(){var d;const s=t.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=t.useEditorStore(l=>l.actions),r=(d=s==null?void 0:s.textVisualOptions)!=null&&d.isDynamicText?"dynamic":"static";function o(l){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsx(t.Tabs,{value:r,onValueChange:o,children:e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"static",children:"Static"}),e.jsx(t.TabsTrigger,{value:"dynamic",children:"Dynamic"})]})})}function Dl(){return e.jsxs("div",{className:"space-y-2 px-6 py-4",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Text mode"}),e.jsx(Il,{}),e.jsx("p",{className:"pt-1 text-[12px] leading-[1.55] text-muted-foreground",children:"Static text is authored inline. Dynamic text reads from the first cell of the card's query."})]})}function kl({color:s,onColorChange:a,onClose:r}){const[o,d]=C.useState(0),[l,i]=C.useState(100),[c,u]=C.useState(50),[m,x]=C.useState(s);C.useEffect(()=>{const N=Jn(s);if(N){const b=Xn(N.r,N.g,N.b);d(b.h),i(b.s),u(b.l),x(s)}},[s]);const g=N=>{d(N),h(N,l,c)},p=N=>{const b=N.currentTarget.getBoundingClientRect(),w=Math.max(0,Math.min(1,(N.clientX-b.left)/b.width)),F=Math.max(0,Math.min(1,(N.clientY-b.top)/b.height)),S=w*100,y=(1-F)*100;i(S),u(y),h(o,S,y)},h=(N,b,w)=>{const F=Al(N,b,w),S=Ml(F.r,F.g,F.b);x(S)},v=N=>{if(x(N),/^#[0-9A-Fa-f]{6}$/.test(N)){const b=Jn(N);if(b){const w=Xn(b.r,b.g,b.b);d(w.h),i(w.s),u(w.l)}}},M=()=>{/^#[0-9A-Fa-f]{6}$/.test(m)&&(a(m),r())};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(${o}, 100%, 50%)`},onClick:p,onMouseMove:N=>{N.buttons===1&&p(N)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${l}%`,top:`${100-c}%`,backgroundColor:m}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:N=>g(Number(N.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:m,onChange:N=>v(N.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:m}}),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:r,children:"Cancel"}),e.jsx(t.Button,{onClick:M,children:"OK"})]})]})}function Jn(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 Ml(s,a,r){return"#"+((1<<24)+(s<<16)+(a<<8)+r).toString(16).slice(1)}function Xn(s,a,r){s/=255,a/=255,r/=255;const o=Math.max(s,a,r),d=Math.min(s,a,r);let l=0,i=0;const c=(o+d)/2;if(o!==d){const u=o-d;switch(i=c>.5?u/(2-o-d):u/(o+d),o){case s:l=((a-r)/u+(a<r?6:0))/6;break;case a:l=((r-s)/u+2)/6;break;case r:l=((s-a)/u+4)/6;break}}return{h:Math.round(l*360),s:Math.round(i*100),l:Math.round(c*100)}}function Al(s,a,r){s/=360,a/=100,r/=100;let o,d,l;if(a===0)o=d=l=r;else{const i=(m,x,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(x-m)*6*g:g<.5?x:g<.6666666666666666?m+(x-m)*(.6666666666666666-g)*6:m),c=r<.5?r*(1+a):r+a-r*a,u=2*r-c;o=i(u,c,s+1/3),d=i(u,c,s),l=i(u,c,s-1/3)}return{r:Math.round(o*255),g:Math.round(d*255),b:Math.round(l*255)}}const Ll=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Fl(){var y,k,E,A,T,I,L,j,P,V;const s=t.useEditorStore(f=>f.card),a=t.useEditorStore(f=>{var O;return(O=f.card)==null?void 0:O.preferences}),r=n.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions(),l=C.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:i}=n.useEditorCardQuery(l),[c,u]=C.useState({}),[m,x]=C.useState(null),[g,p]=C.useState(null),h=C.useMemo(()=>{var R,B,Y,_,z,U,G;if(!(i!=null&&i.records)||i.records.length===0)return[];const f=r==="stackedBar"||r==="stackedLine",O=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",D=((R=s==null?void 0:s.config)==null?void 0:R.pivotByColumns)&&s.config.pivotByColumns.length>0;if((f||O)&&D){if(i.pivotSchema&&Array.isArray(i.pivotSchema)){const q=new Set;return i.pivotSchema.forEach(Q=>{Q.alias&&q.add(Q.alias)}),Array.from(q)}if(i.records.length>0){const q=i.records[0],Q=Object.keys(q),H=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(ge=>{H.add(ge.label||ge.name),H.add(ge.alias||ge.name)});const se=new Set;return(Y=s==null?void 0:s.config)!=null&&Y.metricColumns&&s.config.metricColumns.forEach(ge=>{const fe=ge.alias||ge.name;se.add(fe),se.add(`${fe}_count`),se.add(`${fe}_sum`),se.add(`${fe}_avg`),se.add(`${fe}_min`),se.add(`${fe}_max`);const Te=ge.entityName||ge.qualifiedEntityName;Te&&(se.add(`${Te}_${fe}`),se.add(`${Te}_${fe}_count`))}),Q.filter(ge=>!H.has(ge)&&!se.has(ge))}}if((O||f)&&!D&&((z=(_=s==null?void 0:s.config)==null?void 0:_.metricColumns)!=null&&z.length))return s.config.metricColumns.map(q=>q.alias||q.label||q.name);if((G=(U=s==null?void 0:s.config)==null?void 0:U.groupByColumns)!=null&&G.length){const q=s.config.groupByColumns[0],Q=q.label||q.name,H=new Set;return i.records.forEach(se=>{const ce=se[Q];ce!=null&&H.add(String(ce))}),Array.from(H)}return[]},[i,(y=s==null?void 0:s.config)==null?void 0:y.groupByColumns,(k=s==null?void 0:s.config)==null?void 0:k.pivotByColumns,(E=s==null?void 0:s.config)==null?void 0:E.metricColumns,r]),v=C.useMemo(()=>n.getDefaultChartColors(),[]);C.useEffect(()=>{const f={};h.forEach((O,D)=>{f[O]=n.getColorForValue(O,D,a==null?void 0:a.colorConfig)}),u(f)},[h,a==null?void 0:a.colorConfig,v]);const M=(f,O)=>{const D={...c,[f]:O};u(D);const R={...a||{},colorConfig:{segments:D}};o(R);const B={...s,preferences:R};d(B)},N=(f,O)=>{var z;const D=v[O%v.length],{[f]:R,...B}=((z=a==null?void 0:a.colorConfig)==null?void 0:z.segments)||{},Y={...a||{},colorConfig:{segments:B}};o(Y);const _={...s,preferences:Y};d(_),u(U=>({...U,[f]:D}))};if(!h.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((T=(A=s==null?void 0:s.config)==null?void 0:A.groupByColumns)==null?void 0:T.length)||((L=(I=s==null?void 0:s.config)==null?void 0:I.pivotByColumns)==null?void 0:L.length):(P=(j=s==null?void 0:s.config)==null?void 0:j.groupByColumns)==null?void 0:P.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const F=()=>{const f={...a||{},colorConfig:{segments:{}}};o(f);const O={...s,preferences:f};d(O);const D={};h.forEach((R,B)=>{D[R]=n.getColorForValue(R,B,void 0)}),u(D)},S=Object.keys(((V=a==null?void 0:a.colorConfig)==null?void 0:V.segments)||{}).length>0;return e.jsxs(n.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(n.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:F,children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:h.map((f,O)=>{const D=n.isDefaultColor(c[f],O),R=!D;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:m===f,onOpenChange:B=>x(B?f:null),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:c[f]}})}),e.jsx(t.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:v.slice(0,10).map((B,Y)=>e.jsxs("button",{className:t.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",c[f]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{M(f,B),x(null)},children:[Y===O%v.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:B})]},`default-${Y}`))})]}),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((B,Y)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",c[f]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{M(f,B),x(null)},children:e.jsx("span",{className:"sr-only",children:B})},`preset-${Y}`))})]}),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:()=>{p({value:f,color:c[f]}),x(null)},children:"Custom color"}),!D&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{N(f,O),x(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:f}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},f)})}),g&&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:()=>p(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(kl,{color:g.color,onColorChange:f=>{M(g.value,f),p(null)},onClose:()=>p(null)})})]})]})})]})}function ct({value:s,onSave:a,placeholder:r="",type:o="text",className:d=""}){const[l,i]=C.useState(s??""),[c,u]=C.useState(!1);C.useEffect(()=>{i(s??"")},[s]);const m=()=>{a(l),u(!1)},x=()=>{i(s??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${d}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:c?l:s??"",onChange:g=>{i(g.target.value),u(!0)},onFocus:()=>u(!0),onClick:g=>g.stopPropagation(),className:"h-8 text-xs",onPointerDown:g=>g.stopPropagation(),onKeyDown:g=>{g.stopPropagation(),g.key==="Enter"&&c&&l!==s?m():g.key==="Escape"&&x()},"aria-label":r||"Edit field"}),c&&l!==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:m,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:x,children:e.jsx(oe.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Ss({axis:s,label:a,type:r,config:o,onChange:d,defaultTitle:l,hidePosition:i}){var v,M,N,b,w,F,S,y,k,E,A,T,I,L;const c=n.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),u=(j,P)=>{d({...o??{},[j]:P})},m=(j,P)=>{var D,R,B,Y;const V=j==="enabled"&&P===!0,f=(D=o==null?void 0:o.name)==null?void 0:D.text,O=V&&!f&&l;d({...o??{},name:{...o==null?void 0:o.name,enabled:j==="enabled"?P:((R=o==null?void 0:o.name)==null?void 0:R.enabled)??!1,text:j==="text"?P:O?l:f,fontSize:j==="fontSize"?P:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:j==="fontWeight"?P:(Y=o==null?void 0:o.name)==null?void 0:Y.fontWeight}})},x=(j,P)=>{var V,f;d({...o??{},labels:{enabled:j==="enabled"?P:((V=o==null?void 0:o.labels)==null?void 0:V.enabled)??!0,rotation:j==="rotation"?P:(f=o==null?void 0:o.labels)==null?void 0:f.rotation}})},g=(j,P)=>{d({...o??{},scale:{...o==null?void 0:o.scale,[j]:P===""?"auto":Number(P)}})},p=s==="x"?["auto","top","bottom"]:["auto","left","right"],h=["auto","0","45","90","-45","-90"];return e.jsxs(n.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(n.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-[12px] 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:(o==null?void 0:o.enabled)!==!1,onCheckedChange:j=>u("enabled",j),onClick:j=>j.stopPropagation()})]}),e.jsxs(n.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(n.Checkbox,{id:`${s}-title-enabled`,checked:((v=o==null?void 0:o.name)==null?void 0:v.enabled)??!1,onCheckedChange:j=>m("enabled",j===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((M=o==null?void 0:o.name)==null?void 0:M.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(ct,{placeholder:`${a} title`,value:((N=o==null?void 0:o.name)==null?void 0:N.text)||"",onSave:j=>m("text",j),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(ct,{type:"number",placeholder:"12",value:String(((b=o==null?void 0:o.name)==null?void 0:b.fontSize)||12),onSave:j=>m("fontSize",Number(j)||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:((w=o==null?void 0:o.name)==null?void 0:w.fontWeight)||"normal",onValueChange:j=>m("fontWeight",j),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"})]})]})]})]})]})]}),!i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(t.Select,{value:(o==null?void 0:o.position)||"auto",onValueChange:j=>u("position",j),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":t.titleCase(j)},j))})]})]}),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:((F=o==null?void 0:o.labels)==null?void 0:F.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((S=o==null?void 0:o.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(((y=o==null?void 0:o.labels)==null?void 0:y.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(j=>e.jsx(t.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),r==="value"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"FORMAT"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Inherit from the bound metric by default."})]}),e.jsx(t.Switch,{size:"sm",checked:c==="override",onCheckedChange:j=>d({...o,formatMode:j?"override":"inherit"})})]}),c==="override"&&e.jsx(Xt,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:j=>d({...o,formatMode:"override",formatOptions:j}),showTitle:!1})]}),r==="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(ct,{type:"number",placeholder:"auto",value:((k=o==null?void 0:o.scale)==null?void 0:k.min)==="auto"||((E=o==null?void 0:o.scale)==null?void 0:E.min)===void 0?"":String(o.scale.min),onSave:j=>g("min",j),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(ct,{type:"number",placeholder:"auto",value:((A=o==null?void 0:o.scale)==null?void 0:A.max)==="auto"||((T=o==null?void 0:o.scale)==null?void 0:T.max)===void 0?"":String(o.scale.max),onSave:j=>g("max",j),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(ct,{type:"number",placeholder:"auto",value:((I=o==null?void 0:o.scale)==null?void 0:I.stepSize)==="auto"||((L=o==null?void 0:o.scale)==null?void 0:L.stepSize)===void 0?"":String(o.scale.stepSize),onSave:j=>g("stepSize",j),className:""})})]})]})]})]})]})}function ws(s,a,r){var l,i,c;if(s==="x"){const u=(i=(l=a==null?void 0:a.config)==null?void 0:l.groupByColumns)==null?void 0:i[0];return(u==null?void 0:u.label)||(u==null?void 0:u.name)||""}const o=((c=a==null?void 0:a.config)==null?void 0:c.metricColumns)||[],d=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const u=o.filter((m,x)=>{const g=d.find(p=>p.idx===x);return!g||g.yAxisId!=="y2"});return u.length===1&&(u[0].label||u[0].name)||""}if(s==="y2"){const u=o.filter((m,x)=>{const g=d.find(p=>p.idx===x);return(g==null?void 0:g.yAxisId)==="y2"});return u.length===1&&(u[0].label||u[0].name)||""}return""}function Rl(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),d=n.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(d))return null;const l=n.AxisConfigurator.getAxisInfo(d,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const i=(u,m)=>{let x;u==="x"?x="xAxisConfig":u==="y"?x="yAxisConfig":x="secondaryYAxisConfig";const g={...a||{},[x]:m};r(g);const p={...s,preferences:g};o(p)},c=l.hasY2Axis&&d==="combo";return e.jsxs(n.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] 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(n.AccordionContent,{className:"pt-2",children:e.jsxs(n.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[l.hasXAxis&&e.jsx(Ss,{axis:"x",label:"X-Axis",type:l.xAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"x"),a==null?void 0:a.xAxisConfig),onChange:u=>i("x",u),defaultTitle:ws("x",s,a)}),l.hasYAxis&&e.jsx(Ss,{axis:"y",label:c?"Y-Axis (Left)":"Y-Axis",type:l.yAxisType,config:n.mergeAxisConfig(n.getDefaultAxisConfig(d,"y"),a==null?void 0:a.yAxisConfig),onChange:u=>i("y",u),defaultTitle:ws("y",s,a)}),c&&e.jsx(Ss,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:n.mergeAxisConfig({enabled:!0,position:"right"},a==null?void 0:a.secondaryYAxisConfig),onChange:u=>i("y2",u),defaultTitle:ws("y2",s,a),hidePosition:!0})]})})]})}function Pl(){const s=t.useEditorStore(g=>g.card),a=n.useEffectiveEditorCardType(),r=t.useEditorStore(g=>{var p,h,v,M;return(M=(v=(h=(p=g.card)==null?void 0:p.preferences)==null?void 0:h.chartOptions)==null?void 0:v.plugins)==null?void 0:M.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!n.chartSupportsLegend(a))return null;const d=n.getDefaultLegendConfig(a),l=(d==null?void 0:d.display)??!0,i=(d==null?void 0:d.position)??"top",c=(d==null?void 0:d.align)??"center",u=(g,p)=>{const h={...r,[g]:p};o(h)},m=["top","bottom","left","right"],x=["start","center","end"];return e.jsxs(n.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(n.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:(r==null?void 0:r.display)??l,onCheckedChange:g=>u("display",g)})]}),((r==null?void 0:r.display)??l)&&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:(r==null?void 0:r.position)||i,onValueChange:g=>u("position",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(t.Select,{value:(r==null?void 0:r.align)||c,onValueChange:g=>u("align",g),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(g=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:t.titleCase(g)},g))})]})]})]})]})})]})}function Ol(){var P,V,f,O,D,R,B;const s=t.useEditorStore(Y=>Y.card),a=n.useEffectiveEditorCardType(),r=t.useEditorStore(Y=>{var _,z;return(z=(_=Y.card)==null?void 0:_.preferences)==null?void 0:z.dataLabelsConfig}),o=t.useEditorStore(Y=>{var _;return(_=Y.card)==null?void 0:_.preferences}),{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!n.chartSupportsDataLabels(a))return null;const i=a==="bullet"?((P=o==null?void 0:o.bulletConfig)==null?void 0:P.orientation)??(((V=o==null?void 0:o.chartOptions)==null?void 0:V.indexAxis)==="x"?"vertical":"horizontal"):void 0,c=i!=null?i==="horizontal":((f=o==null?void 0:o.chartOptions)==null?void 0:f.indexAxis)==="y",u=a==="stackedBar"||a==="stackedLine",m=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel",x=a==="bubble"||a==="scatter",g=(D=(O=o==null?void 0:o.chartOptions)==null?void 0:O.plugins)==null?void 0:D.datalabels,p=(g==null?void 0:g.display)!==!1&&((g==null?void 0:g.anchor)||(g==null?void 0:g.align)),h=n.getDefaultDataLabelsConfig(a,s.preferences),v=r??h,M=(h==null?void 0:h.enabled)??p??!1,N=(r==null?void 0:r.enabled)!==void 0?r.enabled:M,b=(Y,_)=>{const G={...h??{},...r??{},[Y]:_};Y==="enabled"&&(G.display=_,_&&x&&!G.position&&(G.position="bottom")),Y==="position"&&x&&(G.position="bottom"),Y==="formatMode"&&_==="inherit"&&(G.format=void 0,G.formatOptions=void 0);const q={...s.preferences||{},dataLabelsConfig:G};d(q);const Q={...s,preferences:q};l(Q)},w=(Y,_)=>{const z=r??{},G={...h??{},...z,font:{...z.font||{},[Y]:_}},q={...s.preferences||{},dataLabelsConfig:G};d(q);const Q={...s,preferences:q};l(Q)},F=()=>{const Y=a;return Y==="stackedBar"||Y==="stackedLine"||Y==="pie"||Y==="doughnut"?"center":c?"right":"top"},S=a!=="treemap"&&a!=="heatmap",y=a!=="treemap",k=F();let E=[];if(S)if(x)E=["bottom"];else if(u||m)E=["center"];else{const Y=c?["center","left","right"]:["center","top","bottom"];E=["auto",...a==="bullet"?Y:Y.filter(z=>z!==k),"custom"]}const A=()=>t.titleCase(k),T=["center","start","end"],I=["center","start","end","top","bottom"],L=(v==null?void 0:v.formatMode)||(v!=null&&v.format&&!["auto"].includes(v.format)?"override":"inherit"),j=(v==null?void 0:v.format)==="none";return e.jsxs(n.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(n.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,onCheckedChange:Y=>b("enabled",Y)})]}),N&&e.jsxs(e.Fragment,{children:[S&&!u&&!m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:x?(v==null?void 0:v.position)||"bottom":(v==null?void 0:v.position)||"auto",onValueChange:Y=>b("position",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:Y==="auto"?A():Y==="custom"?"Custom (Advanced)":t.titleCase(Y)},Y))})]})]}),u&&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:(r==null?void 0:r.showTotal)??!1,onCheckedChange:Y=>b("showTotal",Y)})]}),(v==null?void 0:v.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:(v==null?void 0:v.anchor)||"center",onValueChange:Y=>b("anchor",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:T.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:t.titleCase(Y)},Y))})]})]}),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((v==null?void 0:v.align)||"center"),onValueChange:Y=>b("align",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:I.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:t.titleCase(Y)},Y))})]})]})]}),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:L==="override",onCheckedChange:Y=>b("formatMode",Y?"override":"inherit")})]}),L==="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:j,onCheckedChange:Y=>{const _=r??{},U={...h??{},..._,formatMode:"override",format:Y?"none":void 0,formatOptions:Y?void 0:_.formatOptions},G={...s.preferences||{},dataLabelsConfig:U};d(G),l({...s,preferences:G})}})]}),!j&&e.jsx(Xt,{formatOptions:(v==null?void 0:v.formatOptions)||{},onFormatOptionsChange:Y=>{const U={...h??{},...r??{},formatMode:"override",format:Y.type&&Y.type!=="auto"?Y.type:void 0,formatOptions:Y},G={...s.preferences||{},dataLabelsConfig:U};d(G),l({...s,preferences:G})},showTitle:!1})]})]}),y&&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(ct,{type:"number",placeholder:"12",value:String(((R=v==null?void 0:v.font)==null?void 0:R.size)||12),onSave:Y=>w("size",Number(Y)),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:((B=v==null?void 0:v.font)==null?void 0:B.weight)||"normal",onValueChange:Y=>w("weight",Y),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:(v==null?void 0:v.color)==="auto"||!(v!=null&&v.color)?"auto":"custom",onValueChange:Y=>{Y==="auto"&&b("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(ct,{type:"number",placeholder:"0",value:String((v==null?void 0:v.rotation)||0),onSave:Y=>b("rotation",Number(Y)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Bl(){var l;const s=t.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.type}),a=t.useEditorStore(i=>{var c;return(c=i.card)==null?void 0:c.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((l=a==null?void 0:a.chartOptions)==null?void 0:l.treemapColorMode)??"branch",d=i=>{const c={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:i}};r(c)};return e.jsxs(n.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(n.RadioGroup,{value:o,onValueChange:i=>d(i??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.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(n.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 Vl=Object.keys(n.HEATMAP_PRESET_PALETTES);function _l(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",d=(a==null?void 0:a.heatmapConfig)||{},l=d.colorPalette??"green",i=d.legendPosition??"bottom",c=C.useMemo(()=>d.colorRange&&d.colorRange[0]&&d.colorRange[1]?[d.colorRange[0],d.colorRange[1]]:[...n.DEFAULT_HEATMAP_CUSTOM_RANGE],[d.colorRange]),u=p=>{const h={...d,...p};h.colorPalette!=="custom"?delete h.colorRange:(!h.colorRange||!h.colorRange[0]||!h.colorRange[1])&&(h.colorRange=[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...a||{},heatmapConfig:h})},m=p=>{u({colorPalette:p,colorRange:p==="custom"?d.colorRange??[...n.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},x=(p,h)=>{const v=[...c];v[p]=h,u({colorPalette:"custom",colorRange:v})},g=p=>{u({legendPosition:p})};return o?e.jsxs(n.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(n.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(n.RadioGroup,{value:l,onValueChange:p=>m(p??"blue"),className:"space-y-3",children:[Vl.map(p=>{const h=n.HEATMAP_PRESET_PALETTES[p];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`heatmap-${p}`,value:p}),e.jsxs(t.Label,{htmlFor:`heatmap-${p}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${h.start}, ${h.end})`}})]})]},p)}),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(n.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),l==="custom"&&e.jsxs("div",{className:"flex flex-col gap-2 pl-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[0],onChange:p=>x(0,p??"#000000"),ariaLabel:"Start color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Start color"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.ColorField,{value:c[1],onChange:p=>x(1,p??"#000000"),ariaLabel:"End color",allowEmpty:!1}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"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:i,onValueChange:p=>g(p??"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(p=>e.jsx(t.SelectItem,{value:p,className:"text-xs",children:p[0].toUpperCase()+p.slice(1)},p))})]})]})]})]}):null}const Zn=["poor","satisfactory","good"];function ea(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 Yl(){var P,V;const s=t.useEditorStore(f=>f.card.preferences),a=t.useEditorStore(f=>f.card),r=t.useEditorStore(f=>f.isDevMode),{setCardPreferences:o,setChartOrientation:d}=t.useEditorActions(),l=C.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),c=Ke.hasValidCardConfig(a==null?void 0:a.config)&&!r,[u,m]=C.useState(l.showRanges??!1),[x,g]=C.useState(l.rangesArePercentages??!1),p=l.disableAutoComparative?!1:l.comparativeMetricKey!==void 0||!c,[h,v]=C.useState(p);C.useEffect(()=>{m(l.showRanges??!1)},[l.showRanges]),C.useEffect(()=>{g(l.rangesArePercentages??!1)},[l.rangesArePercentages]);const M=l.targetValue===void 0?"":String(l.targetValue);C.useEffect(()=>{const f=l.disableAutoComparative?!1:l.comparativeMetricKey!==void 0||!c;v(f)},[l.disableAutoComparative,l.comparativeMetricKey,c]);const N=C.useMemo(()=>{var f,O;return((O=(f=a==null?void 0:a.config)==null?void 0:f.metricColumns)==null?void 0:O.map(D=>{const R=D.label||D.name||D.alias||"";return{value:R,label:R}}))||[]},[(P=a==null?void 0:a.config)==null?void 0:P.metricColumns]);C.useEffect(()=>{var z,U;if(!s||N.length===0)return;const f={};let O=!1;const D=(z=N[1])==null?void 0:z.value;!l.targetMetricKey&&D&&(f.targetMetricKey=D,O=!0);const R=(U=N[2])==null?void 0:U.value;!l.comparativeMetricKey&&!l.disableAutoComparative&&R&&(f.comparativeMetricKey=R,O=!0);const B=N.slice(3),Y={...l.rangeKeys||{}};let _=!1;if(Zn.forEach((G,q)=>{!Y[G]&&B[q]&&(Y[G]=B[q].value,_=!0)}),_&&(f.rangeKeys=Y,O=!0,l.showRanges===void 0&&(f.showRanges=!0)),O){const G=ea({...l,...f});o({...s,bulletConfig:G})}},[N,l,s,o]);const b=f=>{const O=ea({...l,...f});o({...s,bulletConfig:O})},w=(f,O)=>{const D={...l.rangeKeys||{},[f]:O.trim()};O.trim()||delete D[f],b({rangeKeys:Object.keys(D).length>0?D:void 0})},F=(f,O)=>{const D=O===""?void 0:Number(O),R={...l.ranges||{}};D===void 0||Number.isNaN(D)?delete R[f]:R[f]=D,b({ranges:Object.keys(R).length?R:void 0})},S=f=>{if(f===""){b({targetValue:void 0});return}const O=Number(f);b({targetValue:Number.isNaN(O)?void 0:O})},y=(f,O)=>{const D=O.trim(),R={...l.rangeLabels||{}};D?R[f]=D:delete R[f],b({rangeLabels:Object.keys(R).length>0?R:void 0})},k=f=>{m(f),b({showRanges:f})},E=f=>{g(f),b({rangesArePercentages:f})},A=l.orientation||(((V=s==null?void 0:s.chartOptions)==null?void 0:V.indexAxis)==="y"?"horizontal":"vertical"),T=f=>{b({orientation:f}),d(f==="horizontal"?"y":"x")},I=[{value:"__none",label:"None"},...N.map(f=>({value:f.value,label:f.label}))],L=I,j=f=>{if(v(f),!f){b({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!c){b({disableAutoComparative:!1});return}if(l.comparativeMetricKey)b({disableAutoComparative:!1});else{const O=N.find(D=>D.value!==l.targetMetricKey);b({comparativeMetricKey:O==null?void 0:O.value,disableAutoComparative:!1})}};return e.jsxs(n.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(n.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:A,onValueChange:f=>T(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(t.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(t.Select,{value:l.targetMetricKey||"__none",onValueChange:f=>b({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"}),N.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:f.label},f.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),c?e.jsxs(t.Select,{value:l.comparativeMetricKey||"__none",onValueChange:f=>b({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:I.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:h,onCheckedChange:f=>j(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(at,{type:"number",className:"h-8 text-xs",value:M,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:u,onCheckedChange:k})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:x,disabled:!u,onChange:f=>E(f.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),u&&e.jsx("div",{className:"space-y-3",children:Zn.map(f=>{var O,D,R,B,Y;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(at,{placeholder:`Display label (${f})`,value:((O=l.rangeLabels)==null?void 0:O[f])||"",onCommit:_=>y(f,_),className:"h-8 text-xs"})]}),c?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[f," COLUMN"]}),e.jsxs(t.Select,{value:((D=l.rangeKeys)==null?void 0:D[f])||"__none",onValueChange:_=>{_==="__none"?w(f,""):w(f,_)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:L.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(at,{placeholder:"Column key",value:((R=l.rangeKeys)==null?void 0:R[f])||"",onCommit:_=>w(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(at,{type:"number",placeholder:x?"0.80":"Static value",value:((B=l.ranges)==null?void 0:B[f])===void 0?"":String((Y=l.ranges)==null?void 0:Y[f]),onCommit:_=>F(f,_),className:"h-8 text-xs"})]})]},f)})})]})]})]})}function ta(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 zl(){var y,k,E,A,T,I,L,j,P,V,f,O;const s=t.useEditorStore(D=>D.card.preferences),a=t.useEditorStore(D=>D.card),r=n.useEffectiveEditorCardType(),o=t.useEditorStore(D=>D.isDevMode),{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions(),i=r==="bubble",c=r==="scatter",u=C.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),x=Ke.hasValidCardConfig(a==null?void 0:a.config)&&!o,g=C.useMemo(()=>{var D,R;return((R=(D=a==null?void 0:a.config)==null?void 0:D.metricColumns)==null?void 0:R.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(y=a==null?void 0:a.config)==null?void 0:y.metricColumns]),p=C.useMemo(()=>{var D,R;return((R=(D=a==null?void 0:a.config)==null?void 0:D.groupByColumns)==null?void 0:R.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(k=a==null?void 0:a.config)==null?void 0:k.groupByColumns]),h=C.useMemo(()=>u.enableGrouping!==void 0?u.enableGrouping:!o&&p.length>=2,[u.enableGrouping,o,p.length]),[v,M]=C.useState(h);C.useEffect(()=>{M(h)},[h]);const N=D=>{const R={...s||{},bubbleScatterConfig:D};d(R),a&&l({...a,preferences:R})},b=D=>{d(D),a&&l({...a,preferences:D})};C.useEffect(()=>{if(!s||g.length===0)return;const D={};let R=!1;if(!u.xMetricKey&&g[0]&&(D.xMetricKey=g[0].value,R=!0),!u.yMetricKey&&g[1]&&(D.yMetricKey=g[1].value,R=!0),i&&!u.radiusMetricKey&&g[2]&&(D.radiusMetricKey=g[2].value,R=!0),!u.labelKey&&p[0]&&(D.labelKey=p[0].value,R=!0),h&&!u.groupKey&&p[1]&&(D.groupKey=p[1].value,D.enableGrouping=!0,R=!0),R){const B=ta({...u,...D});N(B)}},[g,p,u,s,d,i,h]);const w=D=>{const R=ta({...u,...D});N(R)},F=D=>{M(D),w({enableGrouping:D,groupKey:D?u.groupKey:void 0})};if(!i&&!c)return null;const S=i?n.Circle:n.ChartScatter;return e.jsxs(n.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[i?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(n.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"}),x?e.jsxs(t.Select,{value:u.labelKey||"",onValueChange:D=>w({labelKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:p.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for labels",value:u.labelKey||"",onCommit:D=>w({labelKey:D})})]}),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:v,onCheckedChange:F})]}),v&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),x?e.jsxs(t.Select,{value:u.groupKey||"",onValueChange:D=>w({groupKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:p.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:u.groupKey||"",onCommit:D=>w({groupKey:D})})]})]}),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"}),x?e.jsxs(t.Select,{value:u.xMetricKey||"",onValueChange:D=>w({xMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:u.xMetricKey||"",onCommit:D=>w({xMetricKey:D})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),x?e.jsxs(t.Select,{value:u.yMetricKey||"",onValueChange:D=>w({yMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:u.yMetricKey||"",onCommit:D=>w({yMetricKey:D})})]}),i&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),x?e.jsxs(t.Select,{value:u.radiusMetricKey||"",onValueChange:D=>w({radiusMetricKey:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:g.map(D=>e.jsx(t.SelectItem,{value:D.value,children:D.label},D.value))})]}):e.jsx(at,{className:"h-8 text-xs",placeholder:"Column name for radius",value:u.radiusMetricKey||"",onCommit:D=>w({radiusMetricKey:D})})]})]}),i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(t.Select,{value:u.radiusScale||"sqrt",onValueChange:D=>w({radiusScale:D}),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"})]})]})]}),u.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(at,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((E=u.minRadius)==null?void 0:E.toString())||"",onCommit:D=>w({minRadius:D?Number(D):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(at,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((A=u.maxRadius)==null?void 0:A.toString())||"",onCommit:D=>w({maxRadius:D?Number(D):void 0})})]})]}),u.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Fixed Radius: ",u.fixedRadius||10]}),e.jsx(n.Slider,{value:[u.fixedRadius||10],onValueChange:([D])=>w({fixedRadius:D}),min:3,max:30,step:1,className:"py-2"})]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(t.Label,{className:"text-xs",children:["Point Size: ",u.fixedRadius||5]}),e.jsx(n.Slider,{value:[u.fixedRadius||5],onValueChange:([D])=>w({fixedRadius:D}),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:((I=(T=s==null?void 0:s.xAxisConfig)==null?void 0:T.name)==null?void 0:I.enabled)??!1,onCheckedChange:D=>{var Y,_,z,U;const R=u.xMetricKey||"X Axis",B=u.yMetricKey||"Y Axis";b({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:D,text:((_=(Y=s==null?void 0:s.xAxisConfig)==null?void 0:Y.name)==null?void 0:_.text)||R}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:D,text:((U=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:U.text)||B}}})}})]}),((j=(L=s==null?void 0:s.xAxisConfig)==null?void 0:L.name)==null?void 0:j.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(at,{className:"h-8 text-xs",placeholder:u.xMetricKey||"X Axis",value:((V=(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name)==null?void 0:V.text)||"",onCommit:D=>{var R;b({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(R=s==null?void 0:s.xAxisConfig)==null?void 0:R.name,enabled:!0,text:D||u.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(at,{className:"h-8 text-xs",placeholder:u.yMetricKey||"Y Axis",value:((O=(f=s==null?void 0:s.yAxisConfig)==null?void 0:f.name)==null?void 0:O.text)||"",onCommit:D=>{var R;b({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(R=s==null?void 0:s.yAxisConfig)==null?void 0:R.name,enabled:!0,text:D||u.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const ql=[{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 $l(){const s=t.useEditorStore(p=>p.card),a=t.useEditorStore(p=>{var h;return(h=p.card)==null?void 0:h.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",d=(a==null?void 0:a.funnelConfig)||{},l=d.percentMode??"percentOfTotal",i=d.shrinkFraction??1,c=d.labelThreshold??0,u=p=>{const h={...d,...p};r({...a||{},funnelConfig:h})},m=p=>{u({percentMode:p})},x=p=>{u({shrinkFraction:p[0]})},g=p=>{u({labelThreshold:p[0]})};return o?e.jsxs(n.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(n.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(n.RadioGroup,{value:l,onValueChange:p=>m(p),className:"space-y-2",children:ql.map(p=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(n.RadioGroupItem,{id:`funnel-${p.value}`,value:p.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${p.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.description})]})]},p.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(n.Slider,{value:[i],onValueChange:x,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(i*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(n.Slider,{value:[c],onValueChange:g,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:c===0?"Showing all labels":`Hide labels below ${c}%`})]})]})]}):null}function ds(){const s=t.useEditorStore(i=>i.card),{data:a,comparisonMetadata:r}=n.useEditorCardQuery(s),{keys:o}=n.getKeys((a==null?void 0:a.records)||[],r),d=o.slice(1).filter(i=>!Ke.METADATA_KEYS.includes(i));let l=d;if(["stackedBar","stackedLine"].includes(s.type)){const i=n.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:o[0],pivotKey:o[1],valueKey:o[2]}),{keys:c}=n.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:o.slice(0,1),keys:o,defaultMetricKeys:d}}const Kl=[{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"}],Ul=[{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)"}],Hl=["center","start","end"],Gl=["center","start","end","top","bottom"];function us({config:s,onChange:a,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:d,showAppearance:l=!0}){var v,M,N,b,w,F;const i=d??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),c=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],u=(S,y)=>{const k={...s,[S]:y};a(k)},m=(S,y)=>{const k={...s,font:{...(s==null?void 0:s.font)||{},[S]:y}};a(k)},x=(S,y)=>{const k={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[S]:y}};a(k)},g=()=>r?"Right":"Top",p=s||{},h=p.format||(o?"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:p.position||"auto",onValueChange:S=>u("position",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:i.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"?g():S==="custom"?"Custom (Advanced)":t.titleCase(S)},S))})]})]}),p.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:p.anchor||"center",onValueChange:S=>u("anchor",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Hl.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(p.align||"center"),onValueChange:S=>u("align",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Gl.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:h,onValueChange:S=>u("format",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(S=>e.jsx(t.SelectItem,{value:S,className:"text-xs",children:S==="auto"&&o?"Auto (Use Axis)":S==="none"?"None (Raw Value)":t.titleCase(S)},S))})]})]}),!["auto","none"].includes(h)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(h)&&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(ct,{type:"number",placeholder:"0",value:String(((v=p.formatOptions)==null?void 0:v.decimalPlaces)??(h==="currency"?2:h==="percent"?1:0)),onSave:S=>x("decimalPlaces",Number(S)),className:""})})]}),h==="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:((M=p.formatOptions)==null?void 0:M.currency)||"USD",onValueChange:S=>x("currency",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Kl.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]}),["number","currency"].includes(h)&&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:((N=p.formatOptions)==null?void 0:N.useSuffix)??!1,onCheckedChange:S=>x("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:((b=p.formatOptions)==null?void 0:b.locale)||"en-US",onValueChange:S=>x("locale",S),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ul.map(S=>e.jsx(t.SelectItem,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]})]}),l&&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(ct,{type:"number",placeholder:"12",value:String(((w=p.font)==null?void 0:w.size)||12),onSave:S=>m("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:((F=p.font)==null?void 0:F.weight)||"normal",onValueChange:S=>m("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:p.color==="auto"||!p.color?"auto":"custom",onValueChange:S=>{S==="auto"&&u("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(ct,{type:"number",placeholder:"0",value:String(p.rotation||0),onSave:S=>u("rotation",Number(S)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Ql=[{type:"bar",icon:n.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:n.ChartLine,label:"Line"}],Wl=[0,1,2,3,4,5,6,8,10],Jl=[{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 │"}],Xl=[{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 r;return(r=a.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(n.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(ei,{})})]})}function ei(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(ti,{metricKey:a,idx:r},a))})}function ti({metricKey:s,idx:a}){var b;const[r,o]=C.useState(!1),d=t.useEditorStore(w=>{var F;return(F=w.card)==null?void 0:F.preferences}),l=t.useEditorStore(w=>{var F,S;return(S=(F=w.card)==null?void 0:F.preferences)==null?void 0:S.datasetOptions}),i=l==null?void 0:l.find(w=>w.idx===a),{setCardPreferences:c}=t.useEditorStore(w=>w.actions),u=(i==null?void 0:i.type)||"bar",m=(i==null?void 0:i.yAxisId)||"y",x=((b=i==null?void 0:i.dataLabels)==null?void 0:b.enabled)??!1,g=u==="line"?n.ChartLine:n.ChartColumnIncreasing;function p(w){const F={idx:a,type:u,yAxisId:m,dataLabels:i==null?void 0:i.dataLabels,...w};if(!i)c({...d||{},datasetOptions:[...l||[],F]});else{const S=l==null?void 0:l.map(y=>y.idx===a?{...y,...F}:y);c({...d||{},datasetOptions:S})}}function h(w){p({type:w})}function v(w){p({yAxisId:w})}function M(w){p({dataLabels:{...i==null?void 0:i.dataLabels,enabled:w}})}function N(w){p({dataLabels:w})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(g,{className:"h-3 w-3"}),u==="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:m==="y2"?"Y2":"Y1"})]})]})}),e.jsx(n.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:Ql.map(({type:w,icon:F,label:S})=>{const y=u===w;return e.jsxs("button",{onClick:()=>h(w),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",y?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(F,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:S})]},w)})})]}),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:m,onValueChange:w=>v(w),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)"})]})]})]})]}),u==="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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:w=>p({lineStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(({value:w,label:F})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:F},w))})]})]}),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((i==null?void 0:i.pointRadius)??3),onValueChange:w=>p({pointRadius:Number(w)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(w=>e.jsx(t.SelectItem,{value:String(w),className:"text-xs",children:w===0?"None":w},w))})]})]}),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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:w=>p({pointStyle:w}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(({value:w,label:F})=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:F},w))})]})]})]})]}),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:M})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:N,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ts=[{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"}],si=[0,1,2,3,4,5,6,8,10],ni=[{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 │"}],ai=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ri(s){return s==null?"origin":s===!1?"false":s}function oi(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(n.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(li,{})})]})}function li(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(ii,{metricKey:a,idx:r},a))})}function ii({metricKey:s,idx:a}){var M;const[r,o]=C.useState(!1),d=t.useEditorStore(N=>{var b;return(b=N.card)==null?void 0:b.preferences}),l=t.useEditorStore(N=>{var b,w;return(w=(b=N.card)==null?void 0:b.preferences)==null?void 0:w.datasetOptions}),i=l==null?void 0:l.find(N=>N.idx===a),{setCardPreferences:c}=t.useEditorStore(N=>N.actions),u=ri(i==null?void 0:i.fill),m=((M=i==null?void 0:i.dataLabels)==null?void 0:M.enabled)??!1,x=Ts.find(N=>N.value===u)||Ts[0];function g(N){const b={idx:a,fill:u,dataLabels:i==null?void 0:i.dataLabels,...N};if(!i)c({...d||{},datasetOptions:[...l||[],b]});else{const w=l==null?void 0:l.map(F=>F.idx===a?{...F,...b}:F);c({...d||{},datasetOptions:w})}}function p(N){g({fill:N==="false"?!1:N})}function h(N){g({dataLabels:{...i==null?void 0:i.dataLabels,enabled:N}})}function v(N){g({dataLabels:N})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(n.ChartArea,{className:"h-3 w-3"}),x.label.split(" ")[0]]})})]})}),e.jsx(n.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:u,onValueChange:N=>p(N),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ts.map(N=>e.jsx(t.SelectItem,{value:N.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:N.label})})},N.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:(i==null?void 0:i.lineStyle)||"solid",onValueChange:N=>g({lineStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ai.map(({value:N,label:b})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:b},N))})]})]}),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((i==null?void 0:i.pointRadius)??3),onValueChange:N=>g({pointRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:si.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":N},N))})]})]}),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:(i==null?void 0:i.pointStyle)||"circle",onValueChange:N=>g({pointStyle:N}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ni.map(({value:N,label:b})=>e.jsx(t.SelectItem,{value:N,className:"text-xs",children:b},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 text-muted-foreground",children:"Data Labels"}),e.jsx(t.Switch,{size:"sm",checked:m,onCheckedChange:h})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:v,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const ci=[0,1,2,3,4,5,6,8,10],di=[{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 │"}],Es=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ui(){return t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type})!=="line"?null:e.jsxs(n.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(mi,{})})]})}function mi(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(xi,{metricKey:a,idx:r},a))})}function xi({metricKey:s,idx:a}){var N;const[r,o]=C.useState(!1),d=t.useEditorStore(b=>{var w;return(w=b.card)==null?void 0:w.preferences}),l=t.useEditorStore(b=>{var w,F;return(F=(w=b.card)==null?void 0:w.preferences)==null?void 0:F.datasetOptions}),i=l==null?void 0:l.find(b=>b.idx===a),{setCardPreferences:c}=t.useEditorStore(b=>b.actions),u=(i==null?void 0:i.lineStyle)||"solid",m=(i==null?void 0:i.pointRadius)??3,x=(i==null?void 0:i.pointStyle)||"circle",g=((N=i==null?void 0:i.dataLabels)==null?void 0:N.enabled)??!1,p=Es.find(b=>b.value===u)||Es[0];function h(b){const w={idx:a,lineStyle:u,pointRadius:m,pointStyle:x,dataLabels:i==null?void 0:i.dataLabels,...b};if(!i)c({...d||{},datasetOptions:[...l||[],w]});else{const F=l==null?void 0:l.map(S=>S.idx===a?{...S,...w}:S);c({...d||{},datasetOptions:F})}}function v(b){h({dataLabels:{...i==null?void 0:i.dataLabels,enabled:b}})}function M(b){h({dataLabels:b})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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(Rr,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(n.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:u,onValueChange:b=>h({lineStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Es.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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(m),onValueChange:b=>h({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:ci.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:x,onValueChange:b=>h({pointStyle:b}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:di.map(({value:b,label:w})=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:w},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:g,onCheckedChange:v})]}),g&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:i==null?void 0:i.dataLabels,onChange:M,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const hi=[0,2,4,6,8,10,12,16,20];function pi(){const s=t.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(n.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(n.AccordionContent,{className:"pt-2",children:e.jsx(fi,{})})]})}function fi(){const{transformedMetricKeys:s}=ds();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,r)=>e.jsx(gi,{metricKey:a,idx:r},a))})}function gi({metricKey:s,idx:a}){var v;const[r,o]=C.useState(!1),d=t.useEditorStore(M=>{var N;return(N=M.card)==null?void 0:N.type}),l=t.useEditorStore(M=>{var N;return(N=M.card)==null?void 0:N.preferences}),i=t.useEditorStore(M=>{var N,b;return(b=(N=M.card)==null?void 0:N.preferences)==null?void 0:b.datasetOptions}),c=i==null?void 0:i.find(M=>M.idx===a),{setCardPreferences:u}=t.useEditorStore(M=>M.actions),m=(c==null?void 0:c.borderRadius)??0,x=((v=c==null?void 0:c.dataLabels)==null?void 0:v.enabled)??!1;function g(M){const N={idx:a,borderRadius:m,dataLabels:c==null?void 0:c.dataLabels,...M};if(!c)u({...l||{},datasetOptions:[...i||[],N]});else{const b=i==null?void 0:i.map(w=>w.idx===a?{...w,...N}:w);u({...l||{},datasetOptions:b})}}function p(M){g({dataLabels:{...c==null?void 0:c.dataLabels,enabled:M}})}function h(M){g({dataLabels:M})}return e.jsx(n.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(n.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(Ye.ChevronRight,{className:t.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",r&&"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:m>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:",m]})})]})}),e.jsx(n.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(m),onValueChange:M=>g({borderRadius:Number(M)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hi.map(M=>e.jsx(t.SelectItem,{value:String(M),className:"text-xs",children:M===0?"None":`${M}px`},M))})]})]})})]}),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:p})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(us,{config:c==null?void 0:c.dataLabels,onChange:h,isHorizontal:d==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const bi=[0,1,2,3,4,5,6,8,10],ji=[{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 │"}],vi=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function yi(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.preferences}),r=n.useEffectiveEditorCardType(),o=a==null?void 0:a.lineStyleConfig,{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const i=(c,u)=>{const m={...a||{},lineStyleConfig:{...o,[c]:u}};d(m),l({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(n.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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:c=>i("lineStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:vi.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.pointRadius)??3),onValueChange:c=>i("pointRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bi.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":c},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(t.Select,{value:(o==null?void 0:o.pointStyle)||"circle",onValueChange:c=>i("pointStyle",c),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ji.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]})]})})]})}const Ci=[0,2,4,6,8,10,12,16,20],Ni=[{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%"}],Si=[{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 wi(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.preferences}),r=n.useEffectiveEditorCardType(),o=a==null?void 0:a.barStyleConfig,{setCardPreferences:d,updateCardInFrame:l}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const i=(c,u)=>{const m={...a||{},barStyleConfig:{...o,[c]:u}};d(m),l({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] 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(n.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((o==null?void 0:o.borderRadius)??0),onValueChange:c=>i("borderRadius",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ci.map(c=>e.jsx(t.SelectItem,{value:String(c),className:"text-xs",children:c===0?"None":`${c}px`},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.barPercentage)??.9),onValueChange:c=>i("barPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ni.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(t.Select,{value:String((o==null?void 0:o.categoryPercentage)??.8),onValueChange:c=>i("categoryPercentage",Number(c)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Si.map(({value:c,label:u})=>e.jsx(t.SelectItem,{value:c,className:"text-xs",children:u},c))})]})]})]})})]})}function Ti(){const s=t.useEditorStore(r=>{var o,d;return(d=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:d.sortChart}),{setSortChart:a}=t.useEditorActions();return e.jsxs(n.AccordionItem,{value:"stacked-sort",children:[e.jsx(n.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(n.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(Ct,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})})]})}const Ei=["kpi"],Is=2;function Dt(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 Ii(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 Di(s){return{...s,role:"groupby"}}function ki(){var w,F;const s=t.useEditorStore(S=>S.card),a=t.useEditorStore(S=>S.actions.updateCardConfig),r=n.useEffectiveEditorCardType(),{scopedFields:o}=n.useScopedFields(),d=((w=s.config)==null?void 0:w.metricColumns)||[],l=((F=s.config)==null?void 0:F.summary)||{},i=l.breakdownDimensions||[],c=i.length>0,u=Ei.includes(r),m=d.length>0,x=l.enabled===!0,g=u&&m,p=Array.from(new Map(o.filter(Ii).map(S=>[Dt(S),Di(S)])).values()),h=new Set(p.map(S=>Dt(S))),v=new Set(i.map(S=>Dt(S)).filter(S=>S&&h.has(S)));if(!u)return null;const M=S=>{a(s.id,{summary:{...l,...S}})},N=(S,y)=>{const k=Dt(S),E=p.filter(T=>v.has(Dt(T))),A=y?v.has(k)?E:[...E,S].slice(0,Is):E.filter(T=>Dt(T)!==k);M({breakdownDimensions:A,...A.length>0?{showOnCard:!0}:{}})},b=S=>{if(!S){M({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}M({enabled:!0,showOnCard:l.showOnCard??!0,includeInDashboardSummary:l.includeInDashboardSummary??!0})};return e.jsxs(n.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(n.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-[12px] hover:no-underline [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground",children:[e.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[e.jsx(n.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]}),e.jsx(t.Switch,{size:"xs",checked:x,disabled:!g,onClick:S=>S.stopPropagation(),onPointerDown:S=>S.stopPropagation(),onCheckedChange:b,"aria-label":"Enable summary"})]}),e.jsx(n.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!x&&"opacity-60"),children:[!g&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:m?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-show-on-card",checked:l.showOnCard===!0,disabled:!x,onCheckedChange:S=>M({showOnCard:S===!0})}),e.jsx(t.Label,{htmlFor:"summary-show-on-card",className:"cursor-pointer text-xs",children:"Show summary on card"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Checkbox,{id:"summary-include-rollup",checked:l.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:S=>M({includeInDashboardSummary:S===!0})}),e.jsx(t.Label,{htmlFor:"summary-include-rollup",className:"cursor-pointer text-xs",children:"Include in dashboard summary"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[i.length,"/",Is]})]}),p.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("ul",{className:"max-h-40 space-y-1 overflow-y-auto",children:p.map(S=>{const y=Dt(S),k=v.has(y),E=v.size>=Is,A=!x||!k&&E;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(n.Checkbox,{id:`summary-breakdown-${y}`,checked:k,disabled:A,onCheckedChange:T=>N(S,T===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${y}`,className:"cursor-pointer text-xs",children:S.label||S.name})]},y)})})]})]})})]})}const Mi=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Ai(){const s=t.useEditorStore(u=>u.card),a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),r=n.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:d}=t.useEditorActions();if(!s||!Mi.has(r||""))return null;const l=a==null?void 0:a.tooltipConfig,i=(l==null?void 0:l.formatMode)||(l==null?void 0:l.mode)||"inherit",c=u=>{const m={...a||{},tooltipConfig:{...l||{},...u}};o(m),d({...s,preferences:m})};return e.jsxs(n.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(n.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-[12px] font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Info,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Tooltip Format"})]})}),e.jsxs(n.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:i==="override",onCheckedChange:u=>c({formatMode:u?"override":"inherit",mode:u?"override":"inherit"})})]}),i==="override"&&e.jsx(Xt,{formatOptions:(l==null?void 0:l.formatOptions)||{},onFormatOptionsChange:u=>c({formatMode:"override",mode:"override",formatOptions:u}),showTitle:!1})]})]})}function Oa({mode:s}){const a=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return t.isTableChartType(a)?null:e.jsxs(e.Fragment,{children:[a==="combo"&&e.jsx(Zl,{}),(a==="area"||a==="stackedArea")&&e.jsx(oi,{}),a==="line"&&e.jsx(ui,{}),(a==="bar"||a==="horizontalBar"||a==="stackedBar")&&e.jsx(pi,{}),e.jsx(yi,{}),e.jsx(wi,{}),e.jsx(Bl,{}),s==="config"&&e.jsx(El,{}),s==="config"&&e.jsx(ki,{}),e.jsx(_l,{}),a==="bullet"&&e.jsx(Yl,{}),a==="funnel"&&e.jsx($l,{}),(a==="bubble"||a==="scatter")&&e.jsx(zl,{}),(a==="stackedBar"||a==="stackedLine")&&e.jsx(Ti,{}),e.jsx(Fl,{}),e.jsx(Rl,{}),e.jsx(Pl,{}),e.jsx(Ol,{}),e.jsx(Ai,{})]})}function Li(){const s=t.useEditorStore(r=>r.card),a=s==null?void 0:s.type;return a?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Vs,{chartType:a}),e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(Oa,{mode:"dev"})})]}):null}function Fi({focusSection:s,focusRequestId:a}){const r=t.useEditorStore(i=>i.card),o=r.type;if(t.getVisualizationMode(r)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(n.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(n.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(n.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 l(){if(t.supportsRegularTableSettings(o))return e.jsx(Pa,{cardType:o,focusSection:s,focusRequestId:a});switch(o){case"kpi":return e.jsx(jl,{});case"map":return e.jsx(Sl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ma,{})});case"text":return e.jsx(Dl,{});default:return e.jsx(Li,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[l(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}const sa=32;function Ri(){const s=C.useRef(null),a=C.useRef(null),r=t.useEditorStore(b=>b.isShowingVisual),o=t.useEditorStore(b=>b.isDevMode),d=t.useEditorStore(b=>b.showAIDialog),[l,i]=C.useState(!1),[c,u]=C.useState({section:null,id:0}),m=r&&!d,x=m&&(!o||l),g=o&&m,p=()=>i(b=>!b),h=b=>{b&&u(w=>({section:b,id:w.id+1})),o&&i(!0)};C.useEffect(()=>{var b,w,F,S;d?((b=s.current)==null||b.resize(0),(w=a.current)==null||w.resize(0)):((F=s.current)==null||F.resize(sa),(S=a.current)==null||S.resize(25))},[d]);const[v,M]=C.useState(!1),N=m?{show:g,isOpen:x,onToggle:p,onOpen:h}:void 0;return e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(n.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:50,children:e.jsx("div",{className:"flex min-w-0 flex-1 flex-col",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:e.jsx(uo,{renderCommandBarEnd:b=>e.jsx(ys,{mode:"toolbar",inlineToolbar:!0,overflowActions:b,visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})})})})}),e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:x?e.jsxs(n.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(n.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(ys,{mode:"canvas",visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})}),!d&&e.jsx(n.ResizableHandle,{}),e.jsx(n.ResizablePanel,{ref:s,className:"flex",defaultSize:sa,maxSize:45,children:e.jsx(Fi,{focusSection:c.section,focusRequestId:c.id})})]}):e.jsx(ys,{mode:"canvas",visualAsideControl:N,isDynamicInspectorOpen:v,onDynamicInspectorOpenChange:M})})]})}function Pi(s){var Ie;t.useAIInteractionStore($=>$.currentAIContext);const[a,r]=C.useState(""),[o,d]=C.useState(null),{authToken:l,tokenProps:i}=n.useSemaphorContext(),c=t.useEditorStore($=>$.card.id),u=t.useEditorStore($=>{var xe;return(xe=$==null?void 0:$.card)==null?void 0:xe.sql}),m=t.useEditorStore($=>$.isDevMode),x=t.useEditorStore($=>{var xe;return(xe=$==null?void 0:$.card)==null?void 0:xe.python}),{setCardPython:g,setCardSql:p,setRunSql:h,switchCardType:v,setQueryConfig:M}=t.useEditorActions(),N=t.useEditorStore($=>$.currentAssitantScope)||[],b=t.useEditorStore($=>$.userInputForAI),w=t.useEditorStore($=>$.triggerAIRun),F=t.useEditorStore($=>$.card),S=t.useEditorStore($=>$.selectedDatabaseName),y=t.useEditorStore($=>$.selectedTableName),k=t.useEditorStore($=>$.selectedConnectionId),E=t.useEditorStore($=>$.selectedSchemaName),A=t.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:T,refetch:I,data:L}=n.useEditorCardQuery(F),{setTriggerAIRun:j,setCurrentAssitantScope:P,setCardConfig:V}=t.useEditorActions(),{selectedDatamodelName:f,connectionType:O,selectedDatamodelId:D}=n.useEditorAside(),R=(Ie=n.useDashboardQuery().data)==null?void 0:Ie.assistantProfileId,B=C.useRef(n.createAssistantConversationId()),Y=C.useRef(null),_=C.useRef(c),z=C.useRef(!1),U=()=>{const $=Y.current;$&&(Y.current=null,B.current=n.createAssistantConversationId(),$==="clear"&&q([]))},{messages:G,setMessages:q,regenerate:Q,error:H,sendMessage:se,status:ce,addToolResult:ge,stop:fe,clearError:Te}=n.useChat({transport:new n.DefaultChatTransport({api:`${i.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${l==null?void 0:l.accessToken}`}),body:()=>{const $=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:R,conversationId:B.current,assistantRequestId:n.createAssistantRequestId(),isDevMode:m,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:xe})=>({body:{...xe,messages:t.cleanupIncompleteMessages($)}})}),onError:$=>{var xe;if(z.current=!1,$.name==="AbortError"||(xe=$.message)!=null&&xe.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),U();return}console.error("[Editor Assistant] Stream error:",$),U()},onToolCall:Ee,onFinish({isAbort:$,isDisconnect:xe,isError:Ce}){z.current=!1,r(""),console.log($?"[Editor Assistant] Stream aborted by user":xe?"[Editor Assistant] Stream disconnected (network error)":Ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),U()}}),Ve=C.useCallback($=>{z.current=!0;try{const xe=se($);return n.isPromiseLike(xe)?xe.catch(Ce=>{throw z.current=!1,Ce}):xe}catch(xe){throw z.current=!1,xe}},[se]),Ue=C.useCallback(()=>{z.current=!0;try{const $=Q();return n.isPromiseLike($)?$.catch(xe=>{throw z.current=!1,xe}):$}catch($){throw z.current=!1,$}},[Q]),Me=$=>{let xe=!1;q(Ce=>{const ae=typeof $=="function"?$(Ce):$;if(ae.length===0){if(z.current)return Y.current="clear",xe=!0,Ce;Y.current=null,B.current=n.createAssistantConversationId()}return ae}),xe&&fe()};C.useEffect(()=>{if(_.current!==c){if(_.current=c,z.current){Y.current!=="clear"&&(Y.current="rotate"),fe();return}Y.current=null,B.current=n.createAssistantConversationId()}},[c,fe]),C.useEffect(()=>{w&&b&&(Ve({role:"user",parts:[{type:"text",text:b}]}),j(!1))},[w,b,Ve,j]);async function Ee({toolCall:$}){var xe,Ce,ae,ie,Re,Z,Ae,ze,We,_e,Xe,Ze,et,re,J,pe;if(["createChartFromSql","createForecast"].includes($.toolName)){const ue=((xe=$.input)==null?void 0:xe.sql)??((Ce=$.args)==null?void 0:Ce.sql),ne=((ae=$.input)==null?void 0:ae.python)??((ie=$.args)==null?void 0:ie.python),me=((Re=$.input)==null?void 0:Re.chartType)??((Z=$.args)==null?void 0:Z.chartType);v(me),p(ue),g(ne),h(!0),ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!u){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:u,python:x||""}})}else if($.toolName==="generateQueryConfig"){r("Generating query config...");const ue=((Ae=$.input)==null?void 0:Ae.chartType)??((ze=$.args)==null?void 0:ze.chartType),ne=((We=$.input)==null?void 0:We.queryConfig)??((_e=$.args)==null?void 0:_e.queryConfig);((Xe=$.input)==null?void 0:Xe.cardConfig)??((Ze=$.args)==null||Ze.cardConfig),v(ue),V(ne),p(void 0),g(void 0);const me=await I();if((et=me==null?void 0:me.data)!=null&&et.error){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:ne,message:(re=me==null?void 0:me.data)==null?void 0:re.error.message}});return}if((J=me==null?void 0:me.data)!=null&&J.records){ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}ge({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(pe=me==null?void 0:me.data)==null?void 0:pe.records}})}else r("Analyzing...")}function Fe($){const xe=n.removeFromScopeArray(N,$);Oe(xe)}function Oe($){const xe=n.sanitizeAIScope($);P(xe),q(Ce=>[...Ce,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(xe)}`}]}])}function Pe(){const $={databaseName:S||"",schemaName:E||"",tableName:y||"",datamodelId:D||"",datamodelName:t.resolveDatamodelName(f),connectionId:k||"",connectionType:O||""},xe=n.dedup([...N,$]);Oe(xe)}function le(){const $={databaseName:S||"",schemaName:E||"",tableName:y||"",datamodelName:t.resolveDatamodelName(f),connectionId:k||"",connectionType:O||"",datamodelId:D||""};if(!n.isInAiScopeArray([...A||[],...N],$)||N.length===0){const Ce=n.dedup([...A||[],...N,$]).filter(ae=>ae.connectionId===$.connectionId);Oe(Ce)}}const De=!["ready","error"].includes(ce),ve=n.getErrorMessage(H);return{messages:G,setMessages:Me,sendMessage:Ve,regenerate:Ue,isLoading:De,handleSetAIScope:le,handleAddCurrentTableToScope:Pe,removeFromCurrentSelections:Fe,currentAssitantScope:N,setCurrentAssitantScope:P,stop:fe,status:ce,toolStatus:a,llmUsage:o,onFinish:s,errorMessage:ve,clearError:Te}}const Oi=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function na({isFullscreen:s,onFullscreenChange:a,fullscreenContainer:r}){const o=C.useRef(null),d=C.useRef(!1),[l,i]=C.useState(!1),[c,u]=C.useState(Ke.isDevEnv),[m,x]=C.useState(!1),[g,p]=C.useState(!1),[h,v]=C.useState(!1),[M,N]=C.useState(0),b=s??h,w=t.useCurrentAIContext(),{setCurrentAIContext:F,setHasEditorEntitySelectionOverride:S}=t.useAIActions(),{clearQueue:y}=t.useQueueActions(),{clearFileAttachments:k}=t.useFileActions(),E=t.useFileAttachments("editor"),{selectedEntities:A}=n.useAssistantContextEntities("editor"),T=t.useEditorStore(ae=>ae.card.id),I=t.useEditorStore(ae=>ae.card.dataSource),L=t.useEditorStore(ae=>{var ie;return(ie=ae.card.dataSource)==null?void 0:ie.selectedEntities}),j=t.useEditorStore(ae=>ae.actions.setCardSql),P=t.useEditorStore(ae=>ae.actions.setRunSql),V=t.useEditorStore(ae=>ae.showAIDialog),f=t.useDashboardStore(ae=>ae.handleOpenAssistantProfile),{setShowAIDialog:O,setCardPython:D}=t.useEditorActions(),{assistantProfile:R}=n.useAssistantProfile(),{messages:B,setMessages:Y,sendMessage:_,isLoading:z,stop:U,status:G,llmUsage:q,errorMessage:Q,clearError:H}=Pi(),[se,ce]=C.useState(""),ge=ae=>{ce(ae.target.value)},fe=ae=>{ae.preventDefault();const ie=se.trim();if(!ie&&E.length===0)return;const Re=[];ie&&Re.push({type:"text",text:ie}),E.forEach(Z=>{Z.data&&Re.push({type:"file",mediaType:Z.type,filename:Z.name,url:`data:${Z.type};base64,${Z.data}`})}),_({role:"user",parts:Re}),ce(""),k("editor"),Te()},Te=C.useCallback(()=>{N(ae=>ae+1)},[]);C.useEffect(()=>{var ae;V&&!d.current&&((ae=o.current)==null||ae.focus()),d.current=V},[V]),C.useEffect(()=>{V&&(S(!1),F({selectedEntities:L||[]}))},[T,L,F,S,V]),n.useAutoSubmitQueue({assistantType:"editor",status:G,isLoading:z,sendMessage:_});const{hasActiveTools:Ve,activeToolText:Ue}=n.useActiveToolStatus(B),Me=C.useCallback(ae=>{a==null||a(ae),s===void 0&&v(ae)},[s,a]);C.useEffect(()=>{if(!b)return;function ae(ie){ie.key==="Escape"&&Me(!1)}return window.addEventListener("keydown",ae),()=>{window.removeEventListener("keydown",ae)}},[b,Me]);const Ee=C.useCallback(ae=>{_({role:"user",parts:[{type:"text",text:ae}]}),Te()},[Te,_]),Fe=C.useCallback(async()=>{const ae=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ae),n.ue.success("Conversation copied")}catch(ie){console.error("Failed to copy conversation",ie),n.ue.error("Unable to copy conversation")}},[B]),Oe=C.useCallback(()=>{Me(!b)},[b,Me]);function Pe(ae,ie){ie==="sql"?(j(ae),P(!0)):ie==="python"&&(D(ae),P(!0))}function le(){w.selectedEntities.length===0&&F({selectedEntities:A})}function De(ae){le();const ie={role:"user",parts:[{type:"text",text:ae.title+" "+ae.subtitle}]};_(ie),Te()}function ve(ae){le(),_({role:"user",parts:[{type:"text",text:ae}]}),Te()}function Ie(){return e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",size:"xs",variant:"ghost","aria-label":"Assistant options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",children:[e.jsx(n.DropdownMenuLabel,{children:"Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsx(n.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:i,children:"Token usage"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:u,children:"Tool invocations"}),e.jsx(n.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:x,children:"System message"})]})]})}function $(){return e.jsx("div",{"data-role":"header",className:"flex min-w-0 items-center",children:e.jsx("div",{className:"truncate text-[13px] font-medium",children:"Assistant"})})}const xe=(se==null?void 0:se.length)===0&&(B==null?void 0:B.filter(ae=>ae.role==="user").length)===0,Ce=e.jsxs("div",{"data-role":"editor-assistant",className:t.cn("flex h-full w-full flex-col justify-between px-6 py-4",b&&"rounded-card 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-center justify-between gap-2",children:[$(),f&&e.jsx(t.Button,{variant:"outline",size:"xs",className:"min-w-0 shrink",onClick:f,children:e.jsx("span",{className:"truncate",children:(R==null?void 0:R.name)||"Default profile"})}),e.jsxs("div",{"data-role":"header-actions",className:"flex shrink-0 items-center gap-1.5",children:[Ie(),c&&e.jsx(t.Button,{variant:"ghost",size:"xs",className:"text-muted-foreground hover:text-foreground",onClick:Fe,children:"Copy conversation"}),e.jsx(n.IconButton,{tooltip:b?"Exit fullscreen":"Expand",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:Oe,children:b?e.jsx(Ye.Minimize2,{className:"h-3.5 w-3.5"}):e.jsx(Ye.Maximize2,{className:"h-3.5 w-3.5"})}),e.jsx(n.IconButton,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",tooltip:"New chat",onClick:()=>{Y([]),y("editor"),H()},children:e.jsx(n.SquarePen,{className:"h-3.5 w-3.5"})}),e.jsx(n.IconButton,{tooltip:"Close",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>{O(!1)},children:e.jsx(oe.X,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(n.AssistantVirtualizedMessages,{messages:B,showTools:c,handleRun:Pe,showSystemMessage:m,onQuickReply:Ee,disableQuickReplies:z,status:G,errorMessage:Q,activeToolText:z&&Ve?Ue:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:V?"bottom-24 right-8":"hidden",scrollToEndSignal:M}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[xe&&!R&&e.jsx(n.Placeholders,{onClick:De,placeholders:Oi}),e.jsx("div",{children:xe&&R&&e.jsx(n.SeedQuestions,{seedQuestions:R.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(n.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(n.ChatInputWithContext,{ref:o,setInput:ce,stop:U,input:se,handleInputChange:ge,handleSubmit:ae=>{le(),fe(ae)},isLoading:z,status:G,assistantType:"editor",onFocus:()=>{}})]}),q&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",q.inputTokens," prompt tokens, ",q.outputTokens," ","completion tokens, ",q.totalTokens," total tokens"]})}),e.jsx(n.AddDataPicker,{incomingSelectedEntities:A,open:g,onOpenChange:p,dataSource:I||n.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:ae=>{S(!0),F({...w,selectedEntities:ae})}})]});return b&&r?dr.createPortal(e.jsx(n.SemaphorStyleWrapper,{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:Ce})}),r):Ce}function Ba(s,a,r){if(!a)return!1;const o=a.qualifiedFieldName,d=a.qualifiedEntityName,l=d&&a.name?`${d}.${a.name}`:o;return s.some(i=>{if(!(t.getDataType(i.dataType||"")==="date"))return!1;const u=n.getSelectedDateFilterColumn(i,r),m=u.split("."),x=m[m.length-1]||u,g=m.length>1?m.slice(0,-1).join("."):void 0,p=i.qualifiedTableName||g,h=p?`${p}.${x}`:void 0;return o?h?h===l||h.endsWith(`.${o}`):x===a.name:h?h===l:x===a.name})}function Bi({dashboard:s,dateGroupByField:a,dashboardInputValues:r,sheetId:o,card:d,timezone:l}){var m;if(!s||!a)return!1;const i=(m=s.inputs)==null?void 0:m.filter(x=>x.kind==="filter"&&!x.compatibility);if(!(i!=null&&i.length))return!1;const c={...s,inputs:i,controls:[]};return n.resolveDashboardInputContext({dashboard:c,sheetId:o,card:d,sheetKind:"dashboard",runtimeValues:{dashboardInputValues:r},mode:"editor",timezone:l}).resolvedInputs.some(x=>x.kind!=="filter"||!x.filter||!x.filterValue?!1:Ba([x.filter],a,[x.filterValue]))}function Vi(s){switch(s){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function _i({aliasTemplate:s,onAliasTemplateChange:a}){var u;const[r,o]=C.useState(s),[d,l]=C.useState(!1),i=(u=t.useEditorStore(m=>{var x;return(x=m.card.config)==null?void 0:x.pivotByColumns}))==null?void 0:u[0],c=i?`e.g. Min Sales in {{${i.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input,{placeholder:c,value:d?r:s,onChange:m=>{o(m.target.value),l(!0)},onFocus:()=>l(!0),onPointerDown:m=>m.stopPropagation(),className:"h-8 text-xs",onKeyDown:m=>{m.key==="Enter"&&d&&r!==s?(a(r),l(!1)):m.key==="Escape"&&(o(s),l(!1))},"aria-label":"Edit alias template"}),d&&r!==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(r),l(!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:()=>{o(s),l(!1)},children:e.jsx(oe.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Yi({valueAliases:s,onValueAliasesChange:a}){const[r,o]=C.useState(null),[d,l]=C.useState(""),[i,c]=C.useState(""),u=()=>{a({...s,"":""})},m=g=>{const p={...s};delete p[g],a(p)},x=g=>{const p={...s};delete p[g],p[d]=i,a(p),o(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(([g,p],h)=>e.jsx("div",{className:"flex items-center gap-2",children:r===g?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:d,onChange:v=>l(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?x(g):v.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:i,onChange:v=>c(v.target.value),className:"h-8 w-24 text-xs",onPointerDown:v=>v.stopPropagation(),onKeyDown:v=>{v.key==="Enter"?x(g):v.key==="Escape"&&o(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:()=>x(g),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:()=>o(null),children:e.jsx(oe.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:g,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),l(g),c(p)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:p,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(g),l(g),c(p)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(g),"aria-label":"Remove value alias",children:e.jsx(oe.X,{className:"h-3 w-3"})})]})},g+h)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function zi({idx:s}){var c;const a=t.useEditorStore(u=>{var m;return(m=u.card)==null?void 0:m.preferences}),r=t.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.datasetOptions}),o=t.useEditorStore(u=>u.actions.setCardPreferences),d=(c=a==null?void 0:a.chartOptions)==null?void 0:c.indexAxis,l=r==null?void 0:r.find(u=>u.idx===s);function i(u,m){(u==="end"||u==="start")&&Ke.getContrastColor(Ke.getCanvasBackgroundColor());const x={display:u!=="none",align:u,anchor:u,clamp:!0};if(!l)o({...a,datasetOptions:[...r||[],{idx:m,datalabels:x}]});else{const g={...l};g.datalabels=x;const p=r==null?void 0:r.map(h=>h.idx===m?g:h);o({...a,datasetOptions:p})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(n.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:()=>i("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(oe.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>i("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Nr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})}),e.jsx("button",{onClick:()=>i("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sr,{className:t.cn("h-4 w-4",{"rotate-90":d==="y"})})})]})})]})}function _s({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 qi(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function $i({col:s,idx:a,className:r,iconClassName:o,children:d}){const l=t.useEditorStore(x=>{var g;return(g=x.card)==null?void 0:g.preferences}),i=t.useEditorStore(x=>{var g,p;return(p=(g=x.card)==null?void 0:g.preferences)==null?void 0:p.datasetOptions}),c=i==null?void 0:i.find(x=>x.idx===a),{setCardPreferences:u}=t.useEditorStore(x=>x.actions);function m(x){if(!c)u({...l,datasetOptions:[...i||[],{idx:a,type:x==="area"?"line":x,fill:x==="area"?"origin":""}]});else{const g={...c};g.type=x==="area"?"line":x,g.fill=x==="area"?"origin":"";const p=i==null?void 0:i.map(h=>h.idx===a?g:h);u({...l,datasetOptions:p})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[d||e.jsx(_s,{className:"max-w-[100px]",title:s,children:qi(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(n.ChartColumnIncreasing,{onClick:()=>m("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartLine,{onClick:()=>m("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(n.ChartArea,{onClick:()=>m("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(zi,{idx:a})]})]})}function Ki(){const s=t.useEditorStore(c=>c.card.type),a=t.useEditorStore(c=>c.isDevMode),r=t.useEditorStore(c=>c.card.preferences),{setCardPreferences:o}=t.useEditorStore(c=>c.actions);function d(c){var x;const u={datalabels:{display:c!=="none",align:c,anchor:c,clamp:!0}},m={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(x=r==null?void 0:r.chartOptions)==null?void 0:x.plugins,...u}}};o(m)}function l(){var c,u,m;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((m=(u=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:u.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function i(){var c,u,m;return e.jsx("div",{children:e.jsxs(t.Select,{value:((m=(u=(c=r==null?void 0:r.chartOptions)==null?void 0:c.plugins)==null?void 0:u.datalabels)==null?void 0:m.anchor)||"none",onValueChange:d,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?l():i()})}function Ui({column:s}){const a=t.useEditorStore(u=>u.card.type),r=t.useEditorStore(u=>{var m,x;return(x=(m=u.card)==null?void 0:m.config)==null?void 0:x.metricColumns}),o=(r==null?void 0:r.map(u=>u.label))||[],d=o==null?void 0:o.find(u=>u===s.label||u===s.name),l=d?o.indexOf(d):-1;function i(){return e.jsx("div",{className:"pr-1",children:d&&e.jsx($i,{idx:l,col:d,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function c(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ki,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&i(),["pie","doughnut"].includes(a)&&c()]})}function Hi({field:s,searchQuery:a="",limit:r=500}){const{authToken:o,tokenProps:d}=n.useSemaphorContext(),l=t.useDashboardStore(x=>{var g;return((g=x.reportContext)==null?void 0:g.calendar)??null}),i=t.useEditorStore(x=>x.card),c=i==null?void 0:i.dataSource,u=["attribute-values",s.entityName,s.name,a,r,l],m=n.useQuery({queryKey:u,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={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:r},g={connection_id:c.connectionId,cardConfig:x,cardDataSource:c,cache_config:t.getCacheConfig({card:i}),calendarContext:l};console.log("requestBody",g);const p=await t.postRequestRegular(`${d.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",g);if(p!=null&&p.error)return console.error("Error fetching attribute values:",p.error),[];const h=s.name;return((p==null?void 0:p.records)||[]).map(M=>{const N=M[h]||M[s.alias||h]||M[s.label];return{id:N||"",value:N||"",label:String(N||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!s&&!!(c!=null&&c.connectionId)&&!!l,staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:m.data||[],isLoading:m.isLoading,isFetching:m.isFetching,isError:m.isError,error:m.error,refetch:m.refetch}}function Va({open:s,onOpenChange:a,availableFields:r,existingFilters:o,editingCondition:d,onSave:l}){var F,S;const i=!!d,[c,u]=C.useState(i?"values":"fields"),[m,x]=C.useState(""),[g,p]=C.useState({id:(d==null?void 0:d.id)||Ke.v4(),field:(d==null?void 0:d.field)||null,selectedValues:d?Array.isArray(d.value)?d.value:[d.value]:[]}),h=r.filter(y=>{var E;return i?!1:!((E=o==null?void 0:o.conditions)==null?void 0:E.some(A=>A.field.id===y.id))&&y.label.toLowerCase().includes(m.toLowerCase())}),v=y=>{p({...g,field:y}),u("values")},M=()=>{if(g.field&&g.selectedValues.length>0){const y={id:g.id,field:g.field,operator:"in",value:g.selectedValues};let k;if(i){const E=((o==null?void 0:o.conditions)||[]).map(A=>A.id===d.id?y:A);k={...o,conditions:E}}else{const E=(o==null?void 0:o.conditions)||[];k={id:(o==null?void 0:o.id)||Ke.v4(),logicalOperator:"AND",negate:!1,conditions:[...E,y],groups:[]}}l(k),a(!1)}},N=()=>{if(!i||!d)return;const y=((o==null?void 0:o.conditions)||[]).filter(k=>k.id!==d.id);if(y.length>0){const k={...o,conditions:y};l(k)}else l(void 0);a(!1)},b=y=>{p({...g,selectedValues:y})},w=()=>{i&&d?(p({id:d.id,field:d.field,selectedValues:Array.isArray(d.value)?d.value:[d.value]}),u("values")):(p({id:Ke.v4(),field:null,selectedValues:[]}),u("fields")),x("")};return C.useEffect(()=>{s&&w()},[s,i,d]),e.jsx(n.Dialog,{open:s,onOpenChange:a,children:e.jsxs(n.DialogContent,{className:"max-w-2xl",children:[e.jsx(n.DialogHeader,{children:e.jsx(n.DialogTitle,{children:i?`Edit Filter: ${(F=g.field)==null?void 0:F.label}`:c==="fields"?"Select Field to Filter":`Select Values for ${(S=g.field)==null?void 0:S.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!i&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&c==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:o.conditions.map(y=>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:[y.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(y.value)?`${y.value.length} values`:String(y.value)})]},y.id))})]}),c==="fields"&&!i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-border bg-background px-2 focus-within:border-ring",children:[e.jsx(Ye.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search fields",value:m,onChange:y=>x(y.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),m&&e.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>x(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(oe.X,{className:"h-3 w-3"})})]}),e.jsx("div",{className:"grid max-h-[400px] grid-cols-2 gap-1 overflow-y-auto",children:h.map(y=>e.jsxs("button",{type:"button",onClick:()=>v(y),className:"group flex items-center gap-2 rounded-[5px] border border-border px-2 py-1.5 text-left transition-colors hover:bg-muted focus-visible:border-ring focus-visible:outline-none",children:[e.jsx(n.IconForFieldType,{dataType:t.getDataType(y.dataType)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[13px] text-foreground",children:y.label}),e.jsxs("div",{className:"truncate font-mono text-[10px] text-muted-foreground",children:[y.entityName,".",y.name]})]})]},y.id))}),h.length===0&&m&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',m,'"']}),h.length===0&&!m&&r.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(Gi,{field:g.field,selectedValues:g.selectedValues,onValuesChange:b,onBack:i?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:i?e.jsx(t.Button,{variant:"destructive",onClick:N,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:w,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:M,disabled:!g.field||g.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function Gi({field:s,selectedValues:a,onValuesChange:r,onBack:o}){const[d,l]=C.useState(""),{values:i,isLoading:c,isFetching:u}=Hi({field:s,searchQuery:d,limit:500}),m=d?i.filter(p=>String(p.value).toLowerCase().includes(d.toLowerCase())):i,x=p=>{const h=a.includes(p);r(h?a.filter(v=>v!==p):[...a,p])},g=()=>{a.length===m.length&&m.length>0?r([]):r(m.map(p=>p.value))};return e.jsxs("div",{className:"space-y-4",children:[o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:o,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(Ye.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(t.Input,{placeholder:"Search values...",value:d,onChange:p=>l(p.target.value),className:"pl-10"})]}),c||u?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(n.Checkbox,{checked:a.length===m.length&&m.length>0,onCheckedChange:g}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",m.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:m.map(p=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>x(p.value),children:[e.jsx(n.Checkbox,{checked:a.includes(p.value),onCheckedChange:()=>x(p.value)}),e.jsx(_s,{className:"text-sm",children:p.label})]},p.id))})]})]})}function Qi({value:s,onChange:a,cardType:r,showTitle:o=!0,title:d="NUMBER FORMAT"}){const l=n.supportsLiveNumericPresentation(r),i=n.useResolvedValueFormatLocale(),c=n.useResolvedDefaultCurrency(),u=t.toTFormatOptions(t.fromSemanticFormat(s,{preserveOmittedProperties:!0}),{preserveOmittedProperties:!0})||{},m=x=>{a(t.fromTFormatOptions(x,{preserveOmittedProperties:!0}))};return e.jsx(Xt,{formatOptions:u,onFormatOptionsChange:m,showTitle:o,title:d,reportDefaults:l?{currency:c??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,locale:i??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale}:void 0})}function Wi(s,a){return s==="pivotBy"&&(a==="table"||a==="pivotTable")}const Ji=[];function Xi({field:s,zone:a,index:r,sortDirection:o,onSortDirectionChange:d,hasPivotColumns:l=!1,cardType:i}){var Ws,Js,Xs,Zs,en,tn,sn,nn,an,rn,on,ln,cn,dn,un,mn,xn,hn,pn,fn,gn,bn,jn,vn,yn,Cn,Nn,Sn,wn,Tn,En,In,Dn,kn;const{attributes:c,listeners:u,setNodeRef:m,transform:x,transition:g,isDragging:p}=n.useSortable({id:s.id}),h=t.useEditorStore(K=>K.card),v=t.useEditorStore(K=>K.frame),M=t.useDashboardStore(K=>K.isVisualEditing),N=t.useDashboardStore(K=>K.selectedSheetId),b=t.useDashboardStore(K=>K.actions.updateSheetCalculatedFields),w=t.useDashboardStore(K=>K.actions.updateDashboardCalculatedFields),S=t.useDashboardStore(K=>{var be;return K.visualEditPendingDashboardCalculatedFields??((be=K.dashboard)==null?void 0:be.calculatedFields)})??Ji,{scopedFields:y,valuePickFilterableFields:k}=n.useFilterableFields(),{userContext:E}=n.useCurrentUserInfo(),{tokenProps:A}=n.useSemaphorContext(),T=n.canEditLocalCalculatedFields(E),I=n.useTimezone()??void 0,L=n.useResolvedTemporalStylePreferences()??Jt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES,{updateLabel:j,handleAggregationChange:P,handleDetailDateFormatChange:V,handleTemporalBucketFormatChange:f,handleGranularityChange:O,handleAliasTemplateChange:D,handlePivotMemberOrderChange:R,handleValueAliasesChange:B,handleMetricFormatChange:Y,removeField:_,handleMetricComparisonChange:z,handleMetricComparisonSpecChange:U,handleMetricComparisonPolarityChange:G,handleMetricWindowTransformChange:q,handleMetricWindowOrderByChange:Q,handleMetricWindowDirectionChange:H,handleMetricWindowPartitionToggle:se,handleMetricMovingAverageWindowSizeChange:ce,handleMetricMovingAverageMinPeriodsChange:ge,handleMetricPreviousPeriodDeltaModeChange:fe,handleMetricPercentOfTotalScopeChange:Te,handleMetricPercentOfTotalOutputChange:Ve,handleMetricTargetValueChange:Ue}=n.useFieldManagement(h),[Me,Ee]=C.useState(!1),[Fe,Oe]=C.useState(()=>{var K;return!!((K=s.parameters)!=null&&K.windowTransform)}),[Pe,le]=C.useState(!1),[De,ve]=C.useState(!1),[Ie,$]=C.useState(null),xe=C.useMemo(()=>{const K=de=>de!=null&&de.startsWith("card-source-")?de.replace("card-source-",""):de,be=K(s.id),X=y.find(de=>{if(s.qualifiedFieldName&&de.qualifiedFieldName&&de.qualifiedFieldName===s.qualifiedFieldName||s.qualifiedEntityName&&de.qualifiedEntityName&&de.qualifiedEntityName===s.qualifiedEntityName&&de.name===s.name)return!0;const we=K(de.id);return!!(be&&we&&be===we)});return{dataType:(X==null?void 0:X.dataType)||s.dataType,resolvedFromScopedField:!!X}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,y]),Ce=n.getGranularityOptionsForFieldType(xe.dataType),ae=C.useMemo(()=>t.readTemporalBucketAuthoringState({fieldId:s.id,dataType:s.dataType,granularity:s.granularity,format:s.format,dateFormat:s.dateFormat,customFormat:s.customFormat,semanticTemporalPresentation:s.semanticTemporalPresentation}),[s.customFormat,s.dataType,s.dateFormat,s.format,s.id,s.granularity,s.semanticTemporalPresentation]),ie=a==="groupBy"?ae.ok&&Ce.includes(ae.granularity)?ae.granularity:void 0:Ce.includes(s.granularity)?s.granularity:"day",Re=ae.ok?ae.selection:{value:"auto",customPattern:"",format:It.AUTOMATIC_TEMPORAL_BUCKET_FORMAT},[Z,Ae]=C.useState(a==="groupBy"?Re.value:s.dateFormat||"YYYY-MM-DD"),[ze,We]=C.useState(a==="groupBy"?Re.customPattern:s.customFormat||""),_e=Z==="custom",[Xe,Ze]=C.useState(s.aliasTemplate||""),[et,re]=C.useState(s.valueAliases||{}),[J,pe]=C.useState((Ws=s.parameters)==null?void 0:Ws.filters),ue=K=>{var X;if(a==="groupBy"&&!ie)return;const be=ie??"day";if(K==="custom"){const de=a==="groupBy"?It.getTemporalBucketAuthoringOptions(be,Re.format,L).find(Qe=>Qe.value==="custom"):void 0,we=a==="groupBy"?ze||(((X=de==null?void 0:de.format)==null?void 0:X.presentation.mode)==="pattern"?de.format.presentation.pattern:""):ze;Ae(K),We(we),a==="groupBy"&&f(r,It.resolveTemporalBucketAuthoringFormat(be,K,we))}else Ae(K),a==="groupBy"?f(r,It.resolveTemporalBucketAuthoringFormat(be,K)):a==="detailColumns"&&V(r,K,"")},ne=K=>{if(a==="groupBy"&&!ie)return;const be=ie??"day";We(K),a==="groupBy"?f(r,It.resolveTemporalBucketAuthoringFormat(be,"custom",K)):a==="detailColumns"&&V(r,"custom",K)},me=K=>{if(a==="groupBy"){const be=It.reconcileTemporalBucketAuthoringFormat(Re.format,K),X=t.readTemporalBucketAuthoringSelection({fieldId:s.id,dataType:s.dataType,granularity:K,format:be,semanticTemporalPresentation:s.semanticTemporalPresentation});Ae(X.value),We(X.customPattern),O(r,K)}},qe=K=>{Ze(K),a==="metrics"&&D(r,K)},$e=K=>{a==="pivotBy"&&R(r,K)},Je=K=>{re(K),a==="metrics"&&B(r,K)},Ge=K=>{j(a,r,K)},st=n.getExpressionFieldKind(s),St=n.getFieldExpressionAnnotation(s),dt=n.isManagedCalculatedExpressionField(s),pt=s.role==="metric"&&dt,wt=dt&&(st==="user_calculated"||st==="inline_expression"&&s.fieldScope!=="domain"),lt=wt?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(v==null?void 0:v.calculatedFields)||[],dashboardFields:S}):void 0,Zt=wt&&(lt==null?void 0:lt.scope)==="sheet",Ot=wt&&(lt==null?void 0:lt.scope)==="dashboard",ft=st==="domain_calculated"||s.fieldScope==="domain",Bt=ft?n.resolveDomainCalculatedFieldForEdit(s,y):void 0,ut=ft?"domain":Zt?"sheet":Ot?"dashboard":"card",gt=ft?Bt||s:(Zt||Ot)&&(lt!=null&<.matchedField)?lt.matchedField:s,bt=K=>{var be;if(pe(K),a==="metrics"){const X={...s,parameters:{...s.parameters,filters:K}},de=[...((be=h.config)==null?void 0:be.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:de})}le(!1)},qs=()=>{_(a,r)},es={transform:n.CSS.Transform.toString(x),transition:g},ts=t.getDataType(xe.dataType||s.dataType),Vt=ts==="date",_t=i==="kpi",ms=a==="detailColumns",ss=(Js=h.config)==null?void 0:Js.metricColumns,jt=(Xs=h.config)==null?void 0:Xs.groupByColumns,Yt=t.useDashboardStore(K=>K.dashboard),ns=t.useDashboardStore(K=>{var be;return(be=K.dashboard)==null?void 0:be.filters}),Tt=t.useDashboardStore(K=>K.filterValues),zt=t.useDashboardStore(K=>K.dashboardInputValues),qt=t.useDashboardStore(K=>K.semanticExecutionPayload),W=a==="groupBy"&&ie?It.getTemporalBucketAuthoringOptions(ie,Re.format,L):a==="detailColumns"?Vi(ie??"day"):[],te=_e?"custom":!ie&&a==="groupBy"?void 0:W.some(K=>K.value===Z)?Z:((Zs=W[0])==null?void 0:Zs.value)??"YYYY-MM-DD",ee=!!i&&t.COMPARISON_SUPPORTED_CHART_TYPES.includes(i),Ne=!!i&&t.COMPARISON_TARGET_SUPPORTED_CHART_TYPES.includes(i),ye=C.useMemo(()=>jt==null?void 0:jt.find(K=>t.getDataType(K.dataType||"")==="date"),[jt]),je=C.useMemo(()=>t.resolveCardPrimaryDateField({card:h,cardConfig:h.config||{},semanticExecutionPayload:qt}),[h,qt]),Se=C.useMemo(()=>ye||(je?{...je,id:`semantic-primary:${je.entityId}:${je.name}`,label:je.name,role:"groupby",granularity:je.defaultGranularity||"day"}:void 0),[ye,je]),tt=C.useMemo(()=>{var de;if(!Se)return!1;const K=(de=h.config)==null?void 0:de.filters;if(!K)return!1;const be=we=>{const Qe=we.field;return Qe?Se.id&&Qe.id===Se.id||Se.qualifiedFieldName&&Qe.qualifiedFieldName===Se.qualifiedFieldName?!0:Qe.name===Se.name:!1},X=we=>we.conditions.some(He=>t.getDataType(He.field.dataType||"")==="date"&&be(He))?!0:we.groups.some(He=>X(He));return X(K)},[(en=h.config)==null?void 0:en.filters,Se]),mt=C.useMemo(()=>Ba(ns||[],Se,Tt)||Bi({dashboard:Yt,dateGroupByField:Se,dashboardInputValues:zt,sheetId:N,card:h,timezone:I}),[h,Yt,ns,Tt,zt,Se,N,I]),Et=tt||mt,ke=s,Le=((tn=ke.comparison)==null?void 0:tn.mode)==="explicit"?ke.comparison.spec:void 0,vt=((nn=(sn=ke.parameters)==null?void 0:sn.windowTransform)==null?void 0:nn.function)||"none",rt=n.isMetricTransformEnabled(ke),ot=rt?vt:null,xs=n.supportsMetricTransformForMetric({cardType:i||"table",cardConfig:h.config||{},metric:ke,transformMode:ot||"running_total"}),$t=((an=ke.comparison)==null?void 0:an.mode)==="explicit",$s=n.getRunningTotalOrderByCandidates(jt||[]),Mt=((ln=(on=(rn=ke.parameters)==null?void 0:rn.windowTransform)==null?void 0:on.orderBy)==null?void 0:ln.fieldId)||"",Ya=((un=(dn=(cn=ke.parameters)==null?void 0:cn.windowTransform)==null?void 0:dn.orderBy)==null?void 0:un.direction)||"asc",Ks=$s.find(K=>K.id===Mt),hs=ot==="running_total"||ot==="moving_average"||ot==="previous_period_delta",za=rt&&hs&&!!Ks&&t.getDataType(Ks.dataType||"")!=="date",qa=n.getDefaultRunningTotalPartitionByFieldIds({cardType:i||"table",cardConfig:h.config||{},orderByFieldId:Mt||void 0}),$a=new Set(((xn=(mn=ke.parameters)==null?void 0:mn.windowTransform)==null?void 0:xn.partitionByFieldIds)||qa),Ka=i==="pivotTable"||n.isSubtotalEnabledAggregateTable(i||"table",h.config||{}),Us=[...(jt||[]).filter(K=>K.id&&(!hs||K.id!==Mt)),...Ka?(((hn=h.config)==null?void 0:hn.pivotByColumns)||[]).filter(K=>K.id):[]],Hs=((gn=(fn=(pn=ke.parameters)==null?void 0:pn.windowTransform)==null?void 0:fn.movingAverage)==null?void 0:gn.windowSize)||7,Ua=((vn=(jn=(bn=ke.parameters)==null?void 0:bn.windowTransform)==null?void 0:jn.movingAverage)==null?void 0:vn.minPeriods)||1,Ha=((Nn=(Cn=(yn=ke.parameters)==null?void 0:yn.windowTransform)==null?void 0:Cn.previousPeriodDelta)==null?void 0:Nn.mode)||"absolute",Gs=((Tn=(wn=(Sn=ke.parameters)==null?void 0:Sn.windowTransform)==null?void 0:wn.percentOfTotal)==null?void 0:Tn.scope)||"grand_total",Ga=((Dn=(In=(En=ke.parameters)==null?void 0:En.windowTransform)==null?void 0:In.percentOfTotal)==null?void 0:Dn.output)||"percent",Qa=C.useMemo(()=>(ss||[]).some(()=>!1),[ss]);C.useEffect(()=>{rt&&Oe(!0)},[rt]);const Wa=a!=="pivotBy"&&a!=="sortBy",Ja=Wi(a,i),Xa=s.memberOrder??"auto",Za=Vt&&a==="groupBy"&&(!_t||Qa),er=!_t&&Vt&&(a==="groupBy"||ms),tr=a==="metrics",as=ee&&!h.sql&&!h.python&&a==="metrics",sr=()=>{const K=s,be=a==="metrics"&&pt;return e.jsxs("div",{className:"space-y-1",children:[!be&&e.jsx("div",{title:`${s.entityName}.${s.name}`,onPointerDown:X=>{X.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}`}),be&&K.calculatedFormula&&e.jsxs("div",{title:n.formatDisplayFormula(K.calculatedFormula),onPointerDown:X=>{X.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap rounded bg-muted/50 px-1.5 py-0.5 font-mono text-xs text-primary",children:["= ",n.formatDisplayFormula(K.calculatedFormula)]})]})},nr=()=>Wa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(ct,{value:s.label??"",onSave:Ge,placeholder:"Display label...",type:"text"})]}):null,ar=()=>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:o||"asc",onValueChange:K=>d(K),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"})]})]})]}),rr=()=>Ja?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot column order"}),e.jsxs(t.Select,{value:Xa,onValueChange:K=>$e(K),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:"auto",children:"Auto"}),e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}):null,Qs=()=>Za?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:ie,onValueChange:me,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:Ce.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K,children:t.toTitleCase(K)},K))})]})]}):null,or=()=>er?e.jsxs(e.Fragment,{children:[Qs(),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:te,onValueChange:ue,disabled:a==="groupBy"&&!ie,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:W.map(K=>e.jsx(t.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),_e&&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:ze,onChange:K=>{K.stopPropagation(),ne(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,lr=()=>{var be;if(!tr)return null;const K=pt;return e.jsxs(e.Fragment,{children:[K&&T&&!ft&&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:()=>ve(!0),children:[e.jsx(n.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:X=>{P(r,X)},disabled:K,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(Qi,{value:ke.format,onChange:X=>Y(r,X),cardType:i,showTitle:!1})]}),e.jsx(n.Collapsible,{open:Fe,onOpenChange:Oe,children:e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/20 p-2.5",children:[e.jsx(n.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:[!Fe&&e.jsx("span",{className:"mr-2",children:rt?t.toTitleCase(vt.replace(/_/g," ")):"None"}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Fe?"rotate-180":"")})]})]})}),e.jsxs(n.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:rt?vt:"none",onValueChange:X=>q(r,X),disabled:!xs.supported&&!rt,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:$t,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:$t,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:$t,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:$t,children:"Percent of Total"})]})]}),!xs.supported&&!rt&&e.jsx("div",{className:"text-xs text-muted-foreground",children:xs.reason}),$t&&!rt&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),rt&&e.jsxs(e.Fragment,{children:[hs&&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:Mt,onValueChange:X=>Q(r,X),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:$s.filter(X=>!!X.id).map(X=>e.jsx(t.SelectItem,{value:X.id,className:"text-xs",children:X.label||X.name},X.id))})]}),!Mt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),za&&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:Ya,onValueChange:X=>H(r,X),disabled:!Mt,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"})]})]})]})]}),ot==="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:Hs,onChange:X=>ce(r,Number(X.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:Hs,className:"h-8 text-xs",value:Ua,onChange:X=>ge(r,Number(X.target.value))})]}),ot==="previous_period_delta"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Output"}),e.jsxs(t.Select,{value:Ha,onValueChange:X=>fe(r,X),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"})]})]})]}),ot==="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:Gs,onValueChange:X=>Te(r,X),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:Ga,onValueChange:X=>Ve(r,X),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"})]})]})]})]}),(ot==="running_total"||ot==="moving_average"||ot==="previous_period_delta"||ot==="percent_of_total"&&Gs==="partition_total")&&Us.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:Us.map(X=>{const de=!!X.id&&$a.has(X.id);return e.jsxs("button",{type:"button",onClick:()=>X.id&&se(r,X.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:X.label||X.name}),de?e.jsx(t.Check,{className:"h-3 w-3"}):null]},X.id)})})]})]})]})]})}),as&&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:ke.comparison?ke.comparison.mode==="off"?"off":ke.comparison.spec.kind:"inherit",disabled:rt,onValueChange:X=>z(r,X),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:"inherit",children:"Inherit dashboard comparison (default)"}),e.jsx(t.SelectItem,{value:"off",children:"Off"}),(()=>{const X=!Se||!Et,de=Se?Et?void 0:"Add a date filter to enable":"Configure a semantic primary date or add a date axis",we=(Qe,He)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Qe,disabled:X,title:de,children:He})}),X&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[we("previous_period","Previous Period"),we("previous_year","Previous Year")]})})(),Ne&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]}),!ke.comparison&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Dashboard comparison is not available yet. This metric will follow it when a viewer sets it."})]}),as&&Le&&(Le.kind==="previous_period"||Le.kind==="previous_year")&&e.jsxs("div",{className:"space-y-2 rounded border border-border/60 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:Le.kind==="previous_year"?"Years back":"Periods back"}),e.jsx(t.Input,{type:"number",min:1,step:1,value:Le.kind==="previous_year"?Le.offsetYears||1:Le.offsetPeriods||1,onChange:X=>{const de=Number(X.target.value);!Number.isSafeInteger(de)||de<=0||(Le.kind==="previous_year"?U(r,{...Le,offsetYears:de===1?void 0:de}):U(r,{...Le,offsetPeriods:de===1?void 0:de}))},className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Alignment"}),e.jsxs(t.Select,{value:Le.alignment||"calendar",onValueChange:X=>U(r,{...Le,alignment:X==="calendar"?void 0:X}),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,{value:"calendar",children:"Calendar"}),e.jsx(t.SelectItem,{value:"weekday",children:"Match weekdays"})]})]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"To date"}),e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Match the elapsed portion of an incomplete current window."})]}),e.jsx(t.Switch,{size:"xs",checked:Le.toDate===!0,onCheckedChange:X=>U(r,{...Le,toDate:X?!0:void 0})})]}),e.jsxs("p",{className:"text-[11px] leading-4 text-muted-foreground",children:["Anchored to"," ",e.jsx("span",{className:"text-foreground",children:(Se==null?void 0:Se.label)||(Se==null?void 0:Se.name)}),". The resolved comparison dates appear after the card runs."]})]}),as&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Favorable direction"}),e.jsxs(t.Select,{value:t.getMetricComparisonPolarity(ke),disabled:!!ke.semanticComparisonPolarity,onValueChange:X=>G(r,X),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,{value:"higher_is_better",children:"Higher is better"}),e.jsx(t.SelectItem,{value:"lower_is_better",children:"Lower is better"}),e.jsx(t.SelectItem,{value:"neutral",children:"Neutral"})]})]}),ke.semanticComparisonPolarity&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Governed by this metric's semantic definition."})]}),as&&((be=ke.comparison)==null?void 0:be.mode)==="explicit"&&ke.comparison.spec.kind==="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:ke.comparison.spec.targetValue!==void 0&&ke.comparison.spec.targetValue!==null?String(ke.comparison.spec.targetValue):"",onChange:X=>{const de=X.target.value;if(de===""){Ue(r,void 0);return}const we=Number(de);Ue(r,Number.isFinite(we)?we: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"}),(J==null?void 0:J.conditions)&&J.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:J.conditions.map(X=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{$(X),le(!0)},children:[e.jsxs("span",{className:"font-medium",children:[X.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(X.value)?X.value.length===1?String(X.value[0]):X.value.length<=2?X.value.join(", "):`${X.value.slice(0,2).join(", ")} +${X.value.length-2}`:String(X.value)})}),Array.isArray(X.value)&&X.value.length>1&&e.jsx(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 (",X.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:X.value.map((de,we)=>e.jsx("div",{children:String(de)},we))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var Qe;de.stopPropagation();const we=J.conditions.filter(He=>He.id!==X.id);if(we.length>0){const He={...J,conditions:we};bt(He)}else if(pe(void 0),a==="metrics"){const He={...s,parameters:{...s.parameters,filters:void 0}},nt=[...((Qe=h.config)==null?void 0:Qe.metricColumns)||[]];nt[r]=He,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:nt})}},children:e.jsx(oe.X,{className:"h-3 w-3"})})]},X.id))}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{$(null),le(!0)},children:[e.jsx(n.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Ui,{column:s}),l&&e.jsxs(e.Fragment,{children:[e.jsx(_i,{aliasTemplate:Xe,onAliasTemplateChange:qe}),e.jsx(Yi,{valueAliases:et,onValueAliasesChange:Je})]})]})};J!=null&&J.conditions&&J.conditions.length>0;const ir=a!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsxs(t.Popover,{modal:!0,open:Me,onOpenChange:Ee,children:[e.jsxs("div",{ref:m,style:es,className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",Me?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",p&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...c,...u,className:"inline-flex shrink-0 cursor-grab items-center text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing","aria-label":`Drag ${n.getMetricDisplayLabel(s)}`,onClick:K=>{K.stopPropagation()},children:e.jsx(n.GripVertical,{className:"h-3 w-3"})}),e.jsx(n.TypeGlyph,{dataType:ts,calculated:!!St}),e.jsx(_s,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n.getMetricDisplayLabel(s)}),a==="metrics"&&((kn=J==null?void 0:J.conditions)==null?void 0:kn.length)&&!Me&&e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex shrink-0 items-center gap-1 rounded-[3px] bg-primary/10 px-1 text-[10px] tabular-nums text-primary/90",children:[e.jsx(n.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:J.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:J.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a==="sortBy"&&e.jsx("button",{type:"button","aria-label":o==="asc"?"Switch to descending":"Switch to ascending",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:K=>{K.stopPropagation(),d(o==="asc"?"desc":"asc")},children:o==="asc"?e.jsx(n.ArrowUp,{className:"h-3 w-3"}):e.jsx(n.ArrowDown,{className:"h-3 w-3"})}),ir&&e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":"Field configuration",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground",onClick:K=>K.stopPropagation(),children:e.jsx(n.Ellipsis,{className:"h-3 w-3"})})}),e.jsx("button",{type:"button","aria-label":"Remove",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:K=>{K.stopPropagation(),qs()},children:e.jsx(oe.X,{className:"h-3 w-3"})})]}),e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsxs("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:[sr(),ar(),rr(),nr(),i==="kpi"&&Qs(),or(),lr()]})})]}),Pe&&e.jsx(Va,{open:Pe,onOpenChange:K=>{le(K),K||$(null)},availableFields:k,existingFilters:J,editingCondition:Ie,onSave:K=>{var be;if(K)bt(K);else if(pe(void 0),a==="metrics"){const X={...s,parameters:{...s.parameters,filters:void 0}},de=[...((be=h.config)==null?void 0:be.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(h.id,{metricColumns:de})}$(null)}}),De&&a==="metrics"&&pt&&e.jsx(n.CalculatedFieldEditor,{open:De,onOpenChange:ve,availableFields:y,existingField:gt,existingFieldScope:ut,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var At,xt;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=((At=be.config)==null?void 0:At.metricColumns)||[],Qe=((xt=be.config)==null?void 0:xt.sortByColumns)||[],He=ut==="dashboard"?S:X.calculatedFields||[],{nextActiveFields:nt,nextSortByFields:it,nextStoredFields:ht,nextSharedFields:yt}=n.saveCalculatedFieldToCardScope({activeFields:we,sortByFields:Qe,storedFields:be.calculatedFields||[],sharedFields:He,updatedField:K,editingField:gt,previousScope:ut});(nt||it)&&de.updateCardConfig(h.id,{...nt?{metricColumns:nt}:{},...it?{sortByColumns:it}:{}}),de.updateCard(h.id,{calculatedFields:ht}),ut==="dashboard"&&yt!==He?w(yt):yt!==He&&n.commitSharedCalculatedFields({nextSharedFields:yt,currentSharedFields:He,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b})},onSaveToSheet:K=>{var Kt,Ut;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=s,Qe=((Kt=be.config)==null?void 0:Kt.metricColumns)||[],He=((Ut=be.config)==null?void 0:Ut.sortByColumns)||[],nt=X.calculatedFields||[],{nextActiveFields:it,nextSortByFields:ht,nextStoredFields:yt,nextSheetFields:At,nextDashboardFields:xt}=n.saveCalculatedFieldToSheetScope({activeFields:Qe,sortByFields:He,storedFields:be.calculatedFields||[],sheetFields:nt,dashboardFields:S,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:gt,previousScope:ut});n.commitSharedCalculatedFields({nextSharedFields:At,currentSharedFields:nt,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),xt&&xt!==S&&w(xt),(it||ht)&&de.updateCardConfig(h.id,{...it?{metricColumns:it}:{},...ht?{sortByColumns:ht}:{}}),de.updateCard(h.id,{calculatedFields:yt})},onSaveToDashboard:K=>{var Kt,Ut;if(K.role!=="metric")return;const{card:be,frame:X,actions:de}=t.useEditorStore.getState(),we=s,Qe=((Kt=be.config)==null?void 0:Kt.metricColumns)||[],He=((Ut=be.config)==null?void 0:Ut.sortByColumns)||[],nt=X.calculatedFields||[],{nextActiveFields:it,nextSortByFields:ht,nextStoredFields:yt,nextSharedFields:At,nextSheetFields:xt}=n.saveCalculatedFieldToSharedScope({activeFields:Qe,sortByFields:He,storedFields:be.calculatedFields||[],sharedFields:S,sheetFields:nt,updatedField:{...K,id:we.id,aliasTemplate:we.aliasTemplate,valueAliases:we.valueAliases,parameters:we.parameters,customFormat:we.customFormat},editingField:gt,previousScope:ut});w(At),xt&&xt!==nt&&n.commitSharedCalculatedFields({nextSharedFields:xt,currentSharedFields:nt,isVisualEditing:M,selectedSheetId:N,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),(it||ht)&&de.updateCardConfig(h.id,{...it?{metricColumns:it}:{},...ht?{sortByColumns:ht}:{}}),de.updateCard(h.id,{calculatedFields:yt})},cardId:h.id})]})}function Zi({concept:s}){const{title:a,description:r}=ec[s];return e.jsxs(n.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(n.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${a} mean?`,className:"inline-flex h-3 w-3 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",children:e.jsx(n.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(n.HoverCardContent,{side:"right",align:"start",sideOffset:8,className:"w-[260px] space-y-2 rounded-control border border-border bg-popover p-3 shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[12px] font-semibold text-foreground",children:a}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(tc,{highlight:s})]})]})}const ec={groupBy:{title:"Rows",description:"Each unique value becomes a row. Use for the dimensions you want stacked vertically."},pivotBy:{title:"Pivot Columns",description:"Each unique value spreads across as a column, splitting your metrics horizontally."},metrics:{title:"Metrics",description:"The aggregated numbers (sum, count, avg…) that fill the cells of your chart or table."},detailColumns:{title:"Columns",description:"Raw column values with no aggregation — the underlying detail rows from the database."}};function tc({highlight:s}){const a=s==="pivotBy",r=s==="groupBy",o=s==="metrics",d="bg-foreground/[0.06] font-medium text-foreground dark:bg-foreground/[0.12]";return e.jsx("div",{className:"overflow-hidden rounded-control border border-border",children:e.jsxs("table",{className:"w-full text-[10px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-muted/40",children:[e.jsx("th",{className:"px-1.5 py-1 text-left font-normal text-muted-foreground"}),["North","South","East"].map(l=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",a&&d),children:l},l))]})}),e.jsx("tbody",{children:aa.map((l,i)=>e.jsxs("tr",{className:t.cn(i!==aa.length-1&&"border-b border-border/60"),children:[e.jsx("td",{className:t.cn("px-1.5 py-1 text-left text-muted-foreground",r&&d),children:l.label}),l.values.map((c,u)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&d),children:c},u))]},l.label))})]})})}const aa=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],sc={groupBy:n.Rows3,pivotBy:As,metrics:kr,detailColumns:t.Table2,sortBy:la};function Gt({zone:s,fields:a,label:r,placeholder:o,shouldShow:d,hasPivotColumns:l=!1,activeField:i=null}){const{isOver:c,setNodeRef:u}=n.useDroppable({id:s}),{updateSortByColumn:m}=t.useEditorActions(),x=t.useEditorStore(b=>b.card),g=t.useEditorStore(b=>b.card.type),p=a.length>0,h=C.useMemo(()=>!i||!c?!0:n.validateFieldForChartType(i,s,g).isValid,[i,c,s,g]),v=(b,w)=>{var S;!((S=x.config)!=null&&S.sortByColumns)||x.config.sortByColumns.findIndex(y=>y.id===b)===-1||m(x.id,b,{direction:w})};if(s==="sortBy"&&d===!1)return null;const M=s!=="sortBy"&&g!=="kpi",N=sc[s]||n.Plus;return e.jsxs("div",{className:"w-full",children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r}),e.jsx("div",{ref:u,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":c&&h,"border border-destructive/40 bg-destructive/5":c&&!h,"border border-dashed border-border/50 bg-background":!c&&!p}),children:a.length===0?e.jsxs("div",{className:"flex h-9 items-center justify-center gap-1.5 text-[11px] text-muted-foreground/80",children:[e.jsx(N,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:o}),M&&e.jsx(Zi,{concept:s})]}):e.jsx(n.SortableContext,{id:s,items:a.map(b=>b.id),strategy:n.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:a.map((b,w)=>{const S=b.direction;return e.jsx(Xi,{field:b,zone:s,index:w,sortDirection:S,onSortDirectionChange:y=>v(b.id,y),hasPivotColumns:l,cardType:g},b.id)})})})})]})}const nc=[];function ac({groupByFields:s,pivotByFields:a,metricsFields:r,sortByFields:o,detailFields:d,activeField:l}){var G,q,Q;const[i,c]=C.useState(!1);t.useEditorStore(H=>{var se;return!!((se=H.card.customCardPreferences)!=null&&se.url)});const u=t.useEditorStore(H=>H.card),m=t.useEditorStore(H=>H.frame),x=he.findCustomVisualConfigCard(m,u),{manifest:g}=n.useCustomVisual(((G=x==null?void 0:x.customCardPreferences)==null?void 0:G.url)||""),p=(q=g==null?void 0:g.visuals)==null?void 0:q.find(H=>{var se;return H.name===((se=x==null?void 0:x.customCardPreferences)==null?void 0:se.componentName)}),h=he.resolveMultiInputType(x,p)==="multiple";h&&((Q=x==null?void 0:x.customCardPreferences)!=null&&Q.url);const v=he.getConfigSlotExpectedType(p==null?void 0:p.slots),M=t.useEditorStore(H=>H.actions.updateCardConfig),N=t.useEditorStore(H=>H.actions.updateCard),b=t.useEditorStore(H=>H.actions.updateFrame),w=t.useDashboardStore(H=>H.isVisualEditing),F=t.useDashboardStore(H=>H.selectedSheetId),S=t.useDashboardStore(H=>H.actions.updateSheetCalculatedFields),y=t.useDashboardStore(H=>H.actions.updateDashboardCalculatedFields),E=t.useDashboardStore(H=>{var se;return H.visualEditPendingDashboardCalculatedFields??((se=H.dashboard)==null?void 0:se.calculatedFields)})??nc,{scopedFields:A}=n.useScopedFields(),{userContext:T}=n.useCurrentUserInfo(),I=h&&(x==null?void 0:x.id)===u.id&&v?v:u==null?void 0:u.type,L=I==="detailTable",j=s.length>0||r.length>0||d.length>0,P=!L&&(I!=="kpi"||r.length<=2),V=!L,f=!L&&I!=="kpi",O=I!=="kpi"&&j,D=L,R="Drop sort fields here",B=n.canEditLocalCalculatedFields(T),Y=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(I),_=f&&!Y,z=()=>I==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},U=()=>I==="kpi"?{label:"Metric",placeholder:"Drop metric here"}:{label:"Metrics",placeholder:"Drop metrics here"};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between bg-background px-4 py-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Fields"}),j&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:()=>{M(u.id,{groupByColumns:[],pivotByColumns:[],metricColumns:[],sortByColumns:[],detailColumns:[]})},className:"text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:"Reset"})]}),e.jsxs("div",{className:"space-y-3 px-4 pb-6 pt-3",children:[P&&e.jsx(Gt,{zone:"groupBy",fields:s,label:z().label,placeholder:z().placeholder,activeField:l}),_&&e.jsx(Gt,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:l}),V&&e.jsx(Gt,{zone:"metrics",fields:r,label:U().label,placeholder:U().placeholder,hasPivotColumns:a.length>0,activeField:l}),D&&e.jsx(Gt,{zone:"detailColumns",fields:d,label:"Columns",placeholder:"Drop columns here"}),r.length>=1&&B&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>c(!0),className:"mt-1.5 w-full justify-start border-border/60 border-dashed bg-background text-xs text-foreground/70 hover:bg-muted/40 hover:text-foreground",children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),O&&e.jsx(Gt,{zone:"sortBy",fields:o,label:"Sort By",placeholder:R,activeField:l})]}),e.jsx(n.CalculatedFieldEditor,{open:i,onOpenChange:c,availableFields:A,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:H=>{if(H.role!=="metric")return;const{nextStoredFields:se}=n.saveCalculatedFieldToCardScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:m.calculatedFields||[],updatedField:H,previousScope:"card"});N(u.id,{calculatedFields:se})},onSaveToSheet:H=>{if(H.role!=="metric")return;const se=m.calculatedFields||[],{nextSheetFields:ce}=n.saveCalculatedFieldToSheetScope({activeFields:r,storedFields:u.calculatedFields||[],sheetFields:se,updatedField:H,previousScope:"sheet"});n.commitSharedCalculatedFields({nextSharedFields:ce,currentSharedFields:se,isVisualEditing:w,selectedSheetId:F,updateFrame:b,updateSheetCalculatedFields:S})},onSaveToDashboard:H=>{if(H.role!=="metric")return;const{nextSharedFields:se}=n.saveCalculatedFieldToSharedScope({activeFields:r,storedFields:u.calculatedFields||[],sharedFields:E,updatedField:H,previousScope:"dashboard"});y(se)},cardId:u.id})]})}function rc(){var w,F,S;const s=t.useEditorStore(y=>{var k;return(k=y.card)==null?void 0:k.type}),a=s==="kpi",[r,o]=C.useState(a),[d,l]=C.useState(!1),i=t.useEditorStore(y=>{var k;return!!((k=y.card.customCardPreferences)!=null&&k.url)}),c=t.useEditorStore(y=>y.card),u=t.useEditorStore(y=>y.frame),m=he.findCustomVisualConfigCard(u,c),{manifest:x}=n.useCustomVisual(((w=m==null?void 0:m.customCardPreferences)==null?void 0:w.url)||""),g=(F=x==null?void 0:x.visuals)==null?void 0:F.find(y=>{var k;return y.name===((k=m==null?void 0:m.customCardPreferences)==null?void 0:k.componentName)}),h=he.resolveMultiInputType(m,g)==="multiple"&&!!((S=m==null?void 0:m.customCardPreferences)!=null&&S.url),v=!i||h,M=i||h,N=a?"KPI Settings":"Chart Settings",b=v&&!t.isTableChartType(s);return C.useEffect(()=>{a&&o(!0)},[a]),!b&&!M?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[b&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",a?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(n.Accordion,{type:"single",collapsible:!0,className:"w-full divide-y divide-border/60 [&_h3]:sticky [&_h3]:top-0 [&_h3]:z-10 [&_h3]:bg-background",children:e.jsx(Oa,{mode:"config"})})}),b&&e.jsxs("button",{type:"button",onClick:()=>o(y=>!y),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(n.Settings2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:N})]}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),M&&d&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Ma,{})}),M&&e.jsxs("button",{type:"button",onClick:()=>l(y=>!y),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",b&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ia,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/70",children:"Component settings"})]}),e.jsx(oe.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",d&&"rotate-180"),strokeWidth:1.75})]})]})}function oc({onEditJoins:s}){const a=t.useEditorStore(u=>u.card),{autoJoinMetadata:r}=n.useEditorCardQuery(a);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,d=(o==null?void 0:o.joins)||[];if(d.length===0)return null;const l=u=>!u||u.length===0?"No conditions":u.map(m=>{var h,v,M,N;const x=`${(h=m.source)==null?void 0:h.entityName}.${(v=m.source)==null?void 0:v.name}`,g=`${(M=m.target)==null?void 0:M.entityName}.${(N=m.target)==null?void 0:N.name}`,p=m.operator||"=";return`${x} ${p} ${g}`}).join(" AND "),i=u=>!u.joinKeyGroups||u.joinKeyGroups.length===0?"No conditions defined":u.joinKeyGroups.length===1?l(u.joinKeyGroups[0].keys):u.joinKeyGroups.map((m,x)=>({id:x,operator:m.operator,condition:l(m.keys)})),c=e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"shrink-0 cursor-help rounded-control px-1 font-mono text-[10px] tabular-nums text-muted-foreground/70 transition-colors hover:bg-muted hover:text-foreground","aria-label":`${d.length} resolved ${d.length===1?"join":"joins"}`,children:d.length})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-md border border-border bg-popover p-2 text-popover-foreground shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:e.jsx("div",{className:"space-y-2",children:d.map((u,m)=>{const x=i(u),g=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2 text-foreground",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:u.source.name}),e.jsx(n.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:u.target.name})]}),e.jsx("span",{className:"shrink-0 rounded-[3px] border border-border px-1 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground",children:u.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:g?x.map(p=>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:p.condition}),p.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",p.operator,")"]})]},p.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:x})})})]},u.id||m)})})})]})});return e.jsxs("div",{className:"flex h-7 w-full items-center gap-2 rounded-control border border-input bg-background px-2 text-left transition-colors hover:bg-muted",children:[e.jsx(n.Link,{className:"h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-foreground",children:"Resolved joins"}),c,s&&e.jsx("button",{type:"button",onClick:s,className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:border-ring","aria-label":"Edit resolved joins",children:e.jsx(n.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function lc({selectedChart:s,onChartChange:a,isVisible:r=!0,onToggleVisibility:o,groupByFields:d,pivotByFields:l,metricsFields:i,sortByFields:c,detailFields:u,activeField:m}){var E,A;const[x,g]=C.useState(!1),p=t.useEditorStore(T=>T.card),h=t.useEditorStore(T=>T.editorContext),v=t.useEditorStore(T=>T.actions.updateCardConfig),M=(h==null?void 0:h.type)==="documentSection",{autoJoinMetadata:N}=n.useEditorCardQuery(p),b=((E=p==null?void 0:p.config)==null?void 0:E.joinPlan)||(N!=null&&N.autoResolved?N.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),w=((A=p==null?void 0:p.dataSource)==null?void 0:A.selectedEntities)||[],F=T=>{v(p.id,{...p==null?void 0:p.config,joinPlan:T}),g(!1)},S=()=>{v(p.id,{...p==null?void 0:p.config,joinPlan:void 0}),g(!1)},y=()=>{g(!1)},k=()=>{g(!0)};return r?e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[325px] min-w-[325px] shrink-0 flex-col overflow-hidden border-r border-border bg-background transition-all duration-300 ease-in-out",children:[!M&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Vo,{selectedChart:s,onChartChange:a})}),o&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(n.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:o,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(n.ChevronLeft,{className:"h-4 w-4",strokeWidth:1.75})})})]}),e.jsxs(t.ScrollArea,{className:"min-h-0 w-full flex-1 basis-0 border-t border-border [&>[data-radix-scroll-area-viewport]]:overscroll-none [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[e.jsx("div",{className:"px-4 pt-4 empty:hidden",children:e.jsx(oc,{onEditJoins:k})}),e.jsx(ac,{groupByFields:d,pivotByFields:l,metricsFields:i,sortByFields:c,detailFields:u,activeField:m})]}),e.jsx(rc,{}),e.jsx(ua,{open:x,onOpenChange:g,joinPlan:b,availableDataSources:w,onSave:F,onCancel:y,onRemove:S,children:e.jsx("div",{})})]}):e.jsx("div",{"data-content":"Chart Configuration Panel (collapsed)",className:"flex w-9 shrink-0 flex-col items-center border-r border-border bg-background transition-all duration-300 ease-in-out",children:o&&e.jsx(n.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:o,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(Ye.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function ic({initialFilters:s,availableFields:a}={}){const[r,o]=C.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(S=>S.card.dataSource);const{filterableFields:d,isLoading:l}=n.useFilterableFields(),i=a||d||[],c={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=S=>{const y=k=>{if(k.id===S){const E=i[0]||c,A=t.getDataType(E.dataType)==="date";return{...k,conditions:[...k.conditions,{id:`condition-${Date.now()}`,field:E,operator:A?"between":"=",value:A?[]:""}]}}return{...k,groups:k.groups.map(y)}};o(y(r))},m=S=>{const y=k=>{if(k.id===S){const E=i[0]||c,A=t.getDataType(E.dataType)==="date";return{...k,groups:[...k.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:A?"between":"=",value:A?[]:""}],groups:[]}]}}return{...k,groups:k.groups.map(y)}};o(y(r))},x=(S,y)=>{const k=E=>E.id===S?{...E,conditions:E.conditions.filter(A=>A.id!==y)}:{...E,groups:E.groups.map(k)};o(k(r))},g=(S,y)=>{const k=E=>E.id===S?{...E,groups:E.groups.filter(A=>A.id!==y)}:{...E,groups:E.groups.map(k)};o(k(r))},p=(S,y,k,E)=>{if(k==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const A=T=>T.id===S?{...T,conditions:T.conditions.map(I=>I.id===y?{...I,[k]:E}:I)}:{...T,groups:T.groups.map(A)};o(A(r))},h=(S,y,k)=>{const E=A=>A.id===S?{...A,conditions:A.conditions.map(T=>T.id===y?{...T,...k}:T)}:{...A,groups:A.groups.map(E)};o(E(r))},v=(S,y)=>{const k=E=>E.id===S?{...E,logicalOperator:y}:{...E,groups:E.groups.map(k)};o(k(r))},M=(S,y)=>{const k=E=>E.id===S?{...E,negate:y}:{...E,groups:E.groups.map(k)};o(k(r))},N=(S,y,k)=>{const E=A=>A.id===S?{...A,conditions:n.arrayMove(A.conditions,y,k)}:{...A,groups:A.groups.map(E)};o(E(r))},b=(S,y,k)=>{const E=A=>A.id===S?{...A,groups:n.arrayMove(A.groups,y,k)}:{...A,groups:A.groups.map(E)};o(E(r))},w=S=>{if(!S||S.conditions.length===0&&S.groups.length===0)return"-- No filters defined";const y=E=>{let A="";typeof E.field=="object"?A=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:A=String(E.field);const T=E.operator;let I=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof I=="string"?I=`'${I}'`:Array.isArray(I)&&(I=`'${I.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(I)&&I.length===2){const L=I[0]?`'${I[0]}'`:"NULL",j=I[1]?`'${I[1]}'`:"NULL";return`${A} BETWEEN ${L} AND ${j}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(I)){const L=I.map(j=>j?`'${j}'`:"NULL").join(", ");return`${A} ${T} (${L})`}else typeof I=="string"||I instanceof Date?I=`'${I}'`:Array.isArray(I)&&I.length>0&&(I=`'${I[0]}'`);else if(["in","not in"].includes(E.operator)){let L=[];Array.isArray(I)?L=I.map(j=>typeof j=="string"?`'${j}'`:String(j)):typeof I=="string"?L=I.split(",").map(j=>{const P=j.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof I=="number"&&(L=[String(I)]),I=`(${L.join(", ")})`}switch(T){case"contains":return typeof I=="string"?`${A} LIKE '%${I.replace(/'/g,"")}'`:`${A} LIKE '%${String(I)}'`;case"startsWith":return typeof I=="string"?`${A} LIKE '${I.replace(/'/g,"")}%'`:`${A} LIKE '${String(I)}%'`;case"endsWith":return typeof I=="string"?`${A} LIKE '%${I.replace(/'/g,"")}'`:`${A} LIKE '%${String(I)}'`;case"isNull":return`${A} IS NULL`;case"isNotNull":return`${A} IS NOT NULL`;default:return`${A} ${T} ${I}`}},k=E=>{const A=E.conditions.map(y),T=E.groups.map(P=>k(P)),I=[...A,...T].filter(Boolean);if(I.length===0)return"";const L=I.join(` ${E.logicalOperator} `),j=I.length>1?`(${L})`:L;return E.negate?`NOT ${j}`:j};return k(S)},F=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:i,isLoading:l,addCondition:u,addGroup:m,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:h,updateGroupOperator:v,updateGroupNegate:M,reorderConditions:N,reorderGroups:b,generateSQLPreview:w,hasAnyFilters:F}}function cc({children:s,className:a,delayDuration:r}){return e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{delayDuration:r,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 dc=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function uc({value:s,onValueChange:a,availableFields:r,placeholder:o="Select field",className:d="w-64"}){const[l,i]=C.useState(!1),c=C.useMemo(()=>{const u={};return r.forEach(m=>{const x=dc(m);u[x]||(u[x]={}),u[x][m.entityId]||(u[x][m.entityId]=[]),u[x][m.entityId].push(m)}),u},[r]);return e.jsxs(t.Popover,{modal:!0,open:l,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:t.cn("justify-between",!s&&"text-muted-foreground",d),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(cc,{children:[s.entityName,".",s.name]})}):o,e.jsx(n.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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(n.CommandEmpty,{children:"No fields found."}),e.jsx(n.CommandList,{className:"max-h-80",children:Object.entries(c).map(([u,m])=>e.jsx(n.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(n.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(m).map(([x,g])=>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:[n.getEntityIcon(g[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:g[0].entityName})]}),g.map((p,h)=>e.jsxs(n.CommandItem,{value:p.id,onSelect:()=>{a(p),i(!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)===p.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:p.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:p.description&&e.jsx("span",{children:p.description})})]})]},p.id+h))]},`${u}-${x}`))},u))})]})})]})}function Ys(s){var N;const a=t.useEditorStore(b=>b.card),{authToken:r,tokenProps:o}=n.useSemaphorContext(),d=t.useDashboardStore(b=>{var w;return((w=b.reportContext)==null?void 0:w.calendar)??null}),l=t.useEditorStore(b=>b.card.config),i=l==null?void 0:l.joinPlan,c={...s,alias:s.name,label:"value",role:"groupby"},u={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},m={...c,role:"sortby",direction:"asc"},x={joinPlan:i,groupByColumns:[c],metricColumns:[u],sortByColumns:[m]},g=((N=a.dataSource)==null?void 0:N.connectionId)||a.connectionId,{data:p,isPending:h,error:v}=n.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName,d],queryFn:async()=>{try{return await t.postRequestRegular(`${o.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",{connection_id:g,cardConfig:x,cardDataSource:a.dataSource,calendarContext:d})}catch(b){console.log(s),console.error("error",b)}},enabled:!!g&&!!d,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((p==null?void 0:p.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:h,error:v}}function mc({field:s,selected:a,onChange:r,placeholder:o="Select items...",className:d}){const[l,i]=hr.useState(!1),{filterValues:c}=Ys(s),u=x=>{r(a.filter(g=>g!==x))},m=x=>{a.includes(x)?r(a.filter(g=>g!==x)):r([...a,x])};return e.jsx("div",{className:t.cn("w-full",d),children:e.jsxs(t.Popover,{open:l,onOpenChange:i,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":l,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const g=c.find(p=>p.value===x);return e.jsxs(n.Badge,{variant:"secondary",className:"text-xs",children:[g==null?void 0:g.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:p=>{p.key==="Enter"&&u(x)},onMouseDown:p=>{p.preventDefault(),p.stopPropagation()},onClick:p=>{p.stopPropagation(),u(x)},children:e.jsx(oe.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},x)}):e.jsx("span",{className:"text-muted-foreground",children:o})}),e.jsx(oe.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(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No results found."}),e.jsx(n.CommandGroup,{children:c.map((x,g)=>e.jsxs(n.CommandItem,{onSelect:()=>m(x.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(x.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.count})]})]},x.value+g))})]})]})})]})})}function xc({field:s,value:a,onChange:r,placeholder:o="Select value...",className:d}){const{filterValues:l,isPending:i,error:c}=Ys(s);return i?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):c?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:r,children:[e.jsx(t.SelectTrigger,{className:d||"flex-1",children:e.jsx(t.SelectValue,{placeholder:o,children:a})}),e.jsx(t.SelectContent,{children:l.map((u,m)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+m))})]})}function hc({value:s,operator:a,onChange:r,className:o}){const d=n.useTimezone(),l=a==="between"||a==="not between",i=C.useMemo(()=>{if(!(!s||!l)&&Array.isArray(s)&&s.length===2){const g=s[0]?new Date(s[0]):void 0,p=s[1]?new Date(s[1]):void 0;if(g&&p)return{from:g,to:p}}},[s,l]),c=C.useMemo(()=>{if(!s||l)return;const g=Array.isArray(s)?s[0]:s;if(!g)return;const p=new Date(g);if(!isNaN(p.getTime()))return p},[s,l]),u=g=>a==="<="||a===">"?t.endOfDayInTimezone(g,d):t.startOfDayInTimezone(g,d),m=g=>{if(!g){r([]);return}if(g.from&&g.to){r([g.from.toISOString(),g.to.toISOString()]);return}r([])},x=g=>{if(!g){r("");return}const p=u(g);r(p.toISOString())};return e.jsx(n.DateRangePicker,{value:l?i:void 0,selectionMode:l?"range":"single",singleValue:l?void 0:c,onChange:m,onSingleChange:x,timezone:d,showRelativeTab:l,className:o,placeholder:"Select date..."})}const zs=["contains","startsWith","endsWith","like","not like"],pc=["=","!=",">",">=","<","<=",...zs,"in","not in","isNull","isNotNull"],fc=["=","!=",...zs,"in","not in","isNull","isNotNull"],gc=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],bc=["=","!=","isNull","isNotNull"],jc=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],vc={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",like:"Like","not like":"Not Like",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function ra(s){return vc[s]||t.titleCase(s)}function yc(s){switch(s){case"string":return fc;case"number":return gc;case"boolean":return bc;case"date":return jc;default:return pc}}function _a({condition:s,index:a,groupId:r,groupLogicalOperator:o,onUpdateCondition:d,onRemoveCondition:l,onUpdateGroupOperator:i,availableFields:c,updateConditionFields:u}){const{attributes:m,listeners:x,setNodeRef:g,transform:p,transition:h,isDragging:v}=n.useSortable({id:s.id}),{isPending:M,error:N}=Ys(s.field),b={transform:n.CSS.Transform.toString(p),transition:h};return e.jsxs("div",{ref:g,style:b,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${v?"z-50 opacity-50":""}`,children:[e.jsx("div",{...m,...x,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:o,onValueChange:w=>i(r,w),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(uc,{value:s.field,onValueChange:w=>{const F=w,S=t.getDataType(F.dataType)==="date";u(r,s.id,{field:F,value:"",operator:S?"between":"="})},availableFields:c,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:w=>{w==="in"||w==="not in"?u(r,s.id,{operator:w,value:[]}):w==="isNull"||w==="isNotNull"?u(r,s.id,{operator:w,value:null}):w==="between"||w==="not between"?u(r,s.id,{operator:w,value:[]}):u(r,s.id,{operator:w,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-32",children:e.jsx(t.SelectValue,{children:s.operator?ra(s.operator):""})}),e.jsx(t.SelectContent,{children:yc(t.getDataType(s.field.dataType)).map(w=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:w,children:ra(w)},w))})]}),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"?M?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..."]}):N?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(mc,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(w=>typeof w=="string")?s.value:[],onChange:w=>u(r,s.id,{value:w}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):zs.includes(s.operator)?e.jsx(t.Input,{value:typeof s.value=="string"?s.value:"",onChange:w=>u(r,s.id,{value:w.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(xc,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:w=>u(r,s.id,{value:w}),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:w=>u(r,s.id,{value:w==="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(hc,{value:s.value,operator:s.operator,onChange:w=>u(r,s.id,{value:w}),className:"flex-1"}):e.jsx(t.Input,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:w=>d(r,s.id,"value",w.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:()=>l(r,s.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]})}function Cc({group:s,depth:a,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:d,onRemoveGroup:l,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:u,onReorderConditions:m,onReorderGroups:x,onAddCondition:g,onAddGroup:p,availableFields:h,renderFilterGroup:v,updateConditionFields:M}){const{attributes:N,listeners:b,setNodeRef:w,transform:F,transition:S,isDragging:y}=n.useSortable({id:s.id}),k={transform:n.CSS.Transform.toString(F),transition:S},E=T=>{const{active:I,over:L}=T;if(L&&I.id!==L.id){const j=s.conditions.findIndex(V=>V.id===I.id),P=s.conditions.findIndex(V=>V.id===L.id);j!==-1&&P!==-1&&m(s.id,j,P)}},A=T=>{const{active:I,over:L}=T;if(L&&I.id!==L.id&&r){const j=s.groups.findIndex(V=>V.id===I.id),P=s.groups.findIndex(V=>V.id===L.id);j!==-1&&P!==-1&&x(r,j,P)}};return e.jsxs("div",{ref:w,style:k,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${y?"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",{...N,...b,className:"cursor-grab active:cursor-grabbing",children:e.jsx(n.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>d(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:T=>o(s.id,T),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:()=>r&&l(r,s.id),children:e.jsx(n.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:E,children:e.jsx(n.SortableContext,{items:s.conditions.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.conditions.map((T,I)=>e.jsx(_a,{condition:T,index:I,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:i,onUpdateField:c,onRemoveCondition:u,onUpdateGroupOperator:o,availableFields:h,updateConditionFields:M},T.id))})}),e.jsx(n.DndContext,{sensors:n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),collisionDetection:n.closestCenter,onDragEnd:A,children:e.jsx(n.SortableContext,{items:s.groups.map(T=>T.id),strategy:n.verticalListSortingStrategy,children:s.groups.map(T=>v(T,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:()=>g(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>p(s.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Nc({filters:s,availableFields:a,onSave:r,onClearAll:o,onCancel:d}){const{currentFilters:l,availableFields:i,isLoading:c,addCondition:u,addGroup:m,removeCondition:x,removeGroup:g,updateCondition:p,updateConditionFields:h,updateGroupOperator:v,updateGroupNegate:M,reorderConditions:N,reorderGroups:b,generateSQLPreview:w,hasAnyFilters:F,setCurrentFilters:S}=ic({initialFilters:s,availableFields:a}),y=n.useSensors(n.useSensor(n.PointerSensor),n.useSensor(n.KeyboardSensor,{coordinateGetter:n.sortableKeyboardCoordinates})),[k,E]=C.useState(!1),A=(L,j,P)=>{const V=f=>f.id===L?{...f,conditions:f.conditions.map(O=>O.id===j?{...O,field:P,dataType:P.dataType}:O)}:{...f,groups:f.groups.map(V)};S(V(l))},T=(L,j=0,P)=>j===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(n.DndContext,{sensors:y,collisionDetection:n.closestCenter,onDragEnd:V=>{const{active:f,over:O}=V;if(O&&f.id!==O.id){const D=L.conditions.findIndex(B=>B.id===f.id),R=L.conditions.findIndex(B=>B.id===O.id);D!==-1&&R!==-1&&N(L.id,D,R)}},children:e.jsx(n.SortableContext,{items:L.conditions.map(V=>V.id),strategy:n.verticalListSortingStrategy,children:L.conditions.map((V,f)=>e.jsx(_a,{condition:V,index:f,groupId:L.id,groupLogicalOperator:L.logicalOperator,onUpdateCondition:p,onUpdateField:A,onRemoveCondition:x,onUpdateGroupOperator:v,availableFields:i,updateConditionFields:h},V.id))})}),e.jsx(n.DndContext,{sensors:y,collisionDetection:n.closestCenter,onDragEnd:V=>{const{active:f,over:O}=V;if(O&&f.id!==O.id){const D=L.groups.findIndex(B=>B.id===f.id),R=L.groups.findIndex(B=>B.id===O.id);D!==-1&&R!==-1&&b(L.id,D,R)}},children:e.jsx(n.SortableContext,{items:L.groups.map(V=>V.id),strategy:n.verticalListSortingStrategy,children:L.groups.map(V=>T(V,j+1,L.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:()=>u(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),k&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>m(L.id),children:[e.jsx(n.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},L.id):e.jsx(Cc,{group:L,depth:j,parentGroupId:P,onUpdateGroupOperator:v,onUpdateGroupNegate:M,onRemoveGroup:g,onUpdateCondition:p,onUpdateField:A,onRemoveCondition:x,onReorderConditions:N,onReorderGroups:b,onAddCondition:u,onAddGroup:m,availableFields:i,renderFilterGroup:T,updateConditionFields:h},L.id),I=n.getFilterCount(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(n.Card,{children:e.jsx(n.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[c?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):T(l),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Switch,{size:"sm",id:"advanced-mode",checked:k,onCheckedChange:L=>E(L)}),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)"})]})}),F&&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:w(l)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:d,children:"Cancel"}),I>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:o,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>r(F?l:null),children:"Apply Filters"})]})]})}function Sc({cardId:s,filters:a,onFiltersChange:r,onClearFilters:o,availableFields:d,isOpen:l,onOpenChange:i}){const c=m=>{r(s,m),i(!1)},u=()=>{o(s),i(!1)};return e.jsxs(n.Dialog,{modal:!1,open:l,onOpenChange:i,children:[l&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(n.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:m=>{m.preventDefault()},children:[e.jsxs(n.DialogHeader,{children:[e.jsx(n.DialogTitle,{children:"Card Filters"}),e.jsx(n.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Nc,{filters:a,availableFields:d,onSave:c,onCancel:()=>i(!1),onClearAll:u})]})]})}function wc({activeCardId:s,sourceFields:a,getFieldsForContainer:r,setFieldsForContainer:o}){var w,F;const[d,l]=C.useState(null),i=t.useEditorStore(S=>S.card),c=t.useEditorStore(S=>S.actions.updateCardConfig),u=t.useEditorStore(S=>S.actions.setCardPreferences),m=(w=i==null?void 0:i.config)==null?void 0:w.joinPlan,x=C.useCallback(S=>S.entityName===mr.CALCULATED_FIELD_ENTITY_MARKER||S.entityName==="calculated_fields"||S.qualifiedEntityName==="calculated_fields",[]),g=(F=i==null?void 0:i.dataSource)==null?void 0:F.semanticDomainId,{data:p}=n.useJoinabilityMap(g),h=[...a,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],v=C.useCallback(S=>S.startsWith("card-source-")?"source":S.startsWith("card-")?null:S.startsWith("source-")||a.find(y=>y.id===S)?"source":r("groupBy").find(y=>y.id===S)?"groupBy":r("metrics").find(y=>y.id===S)?"metrics":r("pivotBy").find(y=>y.id===S)?"pivotBy":r("sortBy").find(y=>y.id===S)?"sortBy":r("detailColumns").find(y=>y.id===S)?"detailColumns":null,[a,r]),M=C.useCallback(S=>{l(S.active.id)},[]),N=C.useCallback(S=>{var L;const{active:y,over:k}=S;if(!k||!s){l(null);return}const E=y.id,A=k.id,T=v(E),I=v(A)||A;if(I==="sortBy"){if(T==="source"){const j=a.find(V=>V.id===E);if(!j){l(null);return}if(!(r("groupBy").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName)||r("metrics").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName)||r("detailColumns").some(V=>V.name===j.name&&V.qualifiedEntityName===j.qualifiedEntityName))){l(null);return}}else if(T==="pivotBy"){l(null);return}else if(T!=="groupBy"&&T!=="metrics"&&T!=="sortBy"&&T!=="detailColumns"){l(null);return}}if(T==="source"&&I==="sortBy"){const j=[...a].find(O=>O.id===E);if(!j){l(null);return}const P=r("sortBy");if(n.fieldAlreadyExists(j,P)){l(null);return}const V=n.validateFieldForChartType(j,"sortBy",i.type);if(!V.isValid){n.ue.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3}),l(null);return}const f=n.getNewField(j,"sortBy",P);l(null),o("sortBy",[...P,f]);return}if(T==="source"&&I!=="source"&&I!=="sortBy"){const j=[...a].find(B=>B.id===E);if(!j){l(null);return}const P=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],V=P.filter(B=>!x(B));if(V.length>0){const B=V[0].qualifiedEntityName;if(!B){l(null);return}if(B!==j.qualifiedEntityName&&!x(j)&&j.qualifiedEntityName)if(g&&(p!=null&&p.joinabilityMap)){if(n.calculateFieldState(j,{joinabilityMap:p.joinabilityMap,selectedFields:P,baseEntityName:(L=m==null?void 0:m.baseEntity)==null?void 0:L.name,datasetAliases:p.datasets}).state==="unreachable"){n.showJoinRequiredNotification(),l(null);return}}else{if(!m){n.showJoinRequiredNotification(),l(null);return}if(!n.areEntitiesJoined(B,j.qualifiedEntityName,m)){n.showJoinRequiredNotification(),l(null);return}}}const f=r(I);if(n.fieldAlreadyExists(j,f)){l(null);return}const O=n.validateFieldForChartType(j,I,i.type);if(!O.isValid){n.ue.error("Invalid Field Type",{description:O.reason,position:"top-center",duration:3e3}),l(null);return}const D=n.getNewField(j,I,f),R=[...f,D];if(l(null),o(I,R),I==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,D,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,c,s,R)}return}if(T&&I&&T!=="source"&&I!=="source"&&T!==I){const j=r(T),P=r(I),V=j.find(B=>B.id===E);if(!V){l(null);return}const f=n.validateFieldForChartType(V,I,i.type);if(!f.isValid){n.ue.error("Invalid Field Type",{description:f.reason,position:"top-center",duration:3e3}),l(null);return}const O=n.getNewField(V,I,P);if(l(null),I==="sortBy"){n.fieldAlreadyExists(V,P)||o(I,[...P,O]);return}const D=j.filter(B=>B.id!==E),R=[...P,O];if(o(T,D),o(I,R),I==="metrics"&&s){const B=n.seedSemanticMetricFormatDefaults(i,O,i.preferences);B&&u(B),n.cleanupKpiMetricComparisonMode(i.type,i.config,c,s,R)}return}if(T&&I&&T===I&&T!=="source"){const j=r(T),P=j.findIndex(f=>f.id===E),V=j.findIndex(f=>f.id===A);if(P!==V){const f=n.arrayMove(j,P,V);o(T,f)}}l(null)},[s,a,r,o,v,m,g,p,x,i,c,u]),b=d?h.find(S=>S.id===d):null;return{activeId:d,activeField:b,handleDragStart:M,handleDragEnd:N}}function Tc({activeView:s,onViewChange:a,splitViewEnabled:r,hasQueryError:o=!1}){const d=t.useEditorStore(m=>m.card),{config:l}=C.useContext(n.SemaphorContext).tokenProps,i=(l==null?void 0:l.showInfoTab)!==!1,c=()=>r?!1:t.getVisualizationMode(d)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(d.type),u=[{id:"chart",label:"Chart"}];return c()&&u.push({id:"table",label:"Results"}),i&&u.push({id:"info",label:o?"Error":"Info",isError:o}),e.jsx(t.Tabs,{value:s,onValueChange:m=>a(m),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:u.map(m=>e.jsx(t.TabsTrigger,{value:m.id,className:t.cn("px-0 text-[13px]",m.isError&&"text-destructive hover:text-destructive focus-visible:text-destructive data-[state=active]:border-destructive data-[state=active]:text-destructive"),children:m.label},m.id))})})}const Ec=[{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 Ic(){var u,m;const s=t.useEditorStore(x=>x.card),{updateRowLimit:a}=t.useEditorActions(),[r,o]=C.useState(!1),[d,l]=C.useState(""),i=x=>{if(x==="custom"){o(!0);return}o(!1),a(s.id,parseInt(x))},c=x=>{const g=x.target.value;l(g),g&&!isNaN(parseInt(g))&&a(s.id,parseInt(g))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:d,onChange:c,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((m=(u=s.config)==null?void 0:u.rowLimit)==null?void 0:m.toString())||"100",onValueChange:i,children:[e.jsxs(t.SelectTrigger,{className:"mb-0.5 h-auto w-auto gap-1.5 border-none bg-transparent px-0.5 pb-2.5 pt-0 text-[13px] font-normal text-muted-foreground shadow-none transition-colors hover:text-foreground focus:ring-0 focus:ring-offset-0 [&>svg]:hidden",children:[e.jsx(n.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:Ec.map(x=>e.jsx(t.SelectItem,{value:x.value,children:x.label},x.value))})]})})}function Dc({card:s,queryData:a,isLoading:r,isFetching:o,pagination:d,onPaginationChange:l,onSortChange:i,sortState:c,splitViewEnabled:u,isDynamicInspectorOpen:m,onDynamicInspectorOpenChange:x}){var v,M;const g=C.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]),p=t.getVisualizationMode(s)==="dynamic",h=e.jsx(kt,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Ia,{fallbackPreview:e.jsx(kt,{}),records:g,title:s.title,isInspectorOpen:m,onInspectorOpenChange:x})});return p?u?e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:h}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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 px-4 py-4",children:[(r||o)&&(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(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,resultColumns:a==null?void 0:a.columns,columnKeyMap:a==null?void 0:a.columnKeyMap,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,comparisonMetadata:(v=a==null?void 0:a.metadata)==null?void 0:v.comparisonMetadata,paginationMetadata:d,onPaginationChange:l,isLoading:r||o,onSortChange:i,sortState:c})]})})]}):h:!u||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(kt,{}):e.jsxs(n.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(n.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(kt,{})}),e.jsx(n.ResizableHandle,{withHandle:!0}),e.jsx(n.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:[(r||o)&&(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(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(a==null?void 0:a.records)&&e.jsx(n.TableVisual,{card:s,data:g,resultColumns:a==null?void 0:a.columns,columnKeyMap:a==null?void 0:a.columnKeyMap,totalsByColumnId:a==null?void 0:a.tableTotalsByColumnId,comparisonMetadata:(M=a==null?void 0:a.metadata)==null?void 0:M.comparisonMetadata,paginationMetadata:d,onPaginationChange:l,isLoading:r||o,onSortChange:i,sortState:c})]})})]})}function kc(s,a){const[r,o]=C.useState(()=>{const d=localStorage.getItem(s);return d?JSON.parse(d):a});return C.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const Mc="semaphor-split-view-enabled";function Ac(){return kc(Mc,!0)}function Lc({showInfoTab:s}){return e.jsx(n.VisualErrorState,{className:"min-h-[240px]",description:s?"See the Error tab for details and troubleshooting options.":"Contact your administrator for help resolving this issue."})}function Fc({card:s,effectiveCardType:a=s.type,queryResultColumns:r}){return t.supportsRegularTableSettings(a)?e.jsxs(n.Sheet,{modal:!1,children:[e.jsx(n.SheetTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"Table settings",className:"h-7 w-7 rounded-[5px] p-0",buttonProps:{type:"button","aria-label":"Table settings"},children:e.jsx(n.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),e.jsxs(n.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(n.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(n.SheetDescription,{className:"sr-only",children:"Configure table presentation and conditional formatting."}),e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:"Table settings"}),e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Settings apply to this table and document exports that reuse it."})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:e.jsx(Pa,{cardType:a,queryResultColumns:r,focusSection:"style"})})]})]}):null}function Rc({className:s,visible:a}){const r=t.useDashboardStore(c=>c.selectedFrameId),o=n.useManagementStore(c=>c.selectedVisual),d=t.useEditorStore(c=>c.frame),i=!!!(d!=null&&d.visualId||o!=null&&o.id)&&!!r;return!a||i?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(Nt.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Pc({activeView:s,onViewChange:a,onFiltersClick:r,activeCard:o,columns:d}){var Fe,Oe,Pe;const l=t.useEditorStore(le=>le.card),i=t.useEditorStore(le=>le.editorContext),c=t.useEditorStore(le=>le.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),u=t.useEditorStore(le=>le.actions.removeCardInlineFilterValue),m=t.useDashboardStore(le=>le.filterValues),x=t.useDashboardStore(le=>le.selectedSheetId),{updateCardConfig:g,setCard:p,updateCardInFrame:h,setShowAIDialog:v}=t.useEditorActions(),M=t.useEditorStore(le=>le.showAIDialog),N=t.useEditorStore(le=>le.isDevMode),b=t.useDashboardStore(le=>le.isVisualEditing),[w,F]=C.useState(!1),[S,y]=C.useState(!1),[k,E]=C.useState(!1),[A,T]=C.useState(null),{config:I}=C.useContext(n.SemaphorContext).tokenProps,L=(I==null?void 0:I.showInfoTab)!==!1,j=(I==null?void 0:I.showQueryDebugTools)!==!1,[P,V]=Ac();t.useEditorStore(le=>{var De;return!!((De=le.card.customCardPreferences)!=null&&De.url)});const O=t.getVisualizationMode(l)==="dynamic",D=(i==null?void 0:i.type)==="documentSection",R=n.useEffectiveEditorCardType(),{data:B,errorMessage:Y,isLoading:_,isFetching:z,errorSql:U,pagination:G,refetch:q,comparisonMetadata:Q,queryRequestPayload:H,resolvedPrimaryDateField:se}=n.useEditorCardQuery(o),ce=C.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),ge=C.useMemo(()=>!z&&ce.length>0?Object.keys(ce[0]):[],[z,ce]),[fe,Te]=C.useState(!1);C.useEffect(()=>{z||Te(!1)},[z]);const Ve=()=>{const le=!P;le&&s==="table"&&a("chart"),V(le)},Ue=(le,De)=>{const ve={...o,paginationConfig:{page:le+1,pageSize:De}};p(ve),h(ve)},Me=le=>{if(!l.config)return;const De=n.sortStateToSortByColumns(le,l.config.metricColumns,l.config.groupByColumns,l.config.detailColumns);g(l.id,{...l.config,sortByColumns:De})},Ee=C.useMemo(()=>{var le;return n.sortByColumnsToSortState((le=l.config)==null?void 0:le.sortByColumns)},[(Fe=l.config)==null?void 0:Fe.sortByColumns]);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":M&&b}),children:e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col",children:[e.jsxs("div",{className:"flex h-11 items-center gap-3 border-b border-border px-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s==="chart"&&M&&!D&&!O&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Bo,{variant:N?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(Tc,{activeView:s,onViewChange:a,splitViewEnabled:P,hasQueryError:!!Y}),!n.isTableType(R)&&e.jsx(Ic,{})]}),R==="kpi"&&e.jsx(Rc,{visible:!0,className:"self-center"}),Q&&l.type!=="table"&&e.jsx(n.ComparisonMetadataBadge,{metadata:Q,variant:"compact"}),M&&e.jsx(Nt.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(n.FilterInfo,{cardId:o.id,cardFilters:(Oe=o.config)==null?void 0:Oe.filters,cardFilterCount:n.getFilterCount(((Pe=o.config)==null?void 0:Pe.filters)||null),onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:c,sheetId:x||"",removeInlineFilterValue:le=>u(o.id,le),resolvedPrimaryDateField:se}),s==="chart"&&e.jsx(Fc,{card:o,effectiveCardType:R,queryResultColumns:ge}),s==="chart"&&!O&&e.jsx(Ea,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),e.jsx(n.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:_||z,onClick:()=>{Te(!0),q()},children:e.jsx(Ds,{className:t.cn("h-3.5 w-3.5",{"animate-spin":fe})})}),s==="chart"&&e.jsxs(n.DropdownMenu,{modal:!1,children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsx(n.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(n.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(n.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(n.DropdownMenuLabel,{children:"More Options"}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:Ve,children:[P?e.jsx(vr,{className:"mr-2 h-4 w-4"}):e.jsx(Lr,{className:"mr-2 h-4 w-4"}),P?"Hide Results Table":"Show Results Table"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs("div",{className:"px-1 py-1",children:[e.jsx(Os,{triggerVariant:"menu",className:"w-full"}),e.jsx(Bs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"})]}),e.jsx(Da,{onCustomize:()=>E(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"?Y?e.jsx(Lc,{showInfoTab:L}):e.jsx("div",{className:"flex grow flex-col",children:e.jsx(Dc,{card:o,queryData:B,isLoading:_,isFetching:z,pagination:G,onPaginationChange:Ue,onSortChange:Me,sortState:Ee,splitViewEnabled:P,isDynamicInspectorOpen:k,onDynamicInspectorOpenChange:E})}):null,s==="table"&&(B==null?void 0:B.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 px-4 py-4",children:[(_||z)&&(B==null?void 0:B.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(n.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(n.TableVisual,{card:o,data:ce,resultColumns:B.columns,columnKeyMap:B.columnKeyMap,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:Q,paginationMetadata:G,onPaginationChange:Ue,isLoading:_||z,onSortChange:Me,sortState:Ee})]}),s==="info"&&L&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-2",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-1",children:Y?e.jsx(So,{error:Y,errorSql:U,showCardDetails:!0,defaultSqlExpanded:!0,debugPayloads:j?{queryRequest:H,queryResponse:B,columns:d,dashboardFilters:m}:void 0,onSendFeedback:()=>{const le=n.prepareFeedbackData(n.FeedbackCategory.QUERY_GENERATION,{cardConfig:l.config,dataSource:o.dataSource,dashboardFilters:m,errorMessage:Y,errorSql:U,generatedSql:B==null?void 0:B.sql});T(le),y(!0)},onOpenInEditor:()=>{v(!0),setTimeout(()=>{const le=t.useEditorStore.getState().actions;le.setIsDevMode(!0),le.setCardSql(U||""),setTimeout(()=>{le.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(ka,{sql:B.sql,showCardDetails:!0,debugPayloads:j?{queryRequest:H,queryResponse:B,columns:d,dashboardFilters:m}:void 0})})})]}),A&&e.jsx(n.FeedbackDialog,{open:S,onOpenChange:y,feedbackData:A})]})})}function Oc({activeField:s}){const[a,r]=C.useState(!0);if(C.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=!!n.getFieldExpressionAnnotation(s);return e.jsxs("div",{className:`flex h-7 max-w-[300px] items-center gap-2 rounded-[5px] border border-border bg-popover px-3 text-[13px] text-foreground/90 shadow-[0_4px_12px_rgba(0,0,0,0.08)] transition-all duration-150 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(n.TypeGlyph,{dataType:s.dataType,calculated:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const Bc=()=>{const s=console.error;console.error=(...o)=>{o.length>0&&typeof o[0]=="string"&&o[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,o)};const a=o=>{if(o.message&&(o.message.includes("ResizeObserver loop completed with undelivered notifications")||o.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),o.stopPropagation(),!1},r=o=>{var d;if((d=o.reason)!=null&&d.message&&(o.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||o.reason.message.includes("ResizeObserver loop limit exceeded")))return o.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",r,!0)}};function Vc({column:s,isSelected:a,onSelect:r,availableFields:o,width:d,onWidthChange:l}){var B,Y,_;const i=t.useEditorStore(z=>z.card),{updateCardConfig:c,removeGroupByColumn:u,removeMetricColumn:m,updateFilters:x}=t.useEditorActions(),[g,p]=C.useState(!1),[h,v]=C.useState(!1),M=C.useRef(null),N=C.useCallback(z=>{z.preventDefault(),z.stopPropagation(),v(!0),M.current={startX:z.clientX,startWidth:d||150};const U=q=>{if(!M.current)return;const Q=q.clientX-M.current.startX,H=Math.max(80,M.current.startWidth+Q);l==null||l(s.id,H)},G=()=>{v(!1),M.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",G)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",G)},[d,s.id,l]),b=(B=i==null?void 0:i.config)==null?void 0:B.filters,w=(Y=b==null?void 0:b.conditions)==null?void 0:Y.some(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName),F=z=>{z?x(i.id,z):c(i.id,{filters:void 0})},{attributes:S,listeners:y,setNodeRef:k,transform:E,transition:A,isDragging:T}=n.useSortable({id:s.id}),I={transform:n.CSS.Transform.toString(E),transition:A},L=t.getDataType(s.dataType),j=_c(L),P=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.sortByColumns)||[],U=z.findIndex(q=>q.name===s.name);if(U!==-1){const q=[...z];q[U]={...q[U],direction:"asc"},c(i.id,{sortByColumns:q})}else c(i.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},V=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.sortByColumns)||[],U=z.findIndex(q=>q.name===s.name);if(U!==-1){const q=[...z];q[U]={...q[U],direction:"desc"},c(i.id,{sortByColumns:q})}else c(i.id,{sortByColumns:[...z,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},f=()=>{var G;const z=((G=i==null?void 0:i.config)==null?void 0:G.groupByColumns)||[];if(!z.some(q=>q.name===s.name)){const q={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...z,q]})}},O=z=>{var q;const U=((q=i==null?void 0:i.config)==null?void 0:q.metricColumns)||[];if(!U.some(Q=>Q.name===s.name&&Q.aggregate===z)){const Q={...s,id:`metric-${s.id}-${z}-${Date.now()}`,label:`${z} of ${s.label||s.name}`,role:"metric",aggregate:z};c(i.id,{metricColumns:[...U,Q]})}},D=()=>{s.role==="groupby"?u(i.id,s.id):s.role==="metric"&&m(i.id,s.id)},R={...I,width:d?`${d}px`:void 0,minWidth:d?`${d}px`:"120px"};return e.jsxs("th",{ref:k,style:R,className:t.cn("group relative border-r border-border bg-background px-1 py-0",T&&"opacity-50",a&&"bg-primary/10",h&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...S,...y,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(n.GripVertical,{className:"h-3 w-3"})}),e.jsxs(n.DropdownMenu,{children:[e.jsx(n.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:r,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(j,{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,")"]}),w&&e.jsx(n.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(oe.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(n.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(n.DropdownMenuItem,{onClick:()=>p(!0),children:[e.jsx(n.Filter,{className:t.cn("mr-2 h-4 w-4",w&&"text-primary")}),w?"Edit Filter":"Filter"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:P,children:[e.jsx(fr,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(n.DropdownMenuItem,{onClick:V,children:[e.jsx(pr,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuSub,{children:[e.jsxs(n.DropdownMenuSubTrigger,{children:[e.jsx(n.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(n.DropdownMenuSubContent,{children:[e.jsx(n.DropdownMenuItem,{onClick:()=>O("SUM"),children:"Sum"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("AVG"),children:"Average"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("COUNT"),children:"Count"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("DISTINCT"),children:"Count Distinct"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("MIN"),children:"Min"}),e.jsx(n.DropdownMenuItem,{onClick:()=>O("MAX"),children:"Max"})]})]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{onClick:f,children:[e.jsx(n.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(n.DropdownMenuSeparator,{}),e.jsxs(n.DropdownMenuItem,{disabled:!0,children:[e.jsx(n.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(n.DropdownMenuItem,{onClick:D,className:"text-destructive focus:text-destructive",children:[e.jsx(n.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:N,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",h&&"bg-primary")}),e.jsx(Va,{open:g,onOpenChange:p,availableFields:o.length>0?o:[s],existingFilters:b,editingCondition:w?(_=b==null?void 0:b.conditions)==null?void 0:_.find(z=>z.field.name===s.name&&z.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:F})]})}function _c(s){switch(s){case"number":return n.Hash;case"date":return n.Calendar;case"string":default:return t.Type}}function Yc({selectedColumn:s,onColumnSelect:a,isLoading:r=!1,sourceFields:o=[],filterableFields:d=o}){var T,I,L,j;const l=t.useEditorStore(P=>P.card),{updateCardConfig:i}=t.useEditorActions(),[c,u]=C.useState(null),[m,x]=C.useState({}),[g,p]=C.useState(!1),h=C.useMemo(()=>{var f,O;const P=((f=l==null?void 0:l.config)==null?void 0:f.groupByColumns)||[],V=((O=l==null?void 0:l.config)==null?void 0:O.metricColumns)||[];return[...P,...V]},[(T=l==null?void 0:l.config)==null?void 0:T.groupByColumns,(I=l==null?void 0:l.config)==null?void 0:I.metricColumns]),v=C.useMemo(()=>{const P=new Set(h.map(V=>`${V.qualifiedEntityName}.${V.name}`));return o.filter(V=>!P.has(`${V.qualifiedEntityName}.${V.name}`))},[o,h]),{data:M,isLoading:N}=n.useEditorCardQuery(l),b=(M==null?void 0:M.records)||[],w=C.useCallback((P,V)=>{x(f=>({...f,[P]:V}))},[]),F=C.useCallback(P=>{var D,R;const V=t.getDataType(P.dataType),f=((D=l==null?void 0:l.config)==null?void 0:D.groupByColumns)||[],O=((R=l==null?void 0:l.config)==null?void 0:R.metricColumns)||[];if(V==="number"){const B={...P,id:`metric-${P.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};i(l.id,{metricColumns:[...O,B]})}else{const B={...P,id:`groupby-${P.id}-${Date.now()}`,role:"groupby"};i(l.id,{groupByColumns:[...f,B]})}p(!1)},[(L=l==null?void 0:l.config)==null?void 0:L.groupByColumns,(j=l==null?void 0:l.config)==null?void 0:j.metricColumns,l.id,i]),S=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),y=P=>{u(P.active.id)},k=P=>{const{active:V,over:f}=P;if(u(null),!f||V.id===f.id)return;const O=h.findIndex(R=>R.id===V.id),D=h.findIndex(R=>R.id===f.id);if(O!==-1&&D!==-1){const R=n.arrayMove(h,O,D),B=R.filter(_=>_.role==="groupby"),Y=R.filter(_=>_.role==="metric");i(l.id,{groupByColumns:B,metricColumns:Y})}},E=c?h.find(P=>P.id===c):null,A=P=>{let V="";for(;P>=0;)V=String.fromCharCode(P%26+65)+V,P=Math.floor(P/26)-1;return V};return r?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"})}):h.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(n.DndContext,{sensors:S,collisionDetection:n.closestCenter,onDragStart:y,onDragEnd:k,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(n.SortableContext,{items:h.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:h.map((P,V)=>e.jsx("th",{style:{width:m[P.id]?`${m[P.id]}px`:void 0,minWidth:m[P.id]?`${m[P.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:A(V)},`letter-${P.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(n.SortableContext,{items:h.map(P=>P.id),strategy:n.horizontalListSortingStrategy,children:h.map(P=>e.jsx(Vc,{column:P,isSelected:(s==null?void 0:s.id)===P.id,onSelect:()=>a(P),availableFields:d,width:m[P.id],onWidthChange:w},P.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:g,onOpenChange:p,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(n.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns available."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:v.map(P=>{const V=t.getDataType(P.dataType),f=V==="number"?n.Hash:V==="date"?n.Calendar:t.Type;return e.jsxs(n.CommandItem,{value:P.label||P.name,onSelect:()=>F(P),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:P.label||P.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:P.entityName})]})]},P.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:N?e.jsx("tr",{children:e.jsx("td",{colSpan:h.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:h.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):b.slice(0,100).map((P,V)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",V%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:V+1}),h.map(f=>{const O=P[f.name]??P[f.label??""];return e.jsx("td",{style:{width:m[f.id]?`${m[f.id]}px`:void 0,minWidth:m[f.id]?`${m[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:zc(O,f)})},`${V}-${f.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},V))})]}),e.jsx(n.DragOverlay,{children:E&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:E.label||E.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(b.length,100)," of ",b.length," rows"]}),e.jsxs("span",{children:[h.length," columns"]})]})]})}function zc(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 r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function qc({entityGroups:s,isLoading:a=!1}){var F,S;const r=t.useEditorStore(y=>y.card),{updateCardConfig:o,removeGroupByColumn:d,removeMetricColumn:l}=t.useEditorActions(),[i,c]=C.useState(!0),[u,m]=C.useState(""),[x,g]=C.useState(new Set),p=((F=r==null?void 0:r.config)==null?void 0:F.groupByColumns)||[],h=((S=r==null?void 0:r.config)==null?void 0:S.metricColumns)||[],v=y=>{const k=new Set(x);k.has(y)?k.delete(y):k.add(y),g(k)},M=y=>p.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName)||h.some(k=>k.name===y.name&&k.qualifiedEntityName===y.qualifiedEntityName),N=(y,k)=>{if(k)if(t.getDataType(y.dataType)==="number"){const A={...y,id:`metric-${y.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};o(r.id,{metricColumns:[...h,A]})}else{const A={...y,id:`groupby-${y.id}-${Date.now()}`,role:"groupby"};o(r.id,{groupByColumns:[...p,A]})}else{const E=p.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName),A=h.findIndex(T=>T.name===y.name&&T.qualifiedEntityName===y.qualifiedEntityName);E!==-1&&d(r.id,p[E].id),A!==-1&&l(r.id,h[A].id)}},b=y=>{if(!u)return y;const k=u.toLowerCase();return y.filter(E=>E.name.toLowerCase().includes(k)||E.label&&E.label.toLowerCase().includes(k))},w=y=>{switch(t.getDataType(y)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return i?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>c(!1),title:"Close panel",children:e.jsx(Er,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ye.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:u,onChange:y=>m(y.target.value),className:"h-8 pl-8 text-sm"})]})}),(p.length>0||h.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[p.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(Ye.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.Rows3,{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:p.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(y=>{const k=w(y.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>d(r.id,y.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]},y.id)})})})]}),h.length>0&&e.jsxs(n.Collapsible,{defaultOpen:!0,children:[e.jsxs(n.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(Ye.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(n.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:h.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(y=>{const k=w(y.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(n.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:y.label||y.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.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:()=>l(r.id,y.id),children:e.jsx(oe.X,{className:"h-3 w-3"})})]},y.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(y=>{const k=b(y.columns);if(k.length===0)return null;const E=x.has(y.entityId)||u.length>0;return e.jsxs(n.Collapsible,{open:E,onOpenChange:()=>v(y.entityId),children:[e.jsxs(n.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(Ye.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",E&&"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:y.label||y.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.length})]}),e.jsx(n.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:k.map(A=>{const T=w(A.dataType),I=M(A);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",I&&"bg-primary/5"),children:[e.jsx(n.Checkbox,{checked:I,onCheckedChange:L=>N(A,L),className:"h-3.5 w-3.5"}),e.jsx(T,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:A.label||A.name})]},A.id)})})})]},y.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(!0),title:"Open panel",children:e.jsx(Ir,{className:"h-4 w-4"})})})}const $c=[{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 Kc({value:s,onChange:a,onSubmit:r,onCancel:o,selectedColumn:d,availableColumns:l}){const[i,c]=C.useState(!1),[u,m]=C.useState("column"),x=C.useRef(null);C.useEffect(()=>{const v=M=>{M.key==="Escape"&&s?o():M.key==="Enter"&&s&&!i&&r(s)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[s,o,r,i]);const g=v=>{const M=`[${v.label||v.name}]`,N=x.current;if(N){const b=N.selectionStart||0,w=N.selectionEnd||0,F=s.slice(0,b)+M+s.slice(w);a(F),setTimeout(()=>{N.setSelectionRange(b+M.length,b+M.length),N.focus()},0)}else a(s+M);c(!1)},p=v=>{const M=x.current;if(M){const N=M.selectionStart||0,b=M.selectionEnd||0,w=s.slice(0,N)+v.syntax+s.slice(b);a(w),setTimeout(()=>{M.setSelectionRange(N+v.name.length+1,N+v.syntax.length-1),M.focus()},0)}else a(s+v.syntax);c(!1)},h=v=>{switch(t.getDataType(v)){case"number":return n.Hash;case"date":return n.Calendar;default:return t.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:d?e.jsx("span",{className:"truncate",children:d.label||d.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:i&&u==="function",onOpenChange:v=>{c(v),v&&m("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(Ar,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search functions..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No functions found."}),e.jsx(n.CommandGroup,{heading:"Functions",children:$c.map(v=>e.jsx(n.CommandItem,{value:v.name,onSelect:()=>p(v),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:v.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:v.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:v.syntax})]})},v.name))})]})]})})]}),e.jsxs(t.Popover,{open:i&&u==="column",onOpenChange:v=>{c(v),v&&m("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(oe.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(n.Command,{children:[e.jsx(n.CommandInput,{placeholder:"Search columns..."}),e.jsxs(n.CommandList,{children:[e.jsx(n.CommandEmpty,{children:"No columns found."}),e.jsx(n.CommandGroup,{heading:"Available Columns",children:l.map(v=>{const M=h(v.dataType);return e.jsxs(n.CommandItem,{value:v.label||v.name,onSelect:()=>g(v),children:[e.jsx(M,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:v.label||v.name})]},v.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:x,value:s,onChange:v=>a(v.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:o,title:"Cancel (Esc)",children:e.jsx(oe.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:()=>r(s),title:"Apply (Enter)",children:e.jsx(t.Check,{className:"h-4 w-4"})})]})]})}function Uc({className:s}){var h,v,M,N;const a=t.useEditorStore(b=>b.card),[r,o]=C.useState(null),[d,l]=C.useState(""),{columns:i=[],columnGroups:c=[],isLoading:u}=n.useColumns(),{valuePickFilterableFields:m=[]}=n.useFilterableFields();(h=a==null?void 0:a.config)!=null&&h.groupByColumns,(v=a==null?void 0:a.config)!=null&&v.metricColumns,(M=a==null?void 0:a.config)!=null&&M.groupByColumns,(N=a==null?void 0:a.config)!=null&&N.pivotByColumns;const x=b=>{o(b),l(b?`[${b.label||b.name}]`:"")},g=b=>{console.log("Formula submitted:",b),l(""),o(null)},p=()=>{l(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Kc,{value:d,onChange:l,onSubmit:g,onCancel:p,selectedColumn:r,availableColumns:i}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Yc,{selectedColumn:r,onColumnSelect:x,isLoading:u,sourceFields:i,filterableFields:m})}),e.jsx(qc,{entityGroups:c,isLoading:u})]})]})}function Hc(){var B,Y;const[s,a]=C.useState("chart"),[r,o]=C.useState(!1),[d,l]=C.useState(!0),[i,c]=C.useState(!0),u=t.useEditorStore(_=>_.showAIDialog),m=t.useDashboardStore(_=>_.isVisualEditing),{setCardType:x}=t.useEditorActions(),g=t.useEditorStore(_=>_.card.type);C.useEffect(()=>Bc(),[]);const p=_=>{x(_)},h=t.useEditorStore(_=>_.frame),v=t.useEditorStore(_=>_.card);t.useEditorStore(_=>_.activeTabCardId),t.useEditorStore(_=>_.actions.getAvailableFields);const{addCard:M,removeCard:N,updateCard:b,setActiveCard:w,updateFilters:F}=t.useEditorActions(),{columnFields:S=[],scopedFields:y=[],filterableFields:k=[]}=n.useFilterableFields(),E=n.useSensors(n.useSensor(n.PointerSensor,{activationConstraint:{distance:8}})),A=v,{getFieldsForContainer:T,setFieldsForContainer:I}=n.useFieldManagement(A),{activeField:L,handleDragStart:j,handleDragEnd:P}=wc({activeCardId:h.activeCardId,sourceFields:y,getFieldsForContainer:T,setFieldsForContainer:I}),V=(_,z)=>{z&&F(_,z)},f=_=>{var z;b(_,{config:{...(z=h.cards.find(U=>U.id===_))==null?void 0:z.config,filters:void 0}})},O=k,D=_=>{if(!_)return 0;let z=_.conditions.length;return _.groups.forEach(U=>{z+=D(U)}),z},R=D(((B=A==null?void 0:A.config)==null?void 0:B.filters)||null);return e.jsxs(n.DndContext,{sensors:E,collisionDetection:n.closestCenter,onDragStart:j,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(ma,{isVisible:d,onToggleVisibility:()=>l(!d)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:g==="tableBuilder"?e.jsx(Uc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!u&&e.jsx(lc,{selectedChart:g,onChartChange:p,groupByFields:T("groupBy"),pivotByFields:T("pivotBy"),metricsFields:T("metrics"),sortByFields:T("sortBy"),detailFields:T("detailColumns"),activeField:L,isVisible:i,onToggleVisibility:()=>c(!i)}),e.jsx(Pc,{selectedChart:g,activeView:s,onViewChange:a,onFiltersClick:()=>o(!0),filterCount:R,activeCard:A,columns:S,getFieldsForContainer:T,cards:h.cards,activeCardId:h.activeCardId,addCard:M,setActiveCard:w})]})}),!d&&m&&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:()=>l(!0),title:"Show Data Source Panel",children:e.jsx(n.Database,{className:"h-4 w-4"})})})]}),A&&e.jsx(Sc,{cardId:A.id,filters:((Y=A.config)==null?void 0:Y.filters)||null,onFiltersChange:V,onClearFilters:f,availableFields:O,isOpen:r,onOpenChange:o}),e.jsx(n.DragOverlay,{dropAnimation:null,children:e.jsx(Oc,{activeField:L||null})})]})}function Gc({authToken:s,onSave:a,onClose:r}){const o=C.useRef(null),d=t.useEditorStore(E=>E.showAIDialog),l=t.useEditorStore(E=>E.isDevMode),i=n.useAssistantLayoutStore(E=>E.setFullscreen),c=n.useAssistantLayoutStore(E=>E.setPanelOpen),u=n.useAssistantLayoutStore(E=>E.setContainer),m=n.useAssistantPanel("editor"),x=n.useFullscreenAssistant(),g=n.useAssistantContainer("editor"),p=x==="editor",h=n.useDashboardAppearance(),v=C.useCallback(E=>{u("editor",E)},[u]),{setAuthToken:M}=t.useDashboardActions(),{setShowAIDialog:N,setOnSave:b,setOnClose:w}=t.useEditorActions(),{setActiveAssistantType:F}=t.useAIActions();C.useEffect(()=>{a&&b(a),r&&w(r)},[a,b,r,w]),C.useEffect(()=>{s&&s.accessToken&&M(s)},[s,M]),C.useEffect(()=>{var E,A;d?((E=o.current)==null||E.resize(40),c("editor",!0),F("editor")):((A=o.current)==null||A.resize(0),c("editor",!1),x==="editor"&&i(null),F(null))},[d,c,F,i,x]);function S(E){var A;E<1?(N(!1),c("editor",!1),x==="editor"&&i(null),F(null),(A=o.current)==null||A.resize(0)):(d||(N(!0),F("editor")),m.isOpen||c("editor",!0))}function y(){return e.jsxs(e.Fragment,{children:[e.jsx(ma,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ri,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:S,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(na,{isFullscreen:p,onFullscreenChange:E=>i(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:v,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})]})}function k(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(n.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",p&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(n.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hc,{})}),e.jsx(n.ResizableHandle,{disabled:!d}),e.jsx(n.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:S,defaultSize:m.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(na,{isFullscreen:p,onFullscreenChange:E=>i(E?"editor":null),fullscreenContainer:g})})})]}),e.jsx("div",{ref:v,className:t.cn("absolute inset-0",!p&&"pointer-events-none")})]})}return e.jsx(n.ErrorBoundary,{FallbackComponent:n.Fallback,children:l?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:h.dashboardContainerStyle,children:y()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:h.dashboardContainerStyle,children:k()})})}function Qc(){t.useDashboardStore(h=>h.selectedCardId);const s=t.useDashboardStore(h=>h.selectedSheetId),a=t.useDashboardStore(h=>h.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(h=>h.actions),d=t.useEditorStore(h=>h.editorContext),{clearEditorContext:l}=t.useEditorStore(h=>h.actions),i=n.useDashboardAppearance(),c=t.useDashboardStore(h=>h.isVisualEditing),u=t.useDashboardStore(h=>h.actions.updateFrame),m=t.useDashboardStore(h=>h.actions.updateDocumentSectionCard),x=n.useResolveExistingFrameSemanticExecutionPayload();async function g(h){var w,F,S;if((d==null?void 0:d.type)==="documentSection"){const y=n.getDocumentSectionEditorCard(h,d.cardId);if(!y){n.ue.error("No document section card found");return}if(!n.isSupportedDocumentTableCardType(y)){n.ue.error("Document table sections support Table and Pivot Table");return}m(d.sheetId,d.sectionId,y,{calculatedFields:h.calculatedFields}),l(),r(!1);return}const v=s?(w=a==null?void 0:a.sheets)==null?void 0:w.some(y=>{var k;return y.id===s&&((k=y.frames)==null?void 0:k.some(E=>E.id===h.id))}):!1,M=(S=(F=a==null?void 0:a.sheets)==null?void 0:F.find(y=>{var k;return(k=y.frames)==null?void 0:k.some(E=>E.id===h.id)}))==null?void 0:S.id,N=v?s:M||null;if(!N)return;const b=t.findDashboardFrameById(a,h.id);try{const y=await x(h,{previousFrame:b});u(N,h,{semanticExecutionPayload:y}),s!==N&&o(N),r(!1)}catch(y){console.error("Failed to resolve semantic metadata on save:",y),n.ue.error(y instanceof Error?y.message:"Failed to resolve semantic metadata for this visual")}}function p(){l(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!c}),style:i.dashboardContainerStyle,children:e.jsx(Gc,{onSave:g,onClose:p})})}exports.default=Qc;
|