react-semaphor 0.1.513 → 0.1.515

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/brand-studio/index.cjs +1 -1
  2. package/dist/brand-studio/index.js +1 -1
  3. package/dist/briefings/index.cjs +1 -1
  4. package/dist/briefings/index.js +3 -3
  5. package/dist/chunks/{dashboard-briefing-launcher-BgGxFDKD.cjs → dashboard-briefing-launcher-B7zqm8P1.cjs} +1 -1
  6. package/dist/chunks/{dashboard-briefing-launcher-C7ptb5Yf.js → dashboard-briefing-launcher-BA_bl05p.js} +5 -5
  7. package/dist/chunks/{dashboard-controls-BybAeRL8.js → dashboard-controls-QMW17RKx.js} +6 -6
  8. package/dist/chunks/{dashboard-controls-BFT7savs.cjs → dashboard-controls-x_v9wLOU.cjs} +1 -1
  9. package/dist/chunks/{dashboard-json-qNJC4fZW.cjs → dashboard-json-0ZLLBlHj.cjs} +1 -1
  10. package/dist/chunks/{dashboard-json-DmgEQ0yQ.js → dashboard-json-DRnpkNwO.js} +3 -3
  11. package/dist/chunks/{edit-dashboard-visual-CHqpQVfv.js → edit-dashboard-visual-1ISjhwry.js} +1377 -1380
  12. package/dist/chunks/{edit-dashboard-visual-BS219qr8.cjs → edit-dashboard-visual-CI0EqzKj.cjs} +2 -2
  13. package/dist/chunks/{editor-action-buttons-DbU_vUvm.js → editor-action-buttons-BTCKZERI.js} +3 -3
  14. package/dist/chunks/{editor-action-buttons-6NvSUz4D.cjs → editor-action-buttons-Czq5SnA9.cjs} +1 -1
  15. package/dist/chunks/{index-DhlVxvyI.cjs → index-BMMXKK3G.cjs} +1 -1
  16. package/dist/chunks/{index-CrxlydOT.cjs → index-C6_xef4P.cjs} +168 -168
  17. package/dist/chunks/{index-CACdoqu3.js → index-C8w91oj4.js} +61 -51
  18. package/dist/chunks/index-Cw2ypaFl.cjs +1 -0
  19. package/dist/chunks/{index-WMVZeOZp.js → index-Dlic9KZs.js} +32234 -31816
  20. package/dist/chunks/{index-CnGVjyF8.js → index-v1OE4-eA.js} +2 -2
  21. package/dist/chunks/matrix-formatter-BdIsE7Qu.js +341 -0
  22. package/dist/chunks/matrix-formatter-Dajj91Ni.cjs +1 -0
  23. package/dist/chunks/{pivot-header-presentation-Dm9dUQsl.js → pivot-header-presentation-BIf4HW3L.js} +35 -36
  24. package/dist/chunks/{pivot-header-presentation-Cxz8-06f.cjs → pivot-header-presentation-B_N11CgN.cjs} +3 -3
  25. package/dist/chunks/{pivot-result-lifecycle-BeOpjAhg.js → pivot-result-lifecycle-CEmyU2At.js} +207 -148
  26. package/dist/chunks/pivot-result-lifecycle-vg_suUNb.cjs +1 -0
  27. package/dist/chunks/{raw-temporal-DrmCX9Wq.js → raw-temporal-Bj6_w9cG.js} +471 -361
  28. package/dist/chunks/raw-temporal-CeblVJbu.cjs +1 -0
  29. package/dist/chunks/{report-preferences-dialog-CaefWf8W.cjs → report-preferences-dialog-Dr1BYwuf.cjs} +1 -1
  30. package/dist/chunks/{report-preferences-dialog-BoDcPtha.js → report-preferences-dialog-b8J6KjSy.js} +2 -2
  31. package/dist/chunks/semantic-format-DFI1iszk.cjs +1 -0
  32. package/dist/chunks/{semantic-format-BZxJLKvw.js → semantic-format-Dt-nUxFB.js} +23 -29
  33. package/dist/chunks/switch-Ced9ZZwI.cjs +134 -0
  34. package/dist/chunks/{switch-QfKb0Iwe.js → switch-D5_tjsIS.js} +3139 -3087
  35. package/dist/dashboard/index.cjs +1 -1
  36. package/dist/dashboard/index.js +1 -1
  37. package/dist/data-app-builder/index.cjs +1 -1
  38. package/dist/data-app-builder/index.js +2 -2
  39. package/dist/data-app-sdk/index.cjs +1 -1
  40. package/dist/data-app-sdk/index.js +1 -1
  41. package/dist/format-utils/index.cjs +3 -3
  42. package/dist/format-utils/index.js +131 -126
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.js +7 -7
  45. package/dist/surfboard/index.cjs +1 -1
  46. package/dist/surfboard/index.js +2 -2
  47. package/dist/types/components/calculated-fields/templates-menu.d.ts +0 -9
  48. package/dist/types/components/visual/aggregated-table/utils/metric-format-resolver.d.ts +3 -3
  49. package/dist/types/components/visual/data-table/types/data-table.d.ts +4 -1
  50. package/dist/types/components/visual/pivot-table/utils/pivot-metric-formatting.d.ts +2 -2
  51. package/dist/types/index.cjs +1 -1
  52. package/dist/types/index.js +58 -34
  53. package/dist/types/lib/formatters/metric-formatting.d.ts +3 -3
  54. package/dist/types/lib/table-formatting/table-presentation-fields.d.ts +1 -0
  55. package/dist/types/lib/types/calculated-field-template-types.d.ts +3 -2
  56. package/dist/types/lib/utils/calculated-field-row-templates.d.ts +6 -4
  57. package/dist/types/lib/utils/date-timezone-utils.d.ts +26 -4
  58. package/dist/types/shared/format-utils/formatters/duration-formatter.d.ts +4 -1
  59. package/dist/types/shared/format-utils/formatters/index.d.ts +2 -2
  60. package/dist/types/shared/format-utils/formatters/number-formatter.d.ts +8 -2
  61. package/dist/types/shared/format-utils/presentation-execution.d.ts +17 -2
  62. package/dist/types/shared/format-utils/types/format-types.d.ts +16 -1
  63. package/package.json +1 -1
  64. package/dist/chunks/index-F25jnH0p.cjs +0 -1
  65. package/dist/chunks/matrix-formatter-BLunke3R.js +0 -424
  66. package/dist/chunks/matrix-formatter-CveLJo6S.cjs +0 -1
  67. package/dist/chunks/pivot-result-lifecycle-BiERyXnS.cjs +0 -1
  68. package/dist/chunks/raw-temporal-BUeTpG76.cjs +0 -1
  69. package/dist/chunks/semantic-format-BzH69TRq.cjs +0 -1
  70. package/dist/chunks/switch--Re1K566.cjs +0 -134
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),v=require("react"),a=require("./index-CrxlydOT.cjs"),le=require("./x-B6ghREd2.cjs"),t=require("./switch--Re1K566.cjs"),je=require("./card-config-utils-CMO4_zVs.cjs"),at=require("./validators-DVYAnnX0.cjs");require("./matrix-operation-contract-DoiWTUbT.cjs");const Kt=require("../value-format-preferences/index.cjs"),et=require("./field-aggregations-jSi77h9Z.cjs"),$e=require("./selection-reducer-CGKKsaPa.cjs"),jt=require("./editor-action-buttons-6NvSUz4D.cjs"),Dt=require("./calculated-field-identity-BiTGmnST.cjs");require("zod");const xe=require("./index-DhlVxvyI.cjs"),dr=require("react-dom");require("./appearance-runtime-provider-D5pkvgE4.cjs");const ur=require("./appearance-context-DzqCdhB4.cjs");require("./index-Cx3qmRUB.cjs");require("./matrix-continuation-6nhDy-lF.cjs");require("./color-CyB5o13F.cjs");const mr=require("./matrix-control-sources-FjxGIbqk.cjs"),bt=require("./matrix-definition-CBJW_4ii.cjs"),ea=require("./raw-temporal-BUeTpG76.cjs"),Tn=require("./metric-comparison-DBQ3EJTz.cjs"),ta=require("./matrix-formatter-CveLJo6S.cjs"),xr=require("./semantic-format-BzH69TRq.cjs"),hr=require("./palette-BN-jYtaK.cjs");function pr(s){const n=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(n,r,o.get?o:{enumerable:!0,get:()=>s[r]})}}return n.default=s,Object.freeze(n)}const ss=pr(v);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),v=require("react"),a=require("./index-C6_xef4P.cjs"),le=require("./x-B6ghREd2.cjs"),t=require("./switch-Ced9ZZwI.cjs"),je=require("./card-config-utils-CMO4_zVs.cjs"),at=require("./validators-DVYAnnX0.cjs");require("./matrix-operation-contract-DoiWTUbT.cjs");const Kt=require("../value-format-preferences/index.cjs"),et=require("./field-aggregations-jSi77h9Z.cjs"),$e=require("./selection-reducer-CGKKsaPa.cjs"),jt=require("./editor-action-buttons-Czq5SnA9.cjs"),Dt=require("./calculated-field-identity-BiTGmnST.cjs");require("zod");const xe=require("./index-BMMXKK3G.cjs"),dr=require("react-dom");require("./appearance-runtime-provider-D5pkvgE4.cjs");const ur=require("./appearance-context-DzqCdhB4.cjs");require("./index-Cx3qmRUB.cjs");require("./matrix-continuation-6nhDy-lF.cjs");require("./color-CyB5o13F.cjs");const mr=require("./matrix-control-sources-FjxGIbqk.cjs"),bt=require("./matrix-definition-CBJW_4ii.cjs"),ea=require("./raw-temporal-CeblVJbu.cjs"),Tn=require("./metric-comparison-DBQ3EJTz.cjs"),ta=require("./matrix-formatter-Dajj91Ni.cjs"),xr=require("./semantic-format-DFI1iszk.cjs"),hr=require("./palette-BN-jYtaK.cjs");function pr(s){const n=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(n,r,o.get?o:{enumerable:!0,get:()=>s[r]})}}return n.default=s,Object.freeze(n)}const ss=pr(v);/**
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
  ${n||r.sql||r.python}
170
170
 
171
171
  `;c(x)};return{isDevMode:o,handleOpenInEditor:!o&&je.supportsSqlEditor(r.type)?l:void 0,handleDebugWithAssistant:o?u:void 0}}function ha(s,n){const[r,o]=v.useState(!1),i=t.useEditorStore(m=>m.card),d=t.useDashboardStore(m=>m.dashboard.filters),{currentUser:c}=a.useCurrentUserInfo(),{tokenProps:l}=v.useContext(a.SemaphorContext),u=v.useCallback(()=>{o(!0)},[]),x=v.useMemo(()=>{const m=typeof window<"u"?window.location.href:"",b=typeof navigator<"u"?navigator.userAgent:"",h=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:a.FeedbackCategory.QUERY_GENERATION,user:c,tokenContext:l,systemState:{cardConfig:i.config,dataSource:i.dataSource,dashboardFilters:d,errorMessage:s||void 0,errorSql:n||i.sql||i.python,generatedSql:n||i.sql},metadata:{url:m,userAgent:b,timestamp:new Date().toISOString(),viewport:h}}},[c,l,i,d,s,n]);return{feedbackDialogOpen:r,setFeedbackDialogOpen:o,handleSendFeedback:u,feedbackPayload:x}}const wo="__editor_sql__",To="__editor_python__";function Eo(s){var r;const n=xe.normalizeDashboardCardPythonCode(s.python||"");return{sql:(r=s.sql)!=null&&r.trim()?wo:"",python:n.trim()?To:""}}function pa({className:s,style:n,...r}){var Z,Fe,me,qe,Le,Ke,Se;const o=t.useEditorStore(oe=>oe.card),i=a.useDashboardAppearance(),c=t.useEditorStore(oe=>oe.isDevMode)?!1:((Z=o.customCardPreferences)==null?void 0:Z.showCardHeader)??!0,l=((me=(Fe=o.preferences)==null?void 0:Fe.displayOptions)==null?void 0:me.showInlineFilterBar)??!0,u=t.useEditorStore(oe=>oe.frame),x=t.useEditorStore(oe=>oe.inlineFilterValuesMap[o.id]),m=t.useDashboardStore(oe=>oe.dashboard.filters),b=t.useDashboardStore(oe=>oe.selectedSheetId),h=t.useEditorStore(oe=>oe.actions.setRunSql),p=t.useEditorStore(oe=>oe.actions.setCardInlineFilterValue),j=t.useEditorStore(oe=>oe.actions.removeCardInlineFilterValue),{updateFilter:N}=t.useDashboardActions(),f=m==null?void 0:m.find(oe=>oe.id===u.filterId),g=v.useMemo(()=>xe.findCustomVisualConfigCard(u,o),[u,o]),{manifest:D}=a.useCustomVisual(((qe=g==null?void 0:g.customCardPreferences)==null?void 0:qe.url)||""),I=v.useMemo(()=>{var oe;return(oe=D==null?void 0:D.visuals)==null?void 0:oe.find(Ie=>{var Re;return Ie.name===((Re=g==null?void 0:g.customCardPreferences)==null?void 0:Re.componentName)})},[D,(Le=g==null?void 0:g.customCardPreferences)==null?void 0:Le.componentName]),w=xe.resolveMultiInputType(g,I),S=v.useMemo(()=>xe.getCustomVisualInputCards({frame:u,configCard:g,isMultiInputVisual:w==="multiple"}),[u,g,w]),M=v.useMemo(()=>{const oe=S.findIndex(Ie=>(Ie==null?void 0:Ie.id)===(o==null?void 0:o.id));return oe<0?-1:xe.getSlotIndexForCard(o,oe)},[S,o]),A=v.useMemo(()=>!g||w!=="multiple"||M<0?o.type:xe.getEffectiveCardTypeForSlot(o,M,I==null?void 0:I.slots)??o.type,[g,w,M,o,I==null?void 0:I.slots]),F=A??o.type,E=v.useMemo(()=>F===o.type?o:{...o,type:F},[o,F]),C=E.type==="table"||E.type==="matrixTable"||E.type==="pivotTable"||E.type==="aggregateTable"||E.type==="detailTable",T=v.useMemo(()=>A!==o.type?{...o,type:A}:o,[o,A]),{data:L,isLoading:k,isFetching:R,errorMessage:y,errorSql:_,pagination:O}=a.useEditorCardQuery(T),P=!!y,{handleOpenInEditor:B,handleDebugWithAssistant:Y}=As(y,_||o.sql||o.python),{feedbackDialogOpen:q,setFeedbackDialogOpen:z,handleSendFeedback:V,feedbackPayload:$}=ha(y,_||o.sql||o.python),Q=v.useMemo(()=>(L==null?void 0:L.records)||[],[L==null?void 0:L.records]),{setCard:U,updateCardInFrame:J}=t.useEditorActions(),{data:W}=a.useTopoJson(E),ee=E.id,ue=E.config,fe=E.interactionConfig,be=E.controls,ge=E.controlBindings,Pe=E.customCfg,Oe=E.preferences,ke=E.queryConfig,Te=Eo({sql:E.sql,python:E.python}),_e=Te.sql,ze=Te.python,Be=L==null?void 0:L.records,Ae=v.useMemo(()=>({id:ee,type:F,config:ue,interactionConfig:fe,preferences:Oe,controls:be,controlBindings:ge,sql:_e,python:ze}),[ee,F,ue,fe,Oe,be,ge,_e,ze]),Me=v.useMemo(()=>F==="pivotTable"?a.resolvePendingPivotTableResultState({data:L,card:E,isPending:k||R}):{kind:"not_loaded"},[E,F,L,R,k]),ae=a.usePivotTableConfig(E,Me,(Ke=L==null?void 0:L.metadata)==null?void 0:Ke.comparisonMetadata),K=(oe,Ie)=>{var De,te;const Re={...o,paginationConfig:{page:oe+1,pageSize:Ie}};U(Re),J(Re),o.sql&&((te=(De=o.preferences)==null?void 0:De.tablePrefs)!=null&&te.enableDevModePagination)&&h(!0)},ie=oe=>{var De,te,ve,ye,Qe;const Ie=a.sortStateToSortByColumns(oe,(De=o.config)==null?void 0:De.metricColumns,(te=o.config)==null?void 0:te.groupByColumns,(ve=o.config)==null?void 0:ve.detailColumns),Re={...o,config:{...o.config||{},sortByColumns:Ie}};U(Re),J(Re),o.sql&&((Qe=(ye=o.preferences)==null?void 0:ye.tablePrefs)!=null&&Qe.enableDevModePagination)&&h(!0)},Ce=a.useChartNumericPresentation(Ae,Be||void 0),re=v.useMemo(()=>{var oe;return!ee||!Be?null:a.createChartConfig({card:Ae,data:Be,cardType:F,queryConfig:ke,customCfg:Pe,preferences:Oe,topoJson:W,comparisonMetadata:(oe=L==null?void 0:L.metadata)==null?void 0:oe.comparisonMetadata,numericPresentation:Ce,resultColumns:L==null?void 0:L.columns,columnKeyMap:L==null?void 0:L.columnKeyMap})},[Ae,ee,Pe,Oe,ke,Be,L==null?void 0:L.columns,L==null?void 0:L.columnKeyMap,(Se=L==null?void 0:L.metadata)==null?void 0:Se.comparisonMetadata,F,Ce,W]);function he(oe){return e.jsx(a.ErrorBoundary,{FallbackComponent:a.FallbackVisual,children:e.jsx(a.EditorCustomVisual,{card:oe})})}function Ye(){var oe;if(E.type==="matrixTable")return e.jsx(a.MatrixCardView,{card:E,frame:u,mode:"editor"});if(L!=null&&L.records&&(L==null?void 0:L.records.length)===0&&!k&&!R&&F!=="pivotTable")return y?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(rs,{error:y,errorSql:_||o.sql||o.python,onOpenInEditor:B,onDebugWithAssistant:Y,onSendFeedback:V,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(a.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((k||R)&&(!(L!=null&&L.records)||L.records.length===0))return F==="table"||F==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(a.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!E.id)return null;if(F==="custom")return he(o);if(!["table","matrixTable","pivotTable","aggregateTable","detailTable","custom"].includes(F)&&re)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:k||R?e.jsx(e.Fragment,{}):e.jsx(a.ChartJsVisual,{cfg:re})});if(F==="table"||F==="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(a.TableVisual,{card:E,data:Q,resultColumns:L==null?void 0:L.columns,columnKeyMap:L==null?void 0:L.columnKeyMap,totalsByColumnId:L==null?void 0:L.tableTotalsByColumnId,comparisonMetadata:(oe=L==null?void 0:L.metadata)==null?void 0:oe.comparisonMetadata,paginationMetadata:O,onPaginationChange:K,onSortChange:ie,isLoading:k||R})});if(F==="pivotTable"&&ae)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(a.PivotTableTanstack,{card:E,data:ae.data,options:ae.options,onAggregationChange:Ie=>{const Re=a.handleAggregationChange(Ie,o.config),De={...o,config:Re};U(De),J(De)},onAggregationLabelChange:Ie=>{const Re=a.handleAggregationLabelChange(Ie,o.config),De={...o,config:Re};U(De),J(De)}})});if(F==="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(a.AggregateTable,{card:E,data:(L==null?void 0:L.records)||[],resultColumns:L==null?void 0:L.columns,columnKeyMap:L==null?void 0:L.columnKeyMap,groupByColumns:L==null?void 0:L.groupByColumns,pivotSchema:L==null?void 0:L.pivotSchema,paginationMetadata:O,onPaginationChange:K,onAggregationChange:Ie=>{const Re=a.handleAggregationChange(Ie,o.config),De={...o,config:Re};U(De),J(De)},isLoading:k||R})})}return e.jsxs(a.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none bg-card text-card-foreground",s),style:{...i.cardFrameStyle,...n},...r,children:[(k||R)&&!a.showsOwnRefetchCue({type:F})&&(L==null?void 0:L.records)&&L.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),c&&e.jsxs(a.CardHeader,{className:t.cn("flex flex-row items-start justify-between gap-4 px-4 pb-3 pt-3"),style:i.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(a.CardTitle,{className:"min-w-0 text-[17px] font-semibold leading-tight tracking-[-0.005em]",children:e.jsx(a.EditableText,{value:o.title,onSave:oe=>U({...o,title:oe}),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(a.InfoHover,{card:o}),e.jsx(jt.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(go,{})})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(a.EditableText,{value:(o.description||"").trim(),onSave:oe=>U({...o,description:oe.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-[12px] leading-snug text-muted-foreground",inputClassName:"text-[12px] leading-snug"})})]}),f&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Label,{className:"my-1",children:e.jsx(a.EditableText,{value:f.title||f.column,onSave:oe=>N({...f,title:oe}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(a.FilterComponent,{filter:f})]})]}),l&&o.inlineFilters&&o.inlineFilters.length>0&&e.jsx("div",{className:"px-4 pb-2",style:i.cardGutterStyle,children:e.jsx(a.InlineFilterBar,{card:o,sheetId:b||"",inlineFilterValues:x,setInlineFilterValue:oe=>p(o.id,oe),removeInlineFilterValue:oe=>j(o.id,oe)})}),e.jsxs(a.CardContent,{className:t.cn("flex min-h-0 grow flex-col",C?P?"px-4 pb-0 pt-2":"p-0 [&_.data-table-scroll-container]:border-0 [&_.data-table-scroll-container]:bg-transparent":P?"px-4 py-0":"px-4"),style:C&&!P?void 0:i.cardGutterStyle,children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:Ye()}),a.isCardSummaryVisibleOnCard(E)&&e.jsx("div",{className:t.cn("pt-3",C&&"px-4"),children:e.jsx(a.CardSummary,{card:E,mode:"editor",records:L==null?void 0:L.records})})]}),e.jsx(a.FeedbackDialog,{open:q,onOpenChange:z,feedbackData:$,showDebugInfo:!0})]})}function On(s){var n,r;return JSON.stringify({...s,data:{...s.data,datasets:(r=(n=s.data)==null?void 0:n.datasets)==null?void 0:r.map(o=>{const i={...o};return Object.keys(i).forEach(d=>{d.startsWith("semaphor")&&delete i[d]}),{...i,data:[]}})}},null,2)}const fs=({language:s,value:n,onChange:r,readonly:o})=>e.jsx(t.CodeEditor,{className:"h-full w-full text-xs",language:s,value:n,onValueChange:r,readOnly:o,embedded:!0}),Io=()=>e.jsxs(a.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(a.DialogTitle,{children:"Customize Card"})}),e.jsxs(a.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:n,mergedConfig:r,onConfigChange:o,onCodeChange:i})=>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(fs,{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(fs,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(fs,{language:"javascript",value:s,onChange:i})})]}),ko=({error:s,hasCardCustomConfig:n,onReset:r,onApply:o,onClose:i})=>e.jsxs(a.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!n,onClick:r,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:i,variant:"outline",children:"Close"})]});function Mo({triggerVariant:s="icon",className:n,label:r="Customize Visual"}={}){const[o,i]=v.useState(!1),[d,c]=v.useState(""),[l,u]=v.useState(""),[x,m]=v.useState(""),[b,h]=v.useState(""),p=t.useEditorStore(C=>C.card),j=a.useEffectiveEditorCardType(),N=t.useEditorStore(C=>C.card.customCfg),f=N?JSON.stringify(N,null,2):"",g=v.useMemo(()=>j!==p.type?{...p,type:j}:p,[p,j]),{data:D}=a.useEditorCardQuery(g),{data:I}=a.useTopoJson(p),w=a.useChartNumericPresentation(p,D==null?void 0:D.records),{setCardCustomCfg:S,setCustomVisualCode:M}=t.useEditorActions(),A=()=>{var T,L,k;if(!((T=D==null?void 0:D.records)!=null&&T.length))return;const C=a.createChartConfig({card:p,data:D.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:I,comparisonMetadata:(L=D==null?void 0:D.metadata)==null?void 0:L.comparisonMetadata,numericPresentation:w,resultColumns:D==null?void 0:D.columns,columnKeyMap:D==null?void 0:D.columnKeyMap});if(C){c(On(C)),m(((k=p.preferences)==null?void 0:k.customVisualCode)||"");const R=a.merge(C,N);u(On(R))}},F=()=>{try{if(x&&M(x),l){const C=JSON.parse(l),T=Dt.getObjectDiff(JSON.parse(d),C);S(T),h("")}}catch{h("Invalid JSON configuration")}},E=Object.keys(N||{}).length===0;return e.jsxs(a.Dialog,{open:o,onOpenChange:i,children:[e.jsx(a.DialogTrigger,{asChild:!0,children:s==="menu"?e.jsxs(t.Button,{variant:"ghost",onClick:A,className:t.cn("h-7 w-full justify-start gap-2 px-2 text-[13px] font-normal",E?"":"text-green-600 hover:text-green-700",n),children:[e.jsx(a.Settings,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:r})]}):e.jsx(a.IconButton,{tooltip:"Customize Visual",onClick:A,className:t.cn(E?"":"text-green-600 hover:text-green-700",n),children:e.jsx(a.Settings,{className:"h-4 w-4"})})}),e.jsxs(a.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(a.ErrorBoundary,{FallbackComponent:a.FallbackVisual,children:e.jsx(pa,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Do,{customCode:x,cardCustomCfgString:f,mergedConfig:l,onConfigChange:C=>u(C??""),onCodeChange:C=>m(C??"")})]}),e.jsx(ko,{error:b,hasCardCustomConfig:!!N,onReset:()=>{u(d),S(null)},onApply:F,onClose:()=>i(!1)})]})]})}function Ao(s){let n=0;for(let o=0;o<s.length;o++)n=s.charCodeAt(o)+((n<<5)-n);return`hsl(${Math.abs(n%360)}, 65%, 45%)`}function Lo(s){const n=s.trim().split(/\s+/);return n.length>1?(n[0][0]+n[1][0]).toUpperCase():s.slice(0,2).toUpperCase()}function Ls({chartType:s,chartName:n,isCustom:r=!1,className:o="h-6 w-6"}){if(!r&&s)return a.getChartIconByType(s,o);const i=a.getAutoDetectedChartIcon(n);if(i)return v.cloneElement(i,{className:o});const d=Lo(n),c=Ao(n);return e.jsx("div",{className:t.cn("flex items-center justify-center rounded text-white font-semibold text-xs",o),style:{backgroundColor:c},children:d})}function Fo({isStarred:s,onClick:n,className:r}){const o=i=>{i.stopPropagation(),i.preventDefault(),n(i)};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(a.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 Bn({chartType:s,chartName:n,isCustom:r=!1,pluginName:o,isStarred:i,showStar:d=!0,isSelected:c=!1,onSelect:l,onToggleStar:u}){return e.jsxs("div",{className:"group relative",children:[d&&e.jsx("div",{className:t.cn("absolute left-1 top-1 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-focus-within:opacity-100 group-hover:opacity-100"),children:e.jsx(Fo,{isStarred:i,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:l,"aria-pressed":c,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",c&&"border-foreground/50 bg-muted/50 hover:border-foreground/50"),children:[e.jsx(Ls,{chartType:s,chartName:n,isCustom:r,className:"h-4 w-4 text-foreground/80"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-[11px] text-foreground/80",children:n})]})]})}function fa(s,n){return s==="matrixTable"?!n.isDevMode:!0}function qt(s,n){return s==="matrixTable"?!1:fa(s,n)}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(n=>fa(n.id,s))}function ga({onChartSelect:s,onClose:n}){const[r,o]=v.useState(""),{starredCharts:i,isStarred:d,toggleStar:c}=a.useStarredChartsStore(),{data:l=[],isLoading:u}=a.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:m,setIsDevMode:b}=t.useEditorStore(T=>T.actions),h=t.useEditorStore(T=>T.card),p=t.useEditorStore(T=>T.isDevMode),{setCardCustomCfg:j,setCustomCardPreferences:N,setVisualizationMode:f,setQueryConfig:g,replaceFrameCards:D,clearModeDrafts:I,initializeModeDrafts:w}=t.useEditorActions(),S=v.useMemo(()=>{const T=Po({isDevMode:p});if(!r)return T;const L=r.toLowerCase();return T.filter(k=>k.name.toLowerCase().includes(L))},[p,r]),M=v.useMemo(()=>{const T=l.filter(k=>k.componentType==="chart"&&k.pluginType!=="standard");if(!r)return T;const L=r.toLowerCase();return T.filter(k=>k.name.toLowerCase().includes(L))},[l,r]),A=T=>{j(null),m({}),f("builtin"),x(T),["custom","text","map"].includes(T)&&(b(!0),g(void 0)),s==null||s(T),n==null||n()},F=T=>{j(null),m({}),f("builtin"),g(void 0);const L=xe.resolveMultiInputTypeFromVisual(T);if(L==="multiple"&&T.slots&&T.slots.length>0){I();const R=xe.createCardsFromSlots(T.slots,T,h);D(R),R[0]&&w(R[0]),n==null||n();return}else x("custom"),N({type:"component",visualType:L,url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType,minInputs:T.minInputs,maxInputs:T.maxInputs});s==null||s("custom",T),n==null||n()},E=T=>{const L={type:"default",id:T.id,name:T.name};c(L)},C=T=>{const L={type:"custom",id:T.name,url:T.url,icon:T.icon,name:T.name};c(L)};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($e.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",placeholder:"Search charts",value:r,onChange:T=>o(T.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:[S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:S.map(T=>e.jsx(Bn,{chartType:T.id,chartName:T.name,isCustom:!1,isStarred:d("default",T.id),onSelect:()=>A(T.id),onToggleStar:()=>E(T)},T.id))}),M.length>0&&e.jsxs(e.Fragment,{children:[S.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:M.length})]}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:M.map((T,L)=>e.jsx(Bn,{chartName:T.name,isCustom:!0,pluginName:T.pluginName,isStarred:d("custom",T.name),onSelect:()=>F(T),onToggleStar:()=>C(T)},`${T.url}-${T.name}-${L}`))})]}),u&&e.jsx("div",{className:"mt-3 py-4 text-center text-[11px] text-muted-foreground",children:"Loading custom charts…"}),S.length===0&&M.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:n}){var M,A,F,E;const r=t.useEditorStore(C=>C.card),o=t.useEditorStore(C=>C.frame),i=t.useEditorStore(C=>C.isDevMode),{replaceFrameCards:d,clearModeDrafts:c,initializeModeDrafts:l,setIsDevMode:u}=t.useEditorActions(),x=v.useMemo(()=>xe.findCustomVisualConfigCard(o,r),[o,r]),{manifest:m}=a.useCustomVisual(((M=x==null?void 0:x.customCardPreferences)==null?void 0:M.url)||""),b=v.useMemo(()=>{var C;return(C=m==null?void 0:m.visuals)==null?void 0:C.find(T=>{var L;return T.name===((L=x==null?void 0:x.customCardPreferences)==null?void 0:L.componentName)})},[m,(A=x==null?void 0:x.customCardPreferences)==null?void 0:A.componentName]),h=xe.resolveMultiInputType(x,b)==="multiple",p=a.useEffectiveEditorCardType(),j=h?p:s??r.type,N=(F=r==null?void 0:r.customCardPreferences)==null?void 0:F.componentName,f=(E=x==null?void 0:x.customCardPreferences)==null?void 0:E.componentName,g=h&&!!f,D=v.useMemo(()=>{const C=a.chartTypes.find(T=>T.id===j);return C?C.label:j==="custom"?N||"Custom Visual":"Select chart type"},[j,N]),I=v.useMemo(()=>{const C=a.chartTypes.find(T=>T.id===j);if(C){const T=C.icon;return e.jsx(T,{className:"h-4 w-4"})}if(j==="custom"&&N){const T=a.getAutoDetectedChartIcon(N);return T||e.jsx(Ls,{chartName:N,isCustom:!0,className:"h-4 w-4"})}return e.jsx(kr,{className:"h-4 w-4"})},[j,N]);return{displayChartType:j,displayLabel:D,displayIcon:I,showBadge:g,badgeLabel:f,isMultiInputContext:h,handleChartSelect:C=>{n==null||n(C)},handleClearCustomVisual:C=>{C.stopPropagation();const T={...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};d([T]),c(),l(T),i&&u(!0),n==null||n("bar")}}}function Bo({selectedChart:s,onChartChange:n,variant:r="ghost",className:o}){const[i,d]=v.useState(!1),{displayLabel:c,displayIcon:l,showBadge:u,badgeLabel:x,handleChartSelect:m,handleClearCustomVisual:b}=Oo({selectedChart:s,onChartChange:n}),h=r==="header";return e.jsxs("div",{className:t.cn("relative w-full",o),children:[e.jsxs(t.Popover,{open:i,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:h?e.jsxs("button",{type:"button",role:"combobox","aria-expanded":i,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:[l,e.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:c})]}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",i&&"rotate-180")})]}):e.jsxs(t.Button,{size:"xs",variant:r,role:"combobox","aria-expanded":i,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:[l,e.jsx("span",{className:"truncate",children:c})]}),e.jsx(le.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-70"})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:p=>p.preventDefault(),children:e.jsx(ga,{onChartSelect:p=>m(p),onClose:()=>d(!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:x,children:[e.jsx(a.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:b,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(le.X,{className:"h-2.5 w-2.5"})})]})]})}const Pt={table:t.Table2,matrixTable:a.Grid3x3,bar:a.ChartColumnIncreasing,line:a.ChartLine,stackedBar:a.ChartColumnStacked,stackedLine:a.MdStackedLineChart,scatter:a.ChartScatter,bubble:a.TbChartBubble,pie:a.ChartPie,doughnut:a.Donut,kpi:a.TiSortNumerically,treemap:a.TbChartTreemap,bullet:a.BulletChartIcon,funnel:a.TbChartFunnel,tornado:a.Tornado,heatmap:a.Grid3x3,range:a.ChartNoAxesGantt,radar:a.Radar,polarArea:a.PiChartPolar,text:a.BookType,map:a.Map},$t={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"},ba=[{id:"table"},{id:"bar"},{id:"line"},{id:"pie"},{id:"kpi"},{id:"doughnut"}],ja=6;function Vo({selectedChart:s,onChartChange:n}){var I,w;const[r,o]=v.useState(!1),i=t.useEditorStore(S=>S.card),{setCardType:d,setCardPreferences:c}=t.useEditorStore(S=>S.actions),{setCardCustomCfg:l,setCustomCardPreferences:u,setQueryConfig:x,replaceFrameCards:m,clearModeDrafts:b,initializeModeDrafts:h}=t.useEditorActions(),{starredCharts:p}=a.useStarredChartsStore(),{data:j=[]}=a.useCustomVisualsQuery(),N=t.useEditorStore(S=>S.isDevMode),f=v.useMemo(()=>{const S=p.filter(E=>E.type==="default"?qt(E.id,{isDevMode:N}):j.some(C=>C.name===E.id)),M=new Set(S.map(E=>E.id)),A=ba.filter(E=>!M.has(E.id)&&qt(E.id,{isDevMode:N}));return[...S.map(E=>({id:E.id,label:E.name,icon:E.type==="default"?Pt[E.id]:void 0,isCustom:E.type==="custom",url:E.url})),...A.map(E=>({id:E.id,label:$t[E.id]??E.id,icon:Pt[E.id],isCustom:!1}))].slice(0,ja)},[p,j,N]),g=s==="custom"&&((I=i==null?void 0:i.customCardPreferences)==null?void 0:I.componentName);return f.some(S=>{var M;return S.isCustom?g&&((M=i==null?void 0:i.customCardPreferences)==null?void 0:M.componentName)===S.id:s===S.id})||(s==="custom"?(w=i==null?void 0:i.customCardPreferences)!=null&&w.componentName:$t[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(va,{selectedChart:s,onChartChange:n,compactMore:!0})]})}function va({selectedChart:s,onChartChange:n,compactMore:r=!1,responsiveCompact:o=!1}){var F,E;const[i,d]=v.useState(!1),c=t.useEditorStore(C=>C.card),{setCardType:l,setCardPreferences:u}=t.useEditorStore(C=>C.actions),{setCardCustomCfg:x,setCustomCardPreferences:m,setQueryConfig:b,replaceFrameCards:h,clearModeDrafts:p,initializeModeDrafts:j}=t.useEditorActions(),{starredCharts:N}=a.useStarredChartsStore(),{data:f=[]}=a.useCustomVisualsQuery(),g=t.useEditorStore(C=>C.isDevMode),D=((F=c==null?void 0:c.customCardPreferences)==null?void 0:F.componentName)??null,I=v.useMemo(()=>{const C=N.filter(y=>y.type==="default"?qt(y.id,{isDevMode:g}):f.some(_=>_.name===y.id)),T=new Set(C.map(y=>y.id)),L=ba.filter(y=>!T.has(y.id)&&qt(y.id,{isDevMode:g})),k=[...C.map(y=>({id:y.id,label:y.name,icon:y.type==="default"?Pt[y.id]:void 0,isCustom:y.type==="custom",url:y.url})),...L.map(y=>({id:y.id,label:$t[y.id]??y.id,icon:Pt[y.id],isCustom:!1}))];if(!k.some(y=>y.isCustom?s==="custom"&&y.id===D:y.id===s))if(s==="custom"&&D){const y=f.find(_=>_.name===D);y&&k.unshift({id:y.name,label:y.name,icon:void 0,isCustom:!0,url:y.url})}else s&&Pt[s]&&qt(s,{isDevMode:g})&&k.unshift({id:s,label:$t[s]??s,icon:Pt[s],isCustom:!1});return k.slice(0,ja)},[N,f,s,D,g]),w=s==="custom"&&D,S=C=>{if(C.isCustom){const T=f.find(R=>R.name===C.id);if(!T)return;x(null),u({}),b(void 0);const L=xe.resolveMultiInputTypeFromVisual(T);if(L==="multiple"&&T.slots&&T.slots.length>0){p();const R=xe.createCardsFromSlots(T.slots,T,c);h(R),R[0]&&j(R[0]);return}l("custom"),m({type:"component",visualType:L,url:T.url,componentName:T.name,icon:T.icon,pluginChartType:T.chartType,minInputs:T.minInputs,maxInputs:T.maxInputs}),n("custom");return}n(C.id)},M=I.some(C=>{var T;return C.isCustom?w&&((T=c==null?void 0:c.customCardPreferences)==null?void 0:T.componentName)===C.id:s===C.id}),A=M?"More":s==="custom"?((E=c==null?void 0:c.customCardPreferences)==null?void 0:E.componentName)||"Custom":$t[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:[I.map(C=>{var k;const T=C.icon,L=C.isCustom?w&&((k=c==null?void 0:c.customCardPreferences)==null?void 0:k.componentName)===C.id:s===C.id;return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>S(C),"aria-label":C.label,"aria-pressed":!!L,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&&!L&&"hidden @[800px]:flex",L&&"bg-foreground/[0.08] font-medium text-foreground"),children:[T?e.jsx(T,{className:"h-3.5 w-3.5"}):e.jsx(Ls,{chartName:C.label,isCustom:!0,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:C.label})]})}),e.jsx(t.TooltipContent,{side:"bottom",children:C.label})]},`${C.isCustom?"custom":"default"}-${C.id}`)}),e.jsxs(t.Popover,{open:i,onOpenChange:d,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":r?"More chart types":A,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&&(M?"text-muted-foreground":"text-foreground")),children:[!r&&e.jsx("span",{className:"truncate",children:A}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",i&&"rotate-180"),strokeWidth:1.75})]})}),e.jsx(t.PopoverContent,{className:"w-[360px] p-3",align:"end",onOpenAutoFocus:C=>C.preventDefault(),children:e.jsx(ga,{onChartSelect:C=>{n(C),d(!1)},onClose:()=>d(!1)})})]})]})})}function _o(){const s=t.useEditorStore(u=>{var x,m;return(m=(x=u.card.preferences)==null?void 0:x.chartOptions)==null?void 0:m.indexAxis}),n=t.useEditorStore(u=>u.card.type),{setChartOrientation:r,setCardPreferences:o}=t.useEditorStore(u=>u.actions),i=u=>{if(r(u),n!=="bullet")return;const x=u==="y"?"horizontal":"vertical",m=t.useEditorStore.getState().card.preferences,b={...m||{},bulletConfig:{...(m==null?void 0:m.bulletConfig)||{},orientation:x}};o(b)};function d(){const u=s??"x",x=()=>{i(u==="x"?"y":"x")};return e.jsx(a.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="x"?e.jsx(hs,{className:"h-3.5 w-3.5"}):e.jsx(xs,{className:"h-3.5 w-3.5"})})}function c(){const u=()=>{i(s==="y"||s===void 0?"x":"y")};return e.jsx(a.IconButton,{onClick:u,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:s==="y"||s===void 0?e.jsx(hs,{className:"h-3.5 w-3.5"}):e.jsx(xs,{className:"h-3.5 w-3.5"})})}function l(){const u=s??"y",x=()=>{i(u==="y"?"x":"y")};return e.jsx(a.IconButton,{onClick:x,tooltip:"Chart Orientation",className:"h-7 w-7 px-0",children:u==="y"?e.jsx(xs,{className:"h-3.5 w-3.5"}):e.jsx(hs,{className:"h-3.5 w-3.5"})})}return e.jsx(e.Fragment,{children:n==="funnel"?c():n==="bullet"?l():d()})}function Fs({className:s,triggerVariant:n="icon",label:r="Display options"}){var f,g,D,I,w,S,M,A,F,E;const o=t.useEditorStore(C=>C.card),{setCardPreferences:i,updateCardInFrame:d,setCard:c}=t.useEditorActions(),[l,u]=v.useState(!1),x=((g=(f=o.preferences)==null?void 0:f.displayOptions)==null?void 0:g.showFilterInfo)??!0,m=((I=(D=o.preferences)==null?void 0:D.displayOptions)==null?void 0:I.showCardToolbar)??!0,b=((S=(w=o.preferences)==null?void 0:w.displayOptions)==null?void 0:S.showChrome)??!0,h=((A=(M=o.preferences)==null?void 0:M.displayOptions)==null?void 0:A.allowScroll)??!0,p=((E=(F=o.preferences)==null?void 0:F.displayOptions)==null?void 0:E.showInlineFilterBar)??!0,j=(C,T)=>{var R;const L={...o.preferences,displayOptions:{...(R=o.preferences)==null?void 0:R.displayOptions,[C]:T}};i(L);const k={...o,preferences:L};c(k),d(k)},N=[{option:"showFilterInfo",label:"Filter info",hint:"Badge",checked:x},{option:"showCardToolbar",label:"Card toolbar",hint:"Hover actions",checked:m},{option:"showChrome",label:"Card chrome",hint:"Frame and padding",checked:b},{option:"allowScroll",label:"Allow scroll",hint:"Content scroll",checked:h},{option:"showInlineFilterBar",label:"Inline filter bar",hint:"On-card filters",checked:p}];return e.jsx("div",{className:t.cn("flex items-center",s),children:e.jsxs(a.DropdownMenu,{modal:!1,open:l,onOpenChange:u,children:[e.jsx(a.DropdownMenuTrigger,{asChild:!0,children:n==="menu"?e.jsxs(t.Button,{variant:"ghost",className:"h-auto w-full justify-start gap-2 rounded-sm px-2 py-1.5 text-[13px] font-normal",children:[e.jsx($e.Eye,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:r})]}):e.jsx(a.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(a.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx("p",{className:"px-2 pb-1.5 pt-1 text-[11px] text-muted-foreground",children:"Changes apply to dashboard view only"}),N.map(C=>e.jsxs(a.DropdownMenuCheckboxItem,{checked:C.checked,onCheckedChange:T=>j(C.option,T),onSelect:T=>T.preventDefault(),className:"[&_svg]:h-3.5 [&_svg]:w-3.5",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:C.label}),e.jsx("span",{className:"ml-3 shrink-0 text-[11px] text-muted-foreground",children:C.hint})]},C.option))]})]})})}function ya(s,n){var u,x;const r=s.qualifiedFieldName||s.name,o=s.qualifiedFieldName?s.qualifiedFieldName.split(".").slice(0,-1).join("."):s.qualifiedEntityName||s.entityName,i=n.connectionId||((u=n.dataSource)==null?void 0:u.connectionId)||"",d=t.buildFilterFieldMeta(s),c=t.buildFilterSemanticContext(n.dataSource,{connectionId:i,connectionType:(x=n.dataSource)==null?void 0:x.connectionType},s),l=t.getFilterSourceDatabase(n.dataSource,c,s)||"";return{column:r,title:a.getFieldDisplayLabel(s),dataType:s.dataType,...s.nativeDataType?{nativeDataType:s.nativeDataType}:{},table:s.entityName||"",database:l,qualifiedTableName:o,connectionId:i,operation:"in",sql:"",fieldMeta:d,semanticContext:c}}function Rs({className:s,triggerVariant:n="icon",label:r="Inline filters"}){const[o,i]=v.useState(!1),d=t.useEditorStore(S=>S.card),c=t.useEditorStore(S=>S.selectedConnectionId),{tokenProps:l}=a.useSemaphorContext(),{setCard:u}=t.useEditorActions(),x=t.useDashboardStore(S=>S.actions.removeCardInlineFilterValue),m=t.useDashboardStore(S=>S.actions.setCardInlineFilterValue),b=t.useEditorStore(S=>S.actions.removeCardInlineFilterValue),h=t.useEditorStore(S=>S.actions.setCardInlineFilterValue),p=t.useDashboardStore(S=>S.isVisualEditing),j=(d==null?void 0:d.inlineFilters)||[],N=a.useTimezone()??void 0;function f(S){if(j.find(F=>t.doesStoredFilterMatchField(F,S)))return;const A={id:je.v4(),...ya(S,{dataSource:d==null?void 0:d.dataSource,connectionId:c}),width:250};u({...d,inlineFilters:[...j,A]})}function g(S){const M=j.filter(A=>A.id!==S);u({...d,inlineFilters:M}),p?b(d.id,S):x(d.id,S)}function D(S,M){const A=j.map(T=>T.id===S?{...T,...M}:T);if(u({...d,inlineFilters:A}),!(Object.prototype.hasOwnProperty.call(M,"defaultValues")||Object.prototype.hasOwnProperty.call(M,"defaultDateFilter")))return;const E=A.find(T=>T.id===S);if(!E)return;const C=t.buildFilterValueFromDefaults(E,N);C?p?h(d.id,C):m(d.id,C):p?b(d.id,S):x(d.id,S)}if(!["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(d==null?void 0:d.type))return null;const w=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",w&&"w-full",s),children:e.jsxs(t.Popover,{open:o,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:w?e.jsxs(t.Button,{variant:"ghost",className:"h-auto w-full justify-start gap-2 rounded-sm px-2 py-1.5 text-[13px] font-normal",children:[e.jsx(En,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:r}),j.length>0&&e.jsx("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:j.length})]}):e.jsxs(a.IconButton,{tooltip:"Add Inline Filter",className:t.cn("relative h-7 w-7 px-0",{"text-primary":j.length>0}),children:[e.jsx(En,{className:"h-3.5 w-3.5"}),j.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:j.length})]})}),e.jsx(t.PopoverContent,{align:"end",className:t.cn("w-80 p-0",w&&"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(a.DndContext,{collisionDetection:a.closestCenter,children:e.jsx(a.SortableContext,{items:[],strategy:a.verticalListSortingStrategy,children:e.jsx(a.FieldsList,{context:"inline-filter",onFieldSelect:f,inlineFilters:j})})})}),j.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:j.map(S=>e.jsx(Yo,{filter:S,onUpdate:M=>D(S.id,M),onRemove:()=>g(S.id)},S.id))})]})]})})]})})}function Yo({filter:s,onUpdate:n,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(a.CustomFilterPopover,{filter:s,variant:"inline",onAccept:o=>n(o),trigger:e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(a.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(le.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,n){return s&&typeof s=="object"&&"label"in s&&typeof s.label=="string"&&s.label.trim().length>0?s.label:n||null}const $o={metric_selector:"config_metric_selector",field_selector:"config_field_selector",aggregation_selector:"config_aggregation",grain_selector:"config_grain"};function ns(s,n){return`${s}:${n}`}function Ko(s,n,r,o,i){const d=new Set(r.filter(l=>l.target!=="sql_param"&&l.target!=="presentation_currency").map(l=>ns(l.controlId,l.target))),c=n.map(l=>{const u=t.getCompatibleBindingTargetOptions({card:s,control:l,matrixSpec:o,resolveDataType:i}).map(h=>h.value),x=$o[l.type],b=[...x&&u.includes(x)?[x]:[],...u.filter(h=>h!==x)].find(h=>!d.has(ns(l.id,h)));return b?{controlId:l.id,target:b}:null}).find(Boolean);return c?{controlId:c.controlId,target:c.target,mapping:{}}:null}function Uo({card:s,dashboardControls:n,bindings:r,onChange:o,availableFieldChoices:i,matrixFieldCatalog:d=[],availableMetricChoices:c,suppressTransientStaleState:l=!1,matrixSpec:u,matrixPresentation:x}){const m=v.useMemo(()=>x??(u?bt.createMatrixConfig(u).presentation:void 0),[u,x]);function b(E){return!u||!m?[]:Dt.getMatrixBindingTargets(u,E,f).map(C=>({id:C.id,label:C.kind==="measure"?`${bt.getMatrixMeasureLabel(C.measure,m)} (${C.measure.aggregate})`:`${C.axis==="rows"?"Rows":"Columns"}: ${bt.getMatrixLevelLabel(C.level,m)}`}))}const h=[...n,...s.controls||[]],[p,j]=v.useState({}),N=Dt.extractSqlParamReferences({sql:s.sql,controlBindings:s.controlBindings});function f(E){return u?je.matrixAuthoringDataType(E,u.source,d):E.dataType}const g=t.getBindingTargetSuggestions(s,u,f),D=new Set(r.map(E=>ns(E.controlId,E.target))),I=h.some(E=>t.getCompatibleBindingTargetOptions({card:s,control:E,matrixSpec:u,resolveDataType:f}).some(C=>!D.has(ns(E.id,C.value)))),w=l?0:r.reduce((E,C)=>{const T=S(C.target),L=Object.values(C.mapping).filter(k=>{const R=C.target==="config_metric_selector"||C.target==="config_field_selector"?typeof k=="string"?k:k==null?void 0:k.id:typeof k=="string"?k:void 0;return typeof R=="string"&&!T.some(y=>y.value===R)}).length;return E+L},0);function S(E){var C,T,L,k;switch(E){case"config_metric_selector":return c?c.filter(R=>!!R.target).map(R=>({value:R.target.id,label:R.target.label||R.option.label,target:R.target})):u&&m?b(E).map(R=>({value:R.id,label:R.label,target:{kind:"matrix_instance",id:R.id}})):((T=(C=s.config)==null?void 0:C.metricColumns)==null?void 0:T.map(R=>({value:R.id,label:R.label||R.id,target:R})))||[];case"config_field_selector":return i?i.filter(R=>!!R.target).map(R=>({value:R.target.id,label:R.target.label||R.option.label,target:R.target})):u&&m?b(E).map(R=>({value:R.id,label:R.label,target:{kind:"matrix_instance",id:R.id}})):((k=(L=s.config)==null?void 0:L.groupByColumns)==null?void 0:k.map(R=>({value:R.id,label:R.label||R.id,target:R})))||[];case"config_aggregation":return(g.config_aggregation||[]).map(R=>({value:R,label:R}));case"config_grain":return(g.config_grain||[]).map(R=>({value:R,label:R.charAt(0).toUpperCase()+R.slice(1)}));default:return[]}}const M=(E,C)=>{o(r.map((T,L)=>L!==E?T:C(T)))},A=E=>{o(r.filter((C,T)=>T!==E))},F=()=>{const E=Ko(s,h,r,u,f);E&&o([...r,E])};if(typeof s.sql=="string"&&s.sql.trim().length>0){const E=N.map(({controlId:C,paramId:T})=>{const L=h.find(k=>k.id===C);return L?{id:C,paramId:T,label:L.label,reference:`[[param.${T}]]`}:{id:C,paramId:T,label:C,reference:`[[param.${T}]]`}});return e.jsx("div",{className:"space-y-2",children:E.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]]`."}):E.map(C=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referenced in SQL"})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/40 px-2 py-1",children:[e.jsx("code",{className:"text-xs",children:C.reference}),e.jsx(a.CopyButton,{text:C.reference,ariaLabel:`Copy ${C.reference}`})]})]})},`${C.id}:${C.paramId}`))})}return e.jsxs("div",{className:"space-y-4",children:[w>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(a.CircleAlert,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{children:[w," ",w===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((E,C)=>{const T=g[E.target]||[],L=h.find(V=>V.id===E.controlId),k=L?t.ensureManualSource(L):null,R=(k==null?void 0:k.source.kind)==="manual"?k.source.options:[],y=S(E.target),_=b(E.target),O=E.matrixTargetId!==void 0&&!_.some(V=>V.id===E.matrixTargetId),P=Array.from(new Set([...R.map(V=>V.value),...Object.keys(E.mapping)])).map(V=>{const $=R.find(Q=>Q.value===V);return{value:V,label:($==null?void 0:$.label)||V}}),B=`${E.controlId}-${E.target}-${C}`,Y=p[B]??C===0,q=Object.keys(E.mapping).length,z=L!=null&&L.type?zo[L.type]||L.type:null;return e.jsxs(a.Collapsible,{open:Y,onOpenChange:V=>j($=>({...$,[B]:V})),className:"rounded-md border",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[e.jsx(a.CollapsibleTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[Y?e.jsx(le.ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):e.jsx($e.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:(L==null?void 0:L.label)||"Control"}),z?e.jsx(a.Badge,{variant:"secondary",className:"shrink-0 text-[11px] font-normal text-muted-foreground",children:z}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:q>0?`${q} mapped`:"No mappings yet"})]})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>A(C),children:e.jsx(a.Trash2,{className:"h-4 w-4"})})]}),e.jsxs(a.CollapsibleContent,{className:"space-y-3 border-t px-3 pb-3 pt-2",children:[u?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",htmlFor:`matrix-target-${B}`,children:"Matrix target"}),e.jsxs(t.Select,{value:E.matrixTargetId??"__none__",onValueChange:V=>M(C,$=>{const{matrixTargetId:Q,...U}=$;return V==="__none__"?U:{...U,matrixTargetId:V}}),children:[e.jsx(t.SelectTrigger,{id:`matrix-target-${B}`,"aria-label":"Matrix target",children:e.jsx(t.SelectValue,{placeholder:"Choose target"})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"__none__",children:_.length===1?`Automatic: ${_[0].label}`:"Choose target"}),O?e.jsx(t.SelectItem,{value:E.matrixTargetId,disabled:!0,children:"Missing target"}):null,_.map(V=>e.jsx(t.SelectItem,{value:V.id,children:V.label},V.id))]})]}),O?e.jsx("p",{role:"alert",className:"text-xs text-amber-700",children:"The saved Matrix target is no longer available."}):_.length===0?e.jsx("p",{role:"alert",className:"text-xs text-muted-foreground",children:"No eligible Matrix target."}):!E.matrixTargetId&&_.length>1?e.jsx("p",{role:"alert",className:"text-xs text-amber-700",children:"Select a Matrix target."}):null]}):null,P.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."}):y.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:P.map(V=>{const $=E.mapping[V.value],Q=E.target==="config_metric_selector"||E.target==="config_field_selector"?typeof $=="string"?$:$==null?void 0:$.id:typeof $=="string"?$:void 0,U=!l&&typeof Q=="string"&&!y.some(ee=>ee.value===Q),J=qo($,Q),W=Q&&U?[...y,{value:Q,label:"Needs remap",target:$}]:y;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:V.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:Q||"__none__",onValueChange:ee=>M(C,ue=>{if(ue.target==="config_metric_selector"){const be={...ue.mapping};if(ee==="__none__")delete be[V.value];else{const ge=W.find(Pe=>Pe.value===ee);ge!=null&&ge.target?be[V.value]=ge.target:delete be[V.value]}return{...ue,mapping:be}}if(ue.target==="config_field_selector"){const be={...ue.mapping};if(ee==="__none__")delete be[V.value];else{const ge=W.find(Pe=>Pe.value===ee);ge!=null&&ge.target?be[V.value]=ge.target:delete be[V.value]}return{...ue,mapping:be}}const fe={...ue.mapping};return ee==="__none__"?delete fe[V.value]:fe[V.value]=ee,{...ue,mapping:fe}}),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"}),W.map(ee=>e.jsx(t.SelectItem,{value:ee.value,children:ee.label},ee.value))]})]}),U?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-amber-700",children:[e.jsx(a.CircleAlert,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Needs remap",J?` · Previously: ${J}`:""]})]}):null]})]},`${E.controlId}-${E.target}-${V.value}`)})}),T.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Available choices for this card: ",T.join(", ")]})]})]})]},B)}),I?e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:F,children:[e.jsx(a.Plus,{className:"mr-2 h-4 w-4"}),"Add another control response"]}):null]})}function Go(s,n,r){const{eligibleTargets:o}=a.getCardCurrencyPresentationTargets(s,n,r),i=a.getCardCurrencyPresentationFields(s),d=new Map(i.map(l=>[l.id,l])),c=new Map(a.resolveMatrixCardMeasures(s,r).map(l=>[l.measureId,l.label]));return o.map(l=>{var u;return{key:a.currencyPresentationTargetKey(l),label:l.kind==="metric"?((u=d.get(l.metricId))==null?void 0:u.label)||l.metricId:l.kind==="column"?l.columnKey:c.get(l.measureId)||l.measureId,target:l}})}function Ho(s){return s?s.kind==="metric"?s.metricId:s.kind==="column"?s.columnKey:s.measureId:"invalid target"}function Qo({matrixCatalog:s,card:n,dashboardControls:r,resultColumnKeys:o=[],bindings:i,onChange:d}){const c=[...r,...n.controls||[]],l=c.filter(a.isCurrencyPresentationControl),u=v.useMemo(()=>Go(n,o,s),[n,o,s]),x=v.useMemo(()=>a.getCardCurrencyPresentationTargets(n,o,s),[n,o,s]),m=a.diagnoseCurrencyPresentationBindings({bindings:i,controls:c,...x}),{preferences:b,resolveBoundCurrency:h}=a.useCardNumericPresentation(n,o,s),[p,j]=v.useState(""),[N,f]=v.useState(""),g=u.find(w=>w.key===N),D=!!(p&&g)&&!i.some(w=>w.presentationTarget&&g&&a.currencyPresentationTargetKey(w.presentationTarget)===g.key),I=w=>{if(!b)return;const S=a.resolveCurrencyPresentationTargetFormat({card:n,target:w,resultColumnKeys:o,valueFormatPreferences:b,boundCurrency:h(w),matrixCatalog:s});if(S)return ea.formatNumericCanonical(1e3,S)};return l.length===0&&i.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."})]}),i.map((w,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:[w.controlId," →"," ",Ho(w.presentationTarget),w.presentationTarget?` · ${I(w.presentationTarget)??"unavailable"}`:null]}),e.jsx(t.Button,{variant:"ghost",size:"xs",onClick:()=>d(i.filter((M,A)=>A!==S)),children:e.jsx(a.Trash2,{className:"h-3.5 w-3.5"})})]},`${w.controlId}:${JSON.stringify(w.presentationTarget)}`)),m.length>0?e.jsx("div",{className:"space-y-1 text-xs text-destructive",children:m.map((w,S)=>e.jsxs("p",{children:[w.controlId?`${w.controlId}: `:"",w.code.split("_").join(" ")]},`${w.controlId||"binding"}:${w.code}:${S}`))}):null,e.jsxs("div",{className:"grid grid-cols-[1fr_1fr_auto] gap-2",children:[e.jsxs(t.Select,{value:p,onValueChange:j,children:[e.jsx(t.SelectTrigger,{size:"xs",children:e.jsx(t.SelectValue,{placeholder:"Currency control"})}),e.jsx(t.SelectContent,{children:l.map(w=>e.jsx(t.SelectItem,{value:w.id,children:w.label},w.id))})]}),e.jsxs(t.Select,{value:N,onValueChange:f,children:[e.jsx(t.SelectTrigger,{size:"xs",children:e.jsx(t.SelectValue,{placeholder:"Target"})}),e.jsx(t.SelectContent,{children:u.map(w=>e.jsx(t.SelectItem,{value:w.key,children:w.label},w.key))})]}),e.jsx(t.Button,{variant:"outline",size:"xs",disabled:!D,onClick:()=>{g&&(d([...i,{controlId:p,target:"presentation_currency",presentationTarget:g.target}]),f(""))},children:e.jsx(a.Plus,{className:"h-3.5 w-3.5"})})]})]})}const Jo=[];function Ps({className:s,triggerVariant:n="icon",label:r="Controls"}){var B,Y,q;const{handleOpenChange:o,preventPassiveDismissDuringCreate:i,resolvedOpen:d,setIsCreateFlowActive:c}=jt.useCreateFlowOverlayState({}),l=t.useEditorStore(z=>z.card),u=t.useEditorStore(z=>z.frame),x=t.useEditorStore(z=>z.queryResultColumns),m=t.useDashboardStore(z=>z.dashboard),h=t.useDashboardStore(z=>z.dashboard.controls)||Jo,{setCard:p,updateCardInFrame:j}=t.useEditorActions(),[N,f]=v.useState(null);v.useEffect(()=>{d&&!N&&(l!=null&&l.id)&&f(l.id)},[l==null?void 0:l.id,d,N]),v.useEffect(()=>{!d&&N!==null&&f(null)},[d,N]);const g=v.useMemo(()=>N?(u==null?void 0:u.cards.find(z=>z.id===N))||((l==null?void 0:l.id)===N?l:void 0):l,[l,u==null?void 0:u.cards,N]),D=(g==null?void 0:g.type)==="matrixTable"?(B=g.config)==null?void 0:B.matrix:void 0,I=v.useMemo(()=>d&&D?mr.matrixCatalogSources(D.spec,g==null?void 0:g.controlBindings):[],[d,D,g==null?void 0:g.controlBindings]),w=a.useMatrixSourceCatalog(I),S=v.useMemo(()=>w.catalog.map(z=>({...z.field,dataType:at.normalizeAnalyticsCatalogDataType(z.resolvedField.dataType)})),[w.catalog]),M=(g==null?void 0:g.controls)||[],A=g?t.collectDashboardControlIds(m,{excludeCardId:g.id}):h.map(z=>z.id),F=((g==null?void 0:g.controlBindings)||[]).filter(a.isStructuralControlBinding),E=((g==null?void 0:g.controlBindings)||[]).filter(a.isPresentationCurrencyBinding),C=a.buildCardControlUsageById({card:g,controls:M}),T={choices:t.getFieldSelectorChoicesForCard(g),targetMap:Object.fromEntries((((Y=g==null?void 0:g.config)==null?void 0:Y.groupByColumns)||[]).map(z=>[z.id,z]))},L={choices:t.getMetricSelectorChoicesForCard(g),targetMap:Object.fromEntries((((q=g==null?void 0:g.config)==null?void 0:q.metricColumns)||[]).map(z=>[z.id,z]))},k=T.choices.map(z=>({option:z,target:T.targetMap[z.value]})),R=L.choices.map(z=>({option:z,target:L.targetMap[z.value]})),y=(z,V)=>{if(!g)return;const $=(V==null?void 0:V.type)==="rename"?t.applyControlMutationToCard(g,{type:"rename",oldId:V.oldId,newId:V.newId}):(V==null?void 0:V.type)==="remove"?t.applyControlMutationToCard(g,{type:"remove",controlId:V.controlId}):g,Q={...$,controls:z,controlBindings:t.syncStructuralBindingsWithControls($.controlBindings,z)};j(Q),(l==null?void 0:l.id)===Q.id&&p(Q)},_=z=>{if(!g)return;const V={...g,controlBindings:[...t.mergeConfigBindingsWithSqlParamBindings(z,(g.controlBindings||[]).filter($=>!a.isPresentationCurrencyBinding($))),...E]};j(V),(l==null?void 0:l.id)===V.id&&p(V)},O=z=>{if(!g)return;const V={...g,controlBindings:[...(g.controlBindings||[]).filter($=>!a.isPresentationCurrencyBinding($)),...z]};j(V),(l==null?void 0:l.id)===V.id&&p(V)},P=n==="menu";return e.jsx("div",{className:t.cn("flex items-center gap-1",P&&"w-full",s),children:e.jsxs(t.Popover,{modal:!0,open:d,onOpenChange:o,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:P?e.jsxs(t.Button,{variant:"ghost",className:"h-auto w-full justify-start gap-2 rounded-sm px-2 py-1.5 text-[13px] font-normal",children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:r}),M.length+F.length>0&&e.jsx("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:M.length+F.length})]}):e.jsxs(a.IconButton,{tooltip:"Configure Controls",className:t.cn("relative h-7 w-7 px-0",{"text-primary":M.length>0||F.length>0}),children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5"}),M.length+F.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:M.length+F.length})]})}),e.jsxs(t.PopoverContent,{className:t.cn("flex max-h-[85vh] w-[560px] max-w-[95vw] flex-col",P&&"z-[60]"),align:"end",onEscapeKeyDown:i,onPointerDownOutside:i,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."}),g!=null&&g.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(jt.ControlDefinitionListEditor,{scope:"card",card:g,controls:M,reservedControlIds:A,usageByControlId:C,availableFieldChoices:k,availableMetricChoices:R,onCreateFlowActiveChange:c,onChange:(z,V,$)=>y(z,$),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."})]}),g?e.jsxs(e.Fragment,{children:[e.jsx(Uo,{card:g,dashboardControls:h,bindings:F,onChange:_,availableFieldChoices:D?void 0:k,availableMetricChoices:D?void 0:R,matrixSpec:D==null?void 0:D.spec,matrixPresentation:D==null?void 0:D.presentation,matrixFieldCatalog:S,suppressTransientStaleState:!!(D&&w.pending)}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(Qo,{matrixCatalog:w.catalog,card:g,dashboardControls:h,resultColumnKeys:x,bindings:E,onChange:O})})]}):null]})})]})]})})}function Ca({showOrientation:s=!0,showGridStyle:n=!0,showInlineFilters:r=!0,showControls:o=!0,showDisplayOptions:i=!0}={}){const d=t.useEditorStore(p=>p.card),c=t.useEditorStore(p=>{var j,N;return(N=(j=p.card)==null?void 0:j.preferences)==null?void 0:N.chartOptions}),l=a.getChartGridStyle(c),{setChartGrid:u}=t.useEditorActions();function x(){const p=["xy","none","x","y"],N=(p.indexOf(l)+1)%p.length;u(p[N])}const m=s&&["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(d.type),b=n&&!["pie","doughnut","funnel","radar","polarArea","table","aggregateTable","pivotTable","detailTable","custom","kpi","text","map"].includes(d.type);return m||b||r||o||i?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[m&&e.jsx(e.Fragment,{children:e.jsx(_o,{})}),b&&e.jsxs(a.IconButton,{tooltip:"Grid Style",onClick:x,className:"h-7 w-7 px-0",children:[(l==="xy"||!l)&&e.jsx(a.Grid3x3,{className:"h-3.5 w-3.5"}),l==="x"&&e.jsx(Ds,{className:"h-3.5 w-3.5"}),l==="y"&&e.jsx(a.Rows3,{className:"h-3.5 w-3.5"}),l==="none"&&e.jsx(a.Square,{className:"h-3.5 w-3.5"})]}),r&&e.jsx(Rs,{}),o&&e.jsx(Ps,{}),i&&e.jsx(Fs,{})]}):null}function Wo({errorMessage:s,errorSql:n,onOpenInEditor:r,onDebugWithAssistant:o}){const{feedbackDialogOpen:i,setFeedbackDialogOpen:d,handleSendFeedback:c,feedbackPayload:l}=ha(s,n);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(rs,{error:s,errorSql:n,errorMessageClassName:"max-h-40",fillAvailableSqlHeight:!0,className:"max-h-none",onOpenInEditor:r,onDebugWithAssistant:o,onSendFeedback:c,showFeedbackButton:!0})}),e.jsx(a.FeedbackDialog,{open:i,onOpenChange:d,feedbackData:l,showDebugInfo:!0})]})}function Xo({isPreviewMode:s,onPreviewToggle:n,configCard:r}){var _,O,P,B,Y;const o=t.useEditorStore(q=>q.frame),i=t.useEditorStore(q=>q.card),d=t.useEditorStore(q=>q.editorContext),c=(d==null?void 0:d.type)==="documentSection",{setFrame:l,setActiveTabCardId:u,setCard:x,updateCardInFrame:m,clearModeDrafts:b,initializeModeDrafts:h}=t.useEditorActions(),{manifest:p}=a.useCustomVisual(((_=r==null?void 0:r.customCardPreferences)==null?void 0:_.url)||""),j=(O=p==null?void 0:p.visuals)==null?void 0:O.find(q=>{var z;return q.name===((z=r==null?void 0:r.customCardPreferences)==null?void 0:z.componentName)}),f=xe.resolveMultiInputType(r,j)==="multiple",g=(j==null?void 0:j.minInputs)??((P=r==null?void 0:r.customCardPreferences)==null?void 0:P.minInputs)??1,D=(j==null?void 0:j.maxInputs)??((B=r==null?void 0:r.customCardPreferences)==null?void 0:B.maxInputs),I=v.useMemo(()=>xe.getCustomVisualInputCards({frame:o,configCard:r,isMultiInputVisual:f}),[o,r,f]),w=f?I.filter(Boolean).length:o.cards.length,S=c?!1:D?w<D:!0,M=w>Math.max(g||1,1),A=!!((Y=r==null?void 0:r.customCardPreferences)!=null&&Y.dataInputCardIds),F=(q,z)=>{q.dataTransfer.setData("tabIndex",z.toString())},E=q=>{q.preventDefault()},C=(q,z)=>{const V=q.dataTransfer.getData("tabIndex");if(V===z.toString())return;const $=Array.from(o.cards),[Q]=$.splice(parseInt(V),1);$.splice(z,0,Q),l({...o,cards:$})};function T(q){const z=(r==null?void 0:r.id)===q;if(!(A&&z?o.cards.length>1:M))return;let $=o.cards.filter(W=>W.id!==q);f&&!A&&($=xe.reindexSlotCards($));const Q=$[0],U={...o,cards:$,activeCardId:Q.id},J=q===i.id;J&&b(),l(U),u(Q.id),x(Q),J&&h(Q)}function L(q,z){if(!S)return;const V={...o,cards:[...o.cards,z],activeCardId:q.id};l(V),u(z.id)}function k(){if(c)return;if(f&&(r==null?void 0:r.id)===i.id){R(i);return}const q={...i,id:je.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:f?Math.max(-1,...I.map((z,V)=>xe.getSlotIndexForCard(z,V)))+1:i.customCardPreferences.slotIndex}:void 0};L(i,q)}function R(q){var J;if(c||!S)return;let z=f?"table":"bar",V="Title",$="";const Q=f?Math.max(-1,...I.map((W,ee)=>xe.getSlotIndexForCard(W,ee)))+1:w;if(f&&((J=j==null?void 0:j.slots)!=null&&J.length)){const W=xe.getSlotDefinitionForIndex(j.slots,Q);W&&(z=xe.getSlotExpectedChartType(W),V=W.label||`Tab ${Q+1}`,$=W.description||"")}const U={dataSource:q.dataSource,connectionId:q.connectionId,lastSelectedDatabase:q.lastSelectedDatabase,lastSelectedSchema:q.lastSelectedSchema,lastSelectedTable:q.lastSelectedTable,lastSelectedDatamodelId:q.lastSelectedDatamodelId,id:je.v4(),title:V,tabTitle:V,description:$,preferences:{onClickFilter:[{columnIndex:0,expression:""}],...z==="text"?{textVisualOptions:{richContent:t.createEmptyRichContent()}}:{}},type:z,sql:"",data:[],mode:"explorer",...f&&{customCardPreferences:{slotIndex:Q}}};L(q,U)}function y(q,z){return q.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||q.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const V=z.displayTab===void 0?!1:!z.displayTab;x({...z,displayTab:V}),m({...z,displayTab:V})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx($e.Eye,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"}):e.jsx(a.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((q,z)=>{var J,W;const V=f?xe.getSlotIndexForCard(q,z):-1,$=f&&((J=j==null?void 0:j.slots)!=null&&J.length)&&V>=0?xe.getSlotDefinitionForIndex(j.slots,V):null,Q=$?(Array.isArray($.expectedType)?$.expectedType[0]:$.expectedType)||"table":q.type,U=f&&((W=j==null?void 0:j.slots)==null?void 0:W.length)&&j.slots.every(ee=>typeof ee.position=="number"||typeof ee.position=="string"&&!ee.position.includes("+"));return e.jsxs(t.TabsTrigger,{draggable:!f&&!c,onDragStart:f||c?void 0:ee=>F(ee,z),onDragOver:f||c?void 0:E,onDrop:f||c?void 0:ee=>C(ee,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:q.id,children:[f&&$?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:a.getChartIconByType(Q,"size-3.5")}),e.jsx("span",{children:$.label||`Tab ${V+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:$.label}),$.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:$.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[$.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($.expectedType)?$.expectedType.join(" / "):$.expectedType}),$.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:[y(o,q),e.jsx(a.Editable,{enabled:o.activeCardId===q.id,text:q.tabTitle||q.title,onSave:ee=>{x({...i,tabTitle:ee}),m({...i,tabTitle:ee})},children:q.tabTitle||q.title},q.id)]}),!c&&o.activeCardId===q.id&&!U&&e.jsx(a.CopyPlus,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:ee=>{ee.stopPropagation(),k()}}),!c&&o.activeCardId===q.id&&(A&&(r==null?void 0:r.id)===q.id?o.cards.length>1:M)&&e.jsx(le.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground",onClick:()=>T(q.id)})]},q.id)}),!c&&e.jsx(a.IconButton,{tooltip:"Add Card",className:"h-6 w-6 rounded-[5px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>R(i),disabled:!S,children:e.jsx(a.Plus,{className:"h-3 w-3"})}),f&&e.jsxs(a.Toggle,{pressed:s,onPressedChange:n,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(a.EyeOff,{className:"h-3 w-3"}):e.jsx($e.Eye,{className:"h-3 w-3"}),e.jsx("span",{children:"Preview"})]})]})})}function It({renderCardOverride:s,alwaysRenderOverride:n=!1}={}){var Le,Ke,Se,oe,Ie,Re,De;const r=a.useResolvedTemporalStylePreferences(),o=t.useEditorStore(te=>te.frame),i=t.useEditorStore(te=>te.card),[d,c]=v.useState(!1),l=v.useMemo(()=>xe.findCustomVisualConfigCard(o,i),[o,i]),u=t.useEditorStore(te=>te.isSqlRunning);t.useEditorStore(te=>te.isDevMode);const{setFrame:x,setActiveTabCardId:m,setCard:b,setRunSql:h,mergeDraftsIntoCard:p,clearModeDrafts:j,initializeModeDrafts:N,updateColumnSettingsMap:f}=t.useEditorActions(),g=Object.keys(((Ke=(Le=i.preferences)==null?void 0:Le.tablePrefs)==null?void 0:Ke.columnSettingsMap)??{}).length>0,[D,I]=v.useState({}),[w,S]=v.useState(()=>new Set),{authToken:M}=a.useSemaphorContext(),A=t.getTokenParams(M==null?void 0:M.accessToken),{compiledAppearance:F}=ur.useAppearance(),E=v.useMemo(()=>a.buildCustomCardTheme(F),[F]),{getCard:C,manifest:T,isLoading:L}=a.useCustomVisual(((Se=l==null?void 0:l.customCardPreferences)==null?void 0:Se.url)||""),k=(oe=l==null?void 0:l.customCardPreferences)==null?void 0:oe.componentName,R=k?C(k):null,y=(Ie=T==null?void 0:T.visuals)==null?void 0:Ie.find(te=>te.name===k),_=xe.resolveMultiInputType(l,y),O=d&&_==="multiple"&&!!l,P=v.useMemo(()=>xe.getCustomVisualInputCards({frame:o,configCard:l,isMultiInputVisual:!0}).map(ve=>(ve==null?void 0:ve.id)===i.id?i:ve),[o,l,i]),B=v.useMemo(()=>xe.buildSlotOrderedCards(P),[P]),Y=v.useMemo(()=>{const te=P.findIndex(ve=>(ve==null?void 0:ve.id)===i.id);return te<0?-1:xe.getSlotIndexForCard(i,te)},[P,i]),q=v.useMemo(()=>!l||_!=="multiple"||Y<0?i.type:xe.getEffectiveCardTypeForSlot(i,Y,y==null?void 0:y.slots)??i.type,[l,_,Y,i,y==null?void 0:y.slots]),z=v.useMemo(()=>O?{...i,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:q!==i.type?{...i,type:q}:i,[i,q,O]),{data:V,dataUpdatedAt:$,isLoading:Q,isFetching:U,isError:J,errorMessage:W,errorSql:ee,queryKey:ue}=a.useEditorCardQuery(z),fe=JSON.stringify(ue),{handleOpenInEditor:be,handleDebugWithAssistant:ge}=As(W,ee||i.sql||i.python),Pe=i.type==="text"&&((De=(Re=i.preferences)==null?void 0:Re.textVisualOptions)==null?void 0:De.isDynamicText)===!0&&!!W,Oe=v.useCallback((te,ve)=>{const ye=xe.normalizeMultiInputPayload(ve);I(Qe=>({...Qe,[te]:ye}))},[]),ke=v.useCallback((te,ve)=>{S(ye=>{const Qe=new Set(ye);return ve?Qe.add(te):Qe.delete(te),Qe})},[]),Te=w.size>0,_e=v.useMemo(()=>B.map((te,ve)=>xe.getEffectiveCardTypeForSlot(te,ve,y==null?void 0:y.slots)),[B,y==null?void 0:y.slots]),ze=v.useMemo(()=>a.createCustomVisualTemporalBucketFormatter(a.buildMultiInputTemporalPresentationInputs({slotOrderedCards:B,multiInputData:D,valueFormatPreferences:r})),[D,B,r]),Be=a.useCardTransientContexts(),Ae=t.useDashboardStore(te=>te.dashboard.filters),Me=t.useDashboardStore(te=>te.filterValues),ae=t.useDashboardStore(te=>te.selectedSheetId),K=t.useEditorStore(te=>te.inlineFilterValuesMap[(l==null?void 0:l.id)||""]),ie=t.useEditorStore(te=>te.actions.setCardInlineFilterValue),Ce=t.useEditorStore(te=>te.actions.removeCardInlineFilterValue),re=v.useMemo(()=>l?a.buildInlineFilterNodes({card:l,sheetId:ae||"",inlineFilterValues:K,setInlineFilterValue:te=>ie(l.id,te),removeInlineFilterValue:te=>Ce(l.id,te)}):[],[l,ae,K,ie,Ce]),{cardFilters:he,cardFilterValues:Ye}=v.useMemo(()=>l?a.calculateContextAwareFilters({card:l,transientContexts:Be,filters:Ae,filterValues:Me,selectedSheetId:ae}):{cardFilters:[],cardFilterValues:[]},[l,Be,Ae,Me,ae]);function Z(te){const ve=o.cards.find(ye=>ye.id===te);ve&&(a.flushPendingEditorDrafts(),p(),Fe(te),m(te),j(),N(ve))}function Fe(te){const ve=t.useEditorStore.getState().card,ye=t.useEditorStore.getState().frame,Qe={...ye,cards:ye.cards.map(ut=>ut.id===ve.id?ve:ut),activeCardId:te};x(Qe);const st=Qe.cards.find(ut=>ut.id===te);st.sql&&h(!0),b(st)}function me(){return L?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})}):R?e.jsxs("div",{className:"relative flex h-full flex-col pl-2 pr-4",children:[P.map((ve,ye)=>{if(!ve)return null;const Qe=xe.getSlotIndexForCard(ve,ye),st=xe.getEffectiveCardTypeForSlot(ve,Qe,y==null?void 0:y.slots);return e.jsx(a.MultiInputEmptyRenderer,{onLoadingStatus:ke,onDataChange:Oe,card:ve,effectiveCardType:st},`${ve.id}-${Qe}`)}),Te&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(a.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",Te&&"opacity-50"),children:e.jsx(v.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(a.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(R,{editing:!0,...a.buildMultiInputCustomVisualProps({configCard:l,slotOrderedCards:B,slotTypes:_e,multiInputData:D,params:A,theme:E,filters:he,filterValues:[...Ye||[],...K||[]],inlineFilters:re,formatTemporalBucketValue:ze})})})})]}):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 qe(){var te;return O?me():s&&(n||!Q&&!U&&!J&&!W)?s({card:i,data:V,isLoading:Q,isFetching:U,isError:J}):i.type==="kpi"?Q||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):W?e.jsx(Wo,{errorMessage:W,errorSql:ee||i.sql||i.python,onOpenInEditor:be,onDebugWithAssistant:ge}):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(a.KPICard,{card:i,data:V==null?void 0:V.records,isPending:Q||U,isError:J,comparisonMetadata:(te=V==null?void 0:V.metadata)==null?void 0:te.comparisonMetadata})}),a.isCardSummaryVisibleOnCard(i)&&e.jsx(a.CardSummary,{card:i,mode:"editor",records:V==null?void 0:V.records})]})}):i.type==="text"?Q||U?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):Pe?e.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-auto px-4 py-0",children:e.jsx(rs,{error:W,errorSql:ee||i.sql||i.python,onOpenInEditor:be,onDebugWithAssistant:ge,showFeedbackButton:!1})}):e.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 py-4",children:e.jsx(a.TextCard,{isLoading:u,card:i,data:V==null?void 0:V.records})}):e.jsx(a.ErrorBoundary,{fallbackRender:ve=>e.jsx(a.FallbackVisual,{...ve,onResetColumnSettings:g?()=>f({}):void 0}),resetKeys:[fe,$,U],children:e.jsx(pa,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:Z,value:o.activeCardId,className:"flex min-h-0 flex-1 flex-col",children:[O?e.jsx("div",{className:"mt-0 min-h-0 flex-1 overflow-hidden",children:qe()}):o.cards.map(te=>e.jsx(t.TabsContent,{className:"mt-0 min-h-0 flex-1 overflow-hidden focus-visible:ring-0 focus-visible:ring-offset-0",value:te.id,children:qe()},te.id)),e.jsx(Xo,{isPreviewMode:O,onPreviewToggle:c,configCard:l})]})}function Zo({onClick:s,className:n}){return e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:t.cn("h-8 gap-1.5 px-3 text-xs",n),onClick:s,children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),"Customize"]})}function Na({fallbackPreview:s,records:n,title:r,isInspectorOpen:o,onInspectorOpenChange:i}){var k;const d=t.useEditorStore(R=>R.card),c=t.useEditorStore(R=>R.actions.setCard),l=t.useEditorStore(R=>R.actions.updateCardInFrame),u=t.normalizeDynamicRendererSource((k=d.dynamicCardPreferences)==null?void 0:k.rendererCode),[x,m]=v.useState(u),[b,h]=v.useState(u);v.useEffect(()=>{m(u),h(u)},[u,d.id]);const p=v.useMemo(()=>t.normalizeDynamicRendererSource(x),[x]),j=v.useMemo(()=>t.validateDynamicRendererSource(p),[p]),N=!!u,f=v.useMemo(()=>{var R;return t.buildCardWithVisualizationMode(d,b?"dynamic":"builtin",{rendererCode:b||void 0,artifactId:((R=d.dynamicCardPreferences)==null?void 0:R.artifactId)||d.id,title:r||d.title})},[d,b,r]),g=!!b,D=p!==b,I=b!==u,w=!p||!j.valid||D||I,S=p?j.valid?D?"Unapplied changes":"Pending save":"Needs attention":"Draft",M=!p||D||I?"outline":"destructive",A=p?j.valid?D?"The preview still reflects the last applied code until you apply this draft.":I?"Preview reflects pending changes. Accept changes to save them.":"":j.error||"Visual code is invalid.":"Paste visual code or generate one before saving this card.";function F(){if(!j.valid){t.ue.error(j.error||"Visual code is invalid.");return}h(p),t.ue.success("Dynamic preview updated.")}function E(){m(b)}function C(){var y;const R=t.buildCardWithVisualizationMode(d,b?"dynamic":"builtin",{rendererCode:b||void 0,artifactId:((y=d.dynamicCardPreferences)==null?void 0:y.artifactId)||je.v4(),title:r||d.title});c(R),l(R),i(!1),t.ue.success(b?"Dynamic visual changes saved.":"Dynamic visual cleared.")}function T(){m(u),h(u),i(!1)}function L(){m(""),h("")}return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 bg-background px-2",children:N?e.jsx(a.PersistedDynamicVisual,{card:d,records:n,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(a.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:()=>i(!0)})]})}),e.jsx(a.Dialog,{open:o,onOpenChange:R=>{if(!R){T();return}i(!0)},children:e.jsxs(a.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(a.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(a.DialogTitle,{children:"Dynamic Visual Editor"}),e.jsx(a.DialogDescription,{children:"Adjust the preview and visual code here. Query editing stays in the normal editor controls."})]}),w&&e.jsx(a.Badge,{className:"mr-4 shrink-0",variant:M,children:S})]})}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsxs(a.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(a.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:g?e.jsx(a.PersistedDynamicVisual,{card:f,records:n,title:r,layoutMode:"fill",fallback:s},b||"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(a.ResizableHandle,{withHandle:!0}),e.jsx(a.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(a.CodeXml,{className:"h-4 w-4 text-muted-foreground"}),"Visual Code"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(a.AlertDialog,{children:[e.jsx(a.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:!N&&!p,children:[e.jsx(le.X,{className:"h-3.5 w-3.5 shrink-0"}),"Clear"]})}),e.jsxs(a.AlertDialogContent,{children:[e.jsxs(a.AlertDialogHeader,{children:[e.jsx(a.AlertDialogTitle,{children:"Clear dynamic visual?"}),e.jsx(a.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(a.AlertDialogFooter,{children:[e.jsx(a.AlertDialogCancel,{children:"Cancel"}),e.jsx(a.AlertDialogAction,{className:"bg-foreground text-background hover:bg-foreground/90",onClick:L,children:"Clear"})]})]})]}),e.jsxs(t.Button,{type:"button",size:"sm",variant:"outline",className:"h-8 gap-1.5 px-2.5 text-xs",onClick:E,disabled:!D,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:F,disabled:!D||!j.valid,children:[e.jsx(a.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:[A&&e.jsx("p",{className:t.cn("text-xs",j.valid?"text-muted-foreground":"text-destructive"),children:A}),e.jsx("div",{className:t.cn("min-h-0 flex-1 overflow-hidden rounded-md border",!j.valid&&p&&"border-destructive"),children:e.jsx(t.CodeEditor,{value:x,onValueChange:R=>m(R||""),language:"javascript",embedded:!0})})]})]})})]})}),e.jsxs(a.DialogFooter,{className:"border-t px-6 py-4 sm:justify-between",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:A||"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:T,children:"Cancel"}),e.jsx(t.Button,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:C,disabled:!I,children:"Accept changes"})]})]})]})})]})}function Sa({onCustomize:s}){const n=t.useEditorStore(x=>x.card),r=t.useEditorStore(x=>x.frame),o=t.useEditorStore(x=>x.actions.setIsShowingVisual),{setVisualizationMode:i,setDynamicCardPreferences:d}=t.useEditorActions(),l=t.getVisualizationMode(n)==="dynamic";if(r.cards.length!==1||t.isCustomVisualizationCard(n))return null;const u=x=>{var m;x==="dynamic"&&!n.dynamicCardPreferences&&d(t.createEmptyDynamicCardPreferences(n.type,(m=n.preferences)==null?void 0:m.displayOptions)),i(x),o(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(a.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),u(l?"builtin":"dynamic")},className:"justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.CodeXml,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:"Dynamic"})]}),e.jsx(t.Switch,{size:"xs",checked:l,onCheckedChange:x=>u(x?"dynamic":"builtin"),onClick:x=>x.stopPropagation()})]}),l&&s?e.jsxs(a.DropdownMenuItem,{onSelect:x=>{x.preventDefault(),s()},children:[e.jsx(t.SlidersHorizontal,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Customize visual"]}):null]})}function wa({sql:s,showCardDetails:n=!1,debugPayloads:r,className:o}){const[i,d]=v.useState(!1),c=t.useEditorStore(b=>b.isDevMode),l=t.useEditorStore(b=>b.card.type),{switchEditorMode:u,setRunSql:x}=t.useEditorActions(),m=()=>{u("dev",{sqlToLoad:s}),setTimeout(()=>{x(!0)},100)};return e.jsx(la,{className:t.cn("overflow-hidden",o),children:e.jsx(ma,{sql:s,label:"Generated query",ariaLabel:"Executed SQL",copyAriaLabel:"Copy generated query",headerActions:c?void 0:e.jsxs(e.Fragment,{children:[je.supportsSqlEditor(l)&&e.jsx(t.Button,{onClick:m,variant:"outline",size:"xs",className:Ot,children:"Open in SQL editor"}),n&&e.jsx(da,{isOpen:i,onClick:()=>d(b=>!b)})]}),className:"min-h-0",bodyClassName:"max-h-[min(420px,calc(var(--radix-hover-card-content-available-height,100vh)-3rem))]",children:i&&n&&e.jsx(ua,{debugPayloads:r})})})}function gs({children:s,visualAsideControl:n,mode:r="both",inlineToolbar:o=!1,overflowActions:i,isDynamicInspectorOpen:d,onDynamicInspectorOpenChange:c}){var Fe;const l=a.useQueryClient(),u=t.useEditorStore(me=>me.frame),x=t.useEditorStore(me=>me.card),m=t.useEditorStore(me=>me.isDevMode),b=t.useEditorStore(me=>me.editorContext),h=(b==null?void 0:b.type)==="documentSection",p=t.useEditorStore(me=>me.isShowingVisual),j=t.useEditorStore(me=>me.actions.setIsShowingVisual),N=t.useDashboardStore(me=>me.isVisualEditing),{isConsoleMode:f}=a.useDashboardPreferences(),g=t.useEditorStore(me=>me.pythonStdOut),D=t.useEditorStore(me=>me.actions.setRunSql),I=a.useEffectiveEditorCardType(),w=I==="table"||I==="detailTable"||I==="matrixTable",M=a.supportsRegularTableSettings(I)&&!!(n!=null&&n.onOpen),F=t.getVisualizationMode(x)==="dynamic",[E,C]=v.useState(!1),T=d??E,L=c??C,{setFrame:k,setCard:R,setActiveTabCardId:y,mergeDraftsIntoCard:_,clearModeDrafts:O,initializeModeDrafts:P,updatePageSize:B,updateCardInFrame:Y,setCardType:q}=t.useEditorActions(),z=v.useMemo(()=>I!==x.type?{...x,type:I}:x,[x,I]),{data:V,isLoading:$,isFetching:Q,errorMessage:U,errorSql:J,refetch:W,queryKey:ee,pagination:ue}=a.useEditorCardQuery(z),fe=v.useRef(ee);fe.current=ee;const{handleDebugWithAssistant:be}=As(U,J),ge=v.useMemo(()=>(V==null?void 0:V.records)||[],[V==null?void 0:V.records]),{cardFilterValues:Pe}=mo((x==null?void 0:x.id)??""),[Oe,ke]=v.useState(!1),Te=a.useMatrixEditorRefresh(x),[_e,ze]=v.useState();v.useEffect(()=>{Q||ke(!1)},[Q]);const Be=()=>{var me;if(Te){(me=Te.refresh)==null||me.call(Te);return}if(ke(!0),m){a.flushPendingEditorDrafts(),setTimeout(()=>{l.removeQueries({queryKey:fe.current,exact:!0}),D(!0)},0);return}W()};v.useEffect(()=>{w&&!p&&!m&&!f&&j(!0)},[f,m,w,p,j]);function Ae(me,qe){var Se,oe;const Le={...x,paginationConfig:{page:me+1,pageSize:qe}};R(Le);const Ke={...u,cards:u.cards.map(Ie=>Ie.id===x.id?Le:Ie)};k(Ke),x.sql&&((oe=(Se=x.preferences)==null?void 0:Se.tablePrefs)!=null&&oe.enableDevModePagination)&&D(!0)}function Me(me){var Se,oe,Ie,Re,De;const qe=a.sortStateToSortByColumns(me,(Se=x.config)==null?void 0:Se.metricColumns,(oe=x.config)==null?void 0:oe.groupByColumns,(Ie=x.config)==null?void 0:Ie.detailColumns),Le={...x,config:{...x.config||{},sortByColumns:qe}};R(Le);const Ke={...u,cards:u.cards.map(te=>te.id===x.id?Le:te)};k(Ke),x.sql&&((De=(Re=x.preferences)==null?void 0:Re.tablePrefs)!=null&&De.enableDevModePagination)&&D(!0)}const ae=Array.isArray(V==null?void 0:V.records)?V.records:[],K=ae.length>0;function ie(){var qe;if(!K)return;const me=JSON.stringify(ae,null,2);typeof navigator>"u"||!((qe=navigator.clipboard)!=null&&qe.writeText)||navigator.clipboard.writeText(me).catch(Le=>{console.error("Failed to copy JSON",Le)})}function Ce(){if(!K)return;const me=JSON.stringify(ae,null,2),qe=new Blob([me],{type:"application/json"}),Le=URL.createObjectURL(qe),Ke=document.createElement("a");Ke.href=Le,Ke.download=`${x.title}.json`,Ke.click()}function re(){if(!K)return;const qe=[Object.keys(ae.reduce((oe,Ie)=>({...oe,...Ie}),{})).join(","),...ae.map(oe=>Object.values(oe).join(","))].join(`
172
- `),Le=new Blob([qe],{type:"text/csv"}),Ke=URL.createObjectURL(Le),Se=document.createElement("a");Se.href=Ke,Se.download=`${x.title}.csv`,Se.click()}if(!x)return e.jsx(e.Fragment,{children:"No Active Card"});const he=r==="both"||r==="toolbar",Ye=r==="both"||r==="canvas",Z=!$&&!Q&&!U&&(V!=null&&V.sql)?e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:o?e.jsx(a.IconButton,{className:"h-7 w-7 shrink-0 px-0",buttonProps:{"aria-label":"View executed SQL"},children:e.jsx(jr,{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(a.HoverCardContent,{align:"end",collisionPadding:16,className:"w-[500px] overflow-hidden p-0",children:e.jsx(wa,{sql:V.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",!w&&"pt-2")),children:[he&&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?Z:null,p&&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:!h&&!F&&e.jsx(va,{selectedChart:x.type,onChartChange:me=>q(me),compactMore:!0,responsiveCompact:o})})}),!p&&!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:Z,Pe&&Pe.length>0&&e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(a.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:Pe.length})]})}),e.jsxs(a.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(Pe,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),!F&&e.jsx("div",{className:o?"hidden @[1250px]:flex":"",children:e.jsx(Ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1})}),(n==null?void 0:n.show)&&e.jsxs(t.Button,{type:"button",variant:"ghost",size:"xs","aria-pressed":n.isOpen,onClick:n.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",n.isOpen&&"bg-accent text-accent-foreground"),children:[e.jsx(a.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{className:o?"hidden @[1350px]:inline":"",children:"Settings"})]}),e.jsx(a.IconButton,{tooltip:"Refresh",disabled:$||Q,className:t.cn("h-7 w-7 px-0",o&&"hidden @[1150px]:inline-flex"),onClick:Be,children:e.jsx(Ts,{className:t.cn("h-3.5 w-3.5",{"animate-spin":(Te==null?void 0:Te.isFetching)??Oe})})}),e.jsxs(a.DropdownMenu,{modal:!1,children:[e.jsx(a.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",collisionPadding:8,className:"max-h-[var(--radix-dropdown-menu-content-available-height)] w-56 overflow-y-auto overscroll-contain",children:[(o||(i==null?void 0:i.reset))&&e.jsxs(e.Fragment,{children:[o&&e.jsxs(a.DropdownMenuItem,{disabled:$||Q,onSelect:Be,children:[e.jsx(Ts,{className:"h-3.5 w-3.5"}),"Refresh result"]}),i==null?void 0:i.reset,e.jsx(a.DropdownMenuSeparator,{})]}),e.jsx(a.DropdownMenuLabel,{children:"Export"}),Te?e.jsxs(a.DropdownMenuItem,{disabled:$||Q||!Te.hasDelivery,title:Te.hasDelivery?void 0:"Available once the preview has loaded.",onSelect:()=>ze(Te.readDelivery()),className:"gap-2 text-[13px]",children:[e.jsx(a.Download,{className:"h-3.5 w-3.5"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:re,className:"gap-2 text-[13px]",children:[e.jsx(a.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:Ce,className:"gap-2 text-[13px]",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:ie,className:"gap-2 text-[13px]",children:[e.jsx(a.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]}),e.jsx(a.DropdownMenuSeparator,{}),(i==null?void 0:i.query)&&e.jsxs(e.Fragment,{children:[e.jsx(a.DropdownMenuLabel,{children:"Query"}),i.query,e.jsx(a.DropdownMenuSeparator,{})]}),(o&&(n==null?void 0:n.show)||m||f)&&e.jsxs(e.Fragment,{children:[e.jsx(a.DropdownMenuLabel,{children:"Output"}),o&&(n==null?void 0:n.show)&&e.jsx(a.DropdownMenuCheckboxItem,{checked:n.isOpen,onCheckedChange:()=>n.onToggle(),children:"Settings"}),(m||f)&&e.jsx(a.DropdownMenuCheckboxItem,{checked:!p,onCheckedChange:me=>j(me!==!0),children:"Show raw results"}),e.jsx(a.DropdownMenuSeparator,{})]}),e.jsx(a.DropdownMenuLabel,{children:"Customize"}),!F&&!["table","detailTable","custom"].includes(x.type)&&N&&e.jsx(Mo,{triggerVariant:"menu",className:"w-full"}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),M&&e.jsxs(a.DropdownMenuItem,{onSelect:()=>{var me;return(me=n==null?void 0:n.onOpen)==null?void 0:me.call(n,"style")},className:"gap-2 text-[13px]",children:[e.jsx(Er,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsx(Sa,{onCustomize:()=>L(!0)})]})]}),_e&&e.jsx(a.ExportDialog,{isOpen:!0,onClose:()=>ze(void 0),card:x,frame:u,matrix:_e})]})]}),Ye&&(p?F?e.jsx(It,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Na,{fallbackPreview:e.jsx(It,{}),records:ge,title:x.title,isInspectorOpen:T,onInspectorOpenChange:L})}):e.jsx(It,{}):e.jsxs(a.ResizablePanelGroup,{className:t.cn(g&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(a.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:g&&e.jsx(el,{})}),e.jsx(a.ResizableHandle,{})]}),e.jsxs(a.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":g}),children:[Array.isArray(V==null?void 0:V.records)&&!U&&(m?e.jsx(fo,{data:V.records,card:z,paginationMetadata:ue,onPaginationChange:Ae,onPageSizePreferenceChange:B,onSortChange:Me,isLoading:$||Q}):V.records.length>0?e.jsx(a.TableVisual,{card:x,data:ge,resultColumns:V==null?void 0:V.columns,columnKeyMap:V==null?void 0:V.columnKeyMap,totalsByColumnId:V==null?void 0:V.tableTotalsByColumnId,comparisonMetadata:(Fe=V==null?void 0:V.metadata)==null?void 0:Fe.comparisonMetadata,paginationMetadata:ue,onPaginationChange:Ae,onSortChange:Me,isLoading:$||Q}):null),U&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(rs,{error:U,errorSql:J||x.sql||x.python,onDebugWithAssistant:be,showFeedbackButton:!1})})]})]}))]})}function el(){const s=t.useEditorStore(r=>r.pythonStdOut);if(!s)return null;const n=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function tt({value:s,onCommit:n,type:r="text",placeholder:o,className:i}){const[d,c]=v.useState(s),l=v.useRef(!1);v.useEffect(()=>{c(s)},[s]);const u=()=>{if(l.current){l.current=!1;return}d!==s&&n(d)},x=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(l.current=!0,c(s),m.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:d,onChange:m=>c(m.target.value),onBlur:u,onKeyDown:x,className:i})}function gt({defaultValue:s,label:n,options:r,value:o,onValueChange:i,className:d,icon:c,showPlaceholderLabel:l=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:i,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),l&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),r.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function tl(s,n){return xe.getSlotDefinitionForIndex(s,n)||null}function Yt(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,o,i]=n;return`Tabs ${Number(o)+1}-${Number(i)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function sl(s){return s?Array.isArray(s)?s:[s]:[]}function bs(s){var o,i;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const n=!!((i=s.sql)!=null&&i.trim()),r=je.hasValidCardConfig(s.config);return n||r}function nl({slots:s,cards:n,minInputs:r}){const o=[],i=n.filter(Boolean).length;return r&&i<r&&o.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(d=>{if(!d.required)return;if(typeof d.position=="number"){const u=n[d.position];bs(u)||o.push({type:"missing-required",message:`${Yt(d.position)} ("${d.label}") is required but has no data configured.`});return}const c=d.position.match(/^(\d+)-(\d+)$/);if(c){const[,u,x]=c.map(Number);for(let m=u;m<=x;m+=1){const b=n[m];if(!bs(b)){o.push({type:"missing-required",message:`${Yt(m)} ("${d.label}") is required but has no data configured.`});break}}return}const l=d.position.match(/^(\d+)\+$/);if(l){const u=Number(l[1]);if(n.length<=u){o.push({type:"missing-required",message:`${Yt(u)} ("${d.label}") is required but has no data configured.`});return}for(let x=u;x<n.length;x+=1){const m=n[x];if(!bs(m)){o.push({type:"missing-required",message:`${Yt(x)} ("${d.label}") is required but has no data configured.`});break}}}}),n.forEach((d,c)=>{if(!d)return;const l=tl(s,c);if(!l||!l.expectedType)return;const u=sl(l.expectedType);u.length!==0&&(u.includes(d.type)||o.push({type:"wrong-type",message:`${Yt(c)} ("${l.label}") expects ${u.join(", ")}, but is configured as ${d.type}.`}))})),o}const al={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Ta(){var L,k,R;const s=t.useEditorStore(y=>y.card.customCardPreferences),{data:n}=a.usePluginQuery(),r=(n==null?void 0:n.plugins)||[],o=t.useEditorStore(y=>y.card),i=t.useEditorStore(y=>y.frame),{setCustomCardPreferences:d}=t.useEditorActions(),c=v.useMemo(()=>xe.findCustomVisualConfigCard(i,o),[i,o]),l=c==null?void 0:c.customCardPreferences,{components:u,manifest:x}=a.useCustomVisual((l==null?void 0:l.url)||(s==null?void 0:s.url)||""),m=(L=x==null?void 0:x.visuals)==null?void 0:L.find(y=>y.name===((l==null?void 0:l.componentName)||(s==null?void 0:s.componentName))),h=xe.resolveMultiInputType(c||o,m)==="multiple",p=!!c&&c.id===o.id,j=(m==null?void 0:m.minInputs)??((k=c==null?void 0:c.customCardPreferences)==null?void 0:k.minInputs),N=(m==null?void 0:m.maxInputs)??((R=c==null?void 0:c.customCardPreferences)==null?void 0:R.maxInputs),f=v.useMemo(()=>xe.getCustomVisualInputCards({frame:i,configCard:c||o,isMultiInputVisual:h}),[i,c,o,h]),g=v.useMemo(()=>xe.buildSlotOrderedCards(f),[f]),D=v.useMemo(()=>g.map((y,_)=>{if(!y)return null;const O=xe.getSlotIndexForCard(y,_),P=xe.getEffectiveCardTypeForSlot(y,O,m==null?void 0:m.slots);return{...y,type:P??y.type}}),[g,m==null?void 0:m.slots]),I=v.useMemo(()=>nl({slots:m==null?void 0:m.slots,cards:D,minInputs:j}),[m==null?void 0:m.slots,D,j]),w=v.useMemo(()=>{const y=f.findIndex(_=>(_==null?void 0:_.id)===o.id);return y<0?-1:xe.getSlotIndexForCard(o,y)},[f,o]);function S(y){if(typeof y=="number")return`Tab ${y+1}`;const _=y.match(/^(\d+)-(\d+)$/);if(_){const[,P,B]=_;return`Tabs ${Number(P)+1}-${Number(B)+1}`}const O=y.match(/^(\d+)\+$/);return O?`Tabs ${Number(O[1])+1}+`:`Tab ${y}`}function M(y){return y?(Array.isArray(y)?y:[y]).join(", "):null}function A(y,_,O=[],P="",B,Y,q){const z=F({key:_,defaultValue:P,settingsValue:Y,sourceCard:q});return y==="input"?e.jsx(tt,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:V=>{E({key:_,value:V,settingsField:B,settingsValue:Y,sourceCard:q})}},_):y==="select"?e.jsx(gt,{className:"h-8 w-full",label:"",options:O,value:String(z!==void 0?z:P??""),onValueChange:V=>{E({key:_,value:V,settingsField:B,settingsValue:Y,sourceCard:q})}}):null}function F({key:y,defaultValue:_,settingsValue:O,sourceCard:P}){const B=O==null?void 0:O[y];return B!==void 0?B:y==="title"&&(P==null?void 0:P.title)!==void 0?P.title:y==="description"&&(P==null?void 0:P.description)!==void 0?P.description:_}function E({key:y,value:_,settingsField:O,settingsValue:P,sourceCard:B}){const Y={...P||{}},q=y==="title"&&(B==null?void 0:B.title)!==void 0,z=y==="description"&&(B==null?void 0:B.description)!==void 0;q&&_===String((B==null?void 0:B.title)??"")||z&&_===String((B==null?void 0:B.description)??"")?delete Y[y]:Y[y]=_,d({...s||{},[O]:Y})}function C({settingsSchema:y,settingsField:_,settingsValue:O,sourceCard:P,headerLabel:B}){const Y=Object.entries(y||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),Y.map(([q,z])=>{var V;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}),((V=z.docs)==null?void 0:V.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})})]})})]}),A(z.ui,q,z.options,z.defaultValue,_,O,P)]},q)})]})}function T(){return e.jsxs(e.Fragment,{children:[h&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:m!=null&&m.slots&&m.slots.length>0?e.jsx("div",{className:"space-y-3",children:m.slots.map((y,_)=>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:S(y.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:y.label})]}),y.description&&e.jsx("p",{className:"text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[M(y.expectedType)&&e.jsxs("span",{children:["Expected: ",M(y.expectedType)]}),y.required&&e.jsx("span",{children:"Required"})]})]},`${y.label}-${_}`))}):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."}),(j||N)&&e.jsxs("p",{children:[j?`Min ${j} tabs`:"",j&&N?" • ":"",N?`Max ${N} tabs`:""]})]})})]}),h&&I.length>0&&e.jsx(a.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(a.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:I.map((y,_)=>e.jsx("li",{children:y.message},`${y.type}-${_}`))})})}),m&&!h&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:C({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),m&&h&&(m.settings||m.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[p&&m.settings&&e.jsx("div",{className:"px-2",children:C({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:c||o,headerLabel:"Global Settings"})}),m.slotSettings&&e.jsx("div",{className:"px-2",children:C({settingsSchema:m.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const y=o.tabTitle||o.title,_=w>=0?w:0,O=p?"Slot 0":`Slot ${_}`;return y?`${O}: ${y} Settings`:`${O} Settings`})()})})]})]})}return e.jsxs(a.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(a.AccordionItem,{value:"plugin-settings",children:[e.jsx(a.AccordionTrigger,{children:"Plugin"}),e.jsx(a.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!h||p)&&e.jsx(gt,{icon:e.jsx(na,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(l==null?void 0:l.url)||"",onValueChange:y=>d({...s||{url:"",componentName:""},url:y})}),h&&!p&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!h||p)&&e.jsx(e.Fragment,{children:u&&e.jsx(gt,{icon:e.jsx(br,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.map(y=>({value:y.name,label:y.name})))||[],value:s.componentName||"",onValueChange:y=>{var P;const _=(P=x==null?void 0:x.visuals)==null?void 0:P.find(B=>B.name===y),O=u==null?void 0:u.find(B=>B.name===y);d({...s,componentName:y,visualType:(_==null?void 0:_.visualType)||(O==null?void 0:O.type)||"single",minInputs:_==null?void 0:_.minInputs,maxInputs:_==null?void 0:_.maxInputs,pluginChartType:_==null?void 0:_.chartType})}})})]})})]}),((l==null?void 0:l.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(a.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(a.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(m==null?void 0:m.name)||"Settings"}),(m==null?void 0:m.docs)&&e.jsxs(a.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,onClick:y=>y.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(a.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:[m.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:m.docs.description}),m.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(a.Markdown,{remarkPlugins:[a.remarkGfm],components:al,children:m.docs.dataSchema})})]}),(()=>{var _;const y=(_=m.docs)==null?void 0:_.useCases;return!y||y.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:y.map((O,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:O})]},P))})]})})()]})})]})]})}),e.jsx(a.AccordionContent,{children:T()})]})]})}function as(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Ea(s,n,r){if(!n||n==="auto")return{type:"auto"};if(n==="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:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0&&!(n==="currency"&&(r!=null&&r.preserveSparseCurrency))?Ia(o,as(n)):o}function rl(s,n){return{...s,decimalPlaces:void 0,minimumFractionDigits:n,maximumFractionDigits:n}}function Vn(s){const n=s.decimalPlaces;return{...s,currency:void 0,decimalPlaces:void 0,minimumFractionDigits:s.minimumFractionDigits??n,maximumFractionDigits:s.maximumFractionDigits??n}}function ol(s,n){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}:Ea(s,r,n)}function Ia(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Rt="__report_default__",ll=["auto","number","currency","percent","scientific","date","duration"],_n=[{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"}],Yn=[{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"}],js=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],il=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],cl=s=>s.charAt(0).toUpperCase()+s.slice(1);function dl(s,n){try{return ea.resolveCurrencyFractionDigits(s,n).maximumFractionDigits??as("currency")}catch{return as("currency")}}function Ut({formatOptions:s={},onFormatOptionsChange:n,showTitle:r=!0,title:o="NUMBER FORMAT",maxDecimalPlaces:i=10,reportDefaults:d,showAutoFormat:c=!0,showLocaleOverride:l=!0}){var T,L;const u=s.type||"auto",x=ol(s,{preserveSparseCurrency:!!d}),m=k=>{k.stopPropagation()},b=(k,R)=>{n({...x,[k]:R})},h=x.decimalPlaces??x.maximumFractionDigits??x.minimumFractionDigits,p=s.currency??(d==null?void 0:d.currency)??"USD",j=s.locale??(d==null?void 0:d.locale)??"en-US",N=u==="currency"?dl(j,p):void 0,f=h??N??as(u),g=u==="currency"&&x.decimalPlaces===void 0&&x.minimumFractionDigits===void 0&&x.maximumFractionDigits===void 0,[D,I]=v.useState(()=>String(f)),[w,S]=v.useState(()=>x.multiplyBy!==void 0?String(x.multiplyBy):""),M=k=>{const R=Ea(s,k,{preserveSparseCurrency:!!d});n(d&&k==="currency"&&s.type!=="currency"?Vn(R):R)},A=k=>d&&u==="currency"?rl(x,k):Ia(x,k),F=((T=_n.find(k=>k.value===(d==null?void 0:d.currency)))==null?void 0:T.label)??(d==null?void 0:d.currency),E=((L=Yn.find(k=>k.value===(d==null?void 0:d.locale)))==null?void 0:L.label)??(d==null?void 0:d.locale),C=u==="number"||u==="currency"||u==="percent"||u==="scientific";return v.useEffect(()=>{I(String(f))},[f]),v.useEffect(()=>{S(x.multiplyBy!==void 0?String(x.multiplyBy):"")},[x.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:u,onValueChange:k=>M(k),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:ll.filter(k=>c||k!=="auto").map(k=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:k==="auto"?"Auto (Default)":cl(k)},k))})]})]}),u!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(u)&&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:i,placeholder:"0",value:D,onClick:m,onPointerDown:m,onKeyDown:m,onChange:k=>{const R=k.target.value.replace(/[^\d]/g,"");I(R),R!==""&&n(A(Math.max(0,Math.min(i,parseInt(R,10)))))},onBlur:()=>{if(D!=="")return;const k=f;I(String(k)),n(A(k))},className:"h-8 text-xs"}),g&&e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"Currency default"})]})]}),u==="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||(d?Rt:"USD"),onValueChange:k=>{if(k===Rt){n(Vn(x));return}b("currency",k)},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:[d&&e.jsxs(t.SelectItem,{value:Rt,className:"text-xs",children:["Report default — ",F]}),_n.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))]})]})]})}),["number","currency"].includes(u)&&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:k=>k.stopPropagation(),onCheckedChange:k=>b("useSuffix",k)})]}),l&&u!=="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||(d&&C?Rt:"en-US"),onValueChange:k=>b("locale",k===Rt?void 0:k),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:[d&&C&&e.jsxs(t.SelectItem,{value:Rt,className:"text-xs",children:["Report default — ",E]}),Yn.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))]})]})]}),u==="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:k=>b("prefix",k.target.value),className:"h-8 text-xs"})})]}),u==="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:k=>b("suffix",k.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(u)&&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:k=>k.stopPropagation(),onCheckedChange:k=>b("negativeInParentheses",k)})]}),u==="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:w,onClick:m,onPointerDown:m,onKeyDown:m,onChange:k=>{const R=k.target.value.replace(/[^0-9.]/g,"");S(R),b("multiplyBy",R?parseFloat(R):void 0)},className:"h-8 text-xs"})})]}),u==="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:k=>b("dateFormat",k.target.value),className:"h-8 text-xs"})})]}),u==="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:k=>b("durationInputUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationDisplayStyle",k),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:il.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationSmallestUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationLargestUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))})]})]})]})]})]})}function zn({colorRanges:s,setColorRanges:n}){const r={start:-1/0,end:100,color:""};function o(c,l,u){const x=[...s];x[c]={...x[c],[l]:u},n(x)}function i(c){const l=[...s];l.splice(c,1),n(l)}function d(){n([...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:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(a.Plus,{className:"size-3"})})]}),s.map((c,l)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:u=>o(l,"start",u.target.value),value:c.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:c.end,onChange:u=>o(l,"end",u.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:u=>o(l,"color",u.target.value),value:c.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:je.colors.green[600]}),e.jsx("option",{children:je.colors.red[500]}),e.jsx("option",{children:je.colors.yellow[400]}),e.jsx("option",{children:je.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>i(l),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(le.X,{className:"size-3"})})]},l))]})}const ul=[];function ml(s){return(s==null?void 0:s.enabled)===!1||typeof(s==null?void 0:s.enabled)=="string"&&s.enabled.trim().toLowerCase()==="false"}function xl(s){var r;const n=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(n,{preserveOmittedProperties:!0})||{type:"number",minimumFractionDigits:0,maximumFractionDigits:0}}function qn(s){return{enabled:!0,colorRanges:s==null?void 0:s.colorRanges}}function hl(){var h,p,j,N;const s=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.actions.setCardPreferences),r=t.useEditorStore(f=>{var g,D;return((D=(g=f.card.preferences)==null?void 0:g.formatNumber)==null?void 0:D.colorRanges)??ul}),o=t.useEditorStore(f=>f.actions.setColorRanges),i=a.useResolvedValueFormatLocale()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale,d=a.useResolvedDefaultCurrency()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,c=!a.isSqlBackedKpi(s)&&je.hasValidCardConfig(s.config),l=xl(s.preferences),u=!!t.fromPersistedKpiFormatOptions((p=(h=s.preferences)==null?void 0:h.kpiVisualOptions)==null?void 0:p.formatOptions),x=!ml((j=s.preferences)==null?void 0:j.formatNumber)&&(u||!!((N=s.preferences)!=null&&N.formatNumber)),m=f=>{const g=t.useEditorStore.getState().card.preferences??{};n({...g,formatNumber:qn(g.formatNumber),kpiVisualOptions:{...g.kpiVisualOptions,formatOptions:f}})},b=f=>{const g=t.useEditorStore.getState().card.preferences??{};if(f){n({...g,formatNumber:qn(g.formatNumber),kpiVisualOptions:{...g.kpiVisualOptions,formatOptions:l}});return}n({...g,formatNumber:{...g.formatNumber,enabled:!1}})};return c?e.jsx(zn,{colorRanges:r,setColorRanges:o}):e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(a.Checkbox,{id:"query-kpi-format-number",checked:x,onCheckedChange:f=>b(f===!0)}),e.jsx(t.Label,{htmlFor:"query-kpi-format-number",className:"text-xs",children:"Format number"})]}),x&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Ut,{formatOptions:l,onFormatOptionsChange:m,showTitle:!1,showAutoFormat:!1,reportDefaults:{currency:d,locale:i}}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(zn,{colorRanges:r,setColorRanges:o})]})]})}const pl={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 Da(s){return pl[s]}function fl({chartType:s,showDocsLink:n=!0}){const r=Da(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,i)=>e.jsxs("tr",{className:i<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}),n&&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(a.ExternalLink,{className:"h-3 w-3"})]})]}):null}function gl({chartType:s}){return Da(s)?e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.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(a.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(fl,{chartType:s})})]}):null}function Os({chartType:s,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-medium",children:n}),e.jsx(gl,{chartType:s})]})}function bl(){const s=t.useEditorStore(i=>!je.hasValidCardConfig(i.card.config)),n=t.useEditorStore(i=>{var d,c;return((c=(d=i.card.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:c.queryComparisonPolarity)??Tn.DEFAULT_METRIC_COMPARISON_POLARITY}),r=t.useEditorStore(i=>i.actions.setCardPreferences),o=i=>{const d=t.useEditorStore.getState().card.preferences??{},c={...d.kpiVisualOptions,queryComparisonPolarity:i===Tn.DEFAULT_METRIC_COMPARISON_POLARITY?void 0:i};r({...d,kpiVisualOptions:c})};return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Os,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(hl,{})}),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:n,onValueChange:i=>o(i),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 $n({children:s,summary:n,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:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function jl(){const[s,n]=v.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:i}=t.useEditorStore(x=>x.actions),d=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var m;return(m=x.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),v.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function c(x,m){var b,h;m?r!=null&&r.onClickFilter&&((b=r==null?void 0:r.onClickFilter)==null?void 0:b.length)>0?i({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):i({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...r,onClickFilter:(h=r==null?void 0:r.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==x)}),n(p=>{const j=[...p];return j[x]=!1,j}))}function l(x,m){var h;const b=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===x?{...p,expression:m.target.value}:p);i({...r,onClickFilter:b})}function u(x){var m,b,h,p;if(s!=null&&s[x]||(b=(m=r==null?void 0:r.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===x))!=null&&b.expression)return e.jsx(t.Input,{value:(p=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===x))==null?void 0:p.expression,onChange:j=>l(x,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((x,m)=>{var b,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(a.Checkbox,{checked:!!((b=r==null?void 0:r.onClickFilter)!=null&&b.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(a.Pencil,{onClick:()=>{n(p=>{const j=[...p];return j[m]=!p[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},x)})})}const vl=[{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"}],yl=["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"],Cl=yl.map(s=>({label:s,value:s}));function Nl(){var u,x,m,b,h,p,j,N,f,g,D,I,w,S,M,A,F,E;const s=t.useEditorStore(C=>C.card),n=(x=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,o]=v.useState(((b=(m=s==null?void 0:s.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:b.customTopoJsonUrl)||""),{setCardPreferences:i}=t.useEditorActions(),{data:d}=a.useTopoJson(s),c=Object.keys((d==null?void 0:d.objects)||{}).map(C=>({label:C,value:C}))||[],l=[{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(Os,{chartType:"map"}),e.jsx($n,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(gt,{className:"h-9",options:l,onValueChange:C=>{console.log("value",C),i({...s.preferences,mapVisualOptions:{topoJsonUrl:C}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:C=>{o(C.target.value)},onBlur:()=>{var C;console.log("onBlur",r),i({...s.preferences,mapVisualOptions:{...(C=s.preferences)==null?void 0:C.mapVisualOptions,customTopoJsonUrl:r}})},value:r,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(gt,{className:"h-9",options:c,value:((p=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,objectKey:C}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(gt,{className:"h-9",options:vl,value:((N=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:N.projection)||"",label:"Projection",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projection:C}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(gt,{className:"h-9",options:Cl,value:((g=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,colorScale:C}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx($n,{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:((I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionScale)||1,onChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(C.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(S=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:M[0])||0,onChange:C=>{var T,L,k,R;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(C.target.value),((R=(k=(L=s.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:R[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((E=(F=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:E[1])||0,onChange:C=>{var T,L,k,R;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((R=(k=(L=s.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:R[0])||0,Number(C.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(jl,{})]})}function Xe({label:s,value:n,options:r,onChange:o,disabled:i}){const d=v.useId();return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx(t.Label,{htmlFor:d,className:"text-xs",children:s}),e.jsxs(t.Select,{value:n,onValueChange:o,disabled:i,children:[e.jsx(t.SelectTrigger,{id:d,"aria-label":s,className:"h-8 min-w-0 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:r.map(c=>e.jsx(t.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]})}function Et({label:s,value:n,onChange:r,type:o="text",min:i,max:d}){const c=v.useId();return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx(t.Label,{htmlFor:c,className:"text-xs",children:s}),e.jsx(t.Input,{id:c,className:"h-8 text-xs",type:o,min:i,max:d,value:n,onChange:l=>r(l.target.value)})]})}function Bs({label:s,checked:n,onChange:r}){const o=v.useId();return e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 py-1",children:[e.jsx(t.Label,{className:"text-xs",htmlFor:o,children:s}),e.jsx(t.Switch,{id:o,size:"xs",checked:n,onCheckedChange:r})]})}function Sl({label:s,disabled:n,onClick:r,children:o}){return e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0","aria-label":s,title:s,disabled:n,onClick:r,children:o})}function Kn({label:s,value:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Bs,{label:s,checked:n.visible,onChange:o=>r({...n,visible:o})}),e.jsx(Xe,{label:`${s} position`,value:n.position,options:[{value:"before",label:"Before"},{value:"after",label:"After"}],onChange:o=>r({...n,position:o})}),e.jsx(Et,{label:`${s} label`,value:n.label??"",onChange:o=>r({...n,label:o||void 0})})]})}function Es({value:s,onChange:n,cardType:r,showTitle:o=!0,title:i="NUMBER FORMAT",showLocaleOverride:d=!0}){const c=a.supportsLiveNumericPresentation(r),l=a.useResolvedValueFormatLocale(),u=a.useResolvedDefaultCurrency(),x=t.toTFormatOptions(xr.fromSemanticFormat(s,{preserveOmittedProperties:!0}),{preserveOmittedProperties:!0})||{},m=b=>{const h=t.fromTFormatOptions(b,{preserveOmittedProperties:!0});if(!d&&h&&"locale"in h){const{locale:p,...j}=h;n(j)}else n(h)};return e.jsx(Ut,{formatOptions:x,onFormatOptionsChange:m,showTitle:o,title:i,showLocaleOverride:d,reportDefaults:c?{currency:u??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,locale:l??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale}:void 0})}function wl(s){switch(s==null?void 0:s.type){case"date":case"datetime":return{...s,type:"date"};case"number":case"currency":case"percent":case"percentage":case"scientific":case"duration":case"string":return s;default:return}}function ka(s,n,r){const o=(r==null?void 0:r.length)&&r.every((i,d)=>{var c;return((c=s[d])==null?void 0:c.id)===i.levelId&&i.member.kind==="value"});return new Map([...n!=null&&n.length?[[at.matrixPathKey(n),n]]:[],...o?[[at.matrixPathKey(r),r]]:[]])}function Tl({axis:s,level:n,value:r,change:o,scopeSelection:i}){const d=r.spec.sorts.find(h=>h.axis===s&&h.levelId===n.id&&h.scope.kind==="level"),c=r.spec.rankings.find(h=>h.axis===s&&h.levelId===n.id),l=s==="rows"?"columns":"rows",u=ka(r.spec[l],c==null?void 0:c.oppositePath,l==="rows"?i==null?void 0:i.rowPath:i==null?void 0:i.columnPath),x=r.spec.measures.map(h=>({value:h.id,label:bt.getMatrixMeasureLabel(h,r.presentation)})),m=h=>{const p=r.spec.sorts.filter(j=>!(j.axis===s&&j.levelId===n.id&&j.scope.kind==="level"));o({kind:"sorts",sorts:h?[...p,{axis:s,levelId:n.id,scope:{kind:"level"},target:{kind:"member"},direction:"asc",nulls:"last",...d,...h}]:p})},b=h=>{if(h&&!r.spec.measures.length)return;const p=r.spec.rankings.filter(j=>!(j.axis===s&&j.levelId===n.id));o({kind:"rankings",rankings:h?[...p,{id:je.v4(),axis:s,levelId:n.id,direction:"top",count:10,measureId:r.spec.measures[0].id,oppositePath:[],others:!1,...c,...h}]:p})};return e.jsxs("div",{className:"space-y-2 border-t pt-2",children:[e.jsx(Xe,{label:"Sort by",value:d?d.target.kind==="member"?"member":d.target.measureId:"default",options:[{value:"default",label:"Default"},{value:"member",label:"Member"},...x],onChange:h=>m(h==="default"?void 0:{target:h==="member"?{kind:"member"}:{kind:"measure",measureId:h,oppositePath:[]}})}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Sort direction",value:d.direction,options:[{value:"asc",label:"Ascending"},{value:"desc",label:"Descending"}],onChange:h=>m({direction:h})}),e.jsx(Xe,{label:"Null order",value:d.nulls,options:[{value:"first",label:"First"},{value:"last",label:"Last"}],onChange:h=>m({nulls:h})})]}),e.jsx(Xe,{label:"Ranking",disabled:!r.spec.measures.length,value:(c==null?void 0:c.direction)??"none",options:[{value:"none",label:"None"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"}],onChange:h=>b(h==="none"?void 0:{direction:h})}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Ranking count",type:"number",min:1,value:c.count,onChange:h=>{h&&Number.isSafeInteger(Number(h))&&Number(h)>0&&b({count:Number(h)})}}),e.jsx(Xe,{label:"Rank by measure",value:c.measureId,options:x,onChange:h=>b({measureId:h})}),e.jsx(Bs,{label:"Include Others",checked:c.others,onChange:h=>b({others:h})}),e.jsx(Xe,{label:"Ranking context",value:c.oppositePath.length?at.matrixPathKey(c.oppositePath):"total",options:[{value:"total",label:"Grand total"},...[...u].map(([h,p])=>({value:h,label:p.map((j,N)=>ta.matrixMemberLabel(p.slice(0,N+1))).join(" / ")}))],onChange:h=>b({oppositePath:h==="total"?[]:[...u.get(h)]})})]})]})}function El({value:s,change:n,scopeSelection:r}){var f,g,D;const[o,i]=v.useState(((f=s.presentation.conditionalFormatting)==null?void 0:f.rules)??[]),[d,c]=v.useState(s.spec),[l,u]=v.useState(""),x=JSON.stringify(s.presentation.conditionalFormatting??{version:1,rules:[]}),m=v.useRef(x);x!==m.current&&(m.current=x,JSON.stringify(at.matrixConditionalFormattingSchema.safeParse({version:1,rules:o}).data??null)!==x&&i(((g=s.presentation.conditionalFormatting)==null?void 0:g.rules)??[]));const b=o.filter(a.isRuleReadyToApply);v.useEffect(()=>{const I=at.matrixConditionalFormattingSchema.safeParse({version:1,rules:b});if(!I.success)return;const w=JSON.stringify(I.data);w!==m.current&&(m.current=w,n({kind:"presentation",presentation:{...s.presentation,conditionalFormatting:I.data}}))},[b,n,s.presentation]);const h=o.find(I=>!a.isRuleReadyToApply(I)),p=at.matrixConditionalFormattingSchema.safeParse({version:1,rules:b}),j=h?`${h.name||"the new rule"} is incomplete`:p.success?"":((D=p.error.issues[0])==null?void 0:D.message)??"the rule is incomplete";if(d!==s.spec){const I=[],w=Dt.retainMatrixConditionalFormatting(d,s.spec,{version:1,rules:o},I);c(s.spec),I.length&&(i((w==null?void 0:w.rules)??[]),u("Removed rules whose measure, level or member path changed."))}const N=s.spec.measures[0];return N?e.jsxs("div",{className:"min-w-0 space-y-2",children:[l&&e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:l}),j&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Not applied yet: ",j]}),e.jsx(a.DataTableConditionalFormattingSettings,{columnId:N.id,availableColumns:s.spec.measures.map(I=>({value:I.id,label:bt.getMatrixMeasureLabel(I,s.presentation)})),conditionalRules:o,onConditionalRulesChange:i,capabilities:{ruleKinds:["comparison","colorScale","dataBar"],automaticRanges:!1,separateApplyTargets:!0,targetScope:{defaultRowRoles:["member"]}}}),o.map((I,w)=>{var C;const S=I.target.matrix,M=(S==null?void 0:S.axis)==="columns"?"rows":"columns",A=M==="rows"?r==null?void 0:r.rowPath:r==null?void 0:r.columnPath,F=ka(s.spec[M],S==null?void 0:S.oppositePath,A),E=T=>i(L=>L.map(k=>k.id===I.id?{...k,target:{...k.target,matrix:T}}:k));return e.jsxs("fieldset",{className:"min-w-0 space-y-2 border-t pt-2",children:[e.jsxs("legend",{className:"text-xs font-medium",children:[I.name||`Rule ${w+1}`," scope"]}),e.jsx(Xe,{label:"Cell role",value:((C=I.target.rowRoles)==null?void 0:C.length)===1?I.target.rowRoles[0]:"all",options:[{value:"all",label:"All roles"},{value:"member",label:"Detail"},{value:"subtotal",label:"Subtotal"},{value:"grand_total",label:"Grand total"},{value:"others",label:"Others"}],onChange:T=>i(L=>L.map(k=>{if(k.id!==I.id)return k;const{tableParts:R,includeTotals:y,includeSubtotals:_,...O}=k.target;return{...k,target:{...O,rowRoles:T==="all"?void 0:[T]}}}))}),e.jsx(Xe,{label:"Rule axis",value:(S==null?void 0:S.axis)??"all",options:[{value:"all",label:"All cells"},{value:"rows",label:"Rows"},{value:"columns",label:"Columns"}],onChange:T=>E(T==="all"?void 0:{axis:T})}),S&&e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Rule level",value:S.levelId??"all",options:[{value:"all",label:"All levels"},...s.spec[S.axis].map(T=>({value:T.id,label:bt.getMatrixLevelLabel(T,s.presentation)}))],onChange:T=>E({...S,levelId:T==="all"?void 0:T})}),e.jsx(Xe,{label:"Opposite members",value:S.oppositePath===void 0?"all":S.oppositePath.length?at.matrixPathKey(S.oppositePath):"total",options:[{value:"all",label:"All members"},{value:"total",label:"Grand total"},...[...F].map(([T,L])=>({value:T,label:L.map((k,R)=>ta.matrixMemberLabel(L.slice(0,R+1))).join(" / ")}))],onChange:T=>E({...S,oppositePath:T==="all"?void 0:T==="total"?[]:[...F.get(T)]})})]})]},I.id)})]}):e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"No metrics available"})}function Il({section:s,value:n,availableFields:r,bindings:o,scopeSelection:i,onChange:d}){const[c,l]=v.useState([]),[u,x]=v.useState(""),m=N=>je.matrixAuthoringDataType(N,n.spec.source,r),b=N=>{try{const f=Dt.updateMatrixConfig(n,N,o,m,!0);x(""),l(f.notices),d(f.config,f.notices,f.removedBindings,f.bindings)}catch(f){x(f instanceof Error?f.message:"Invalid Matrix settings.")}},h=N=>b({kind:"presentation",presentation:{...n.presentation,...N}}),p=(N,f,g)=>{const D={...n.presentation[N]};if(g===void 0)delete D[f];else{const I=at.semaphorValueFormatSchema.safeParse(g);if(!I.success){x(I.error.message);return}D[f]=I.data}h({[N]:D})},j=(N,f)=>{const g=n.presentation[f][N];return e.jsx(Es,{showLocaleOverride:!1,cardType:"matrixTable",value:wl(g),onChange:D=>p(f,N,D)})};return e.jsxs("aside",{"aria-label":"Matrix authoring",className:"min-w-0 text-foreground",children:[u&&e.jsx("p",{role:"alert",className:"break-words p-3 text-xs text-destructive",children:u}),c.length>0&&e.jsxs("div",{role:"status",className:"border-b p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("strong",{children:"Updated references"}),e.jsx(Sl,{label:"Dismiss cleanup notices",onClick:()=>l([]),children:e.jsx(le.X,{className:"size-3.5"})})]}),e.jsx("ul",{className:"space-y-1",children:c.map((N,f)=>e.jsx("li",{children:N.message},`${N.kind}-${N.id}-${f}`))})]}),s.kind!=="conditional-formatting"&&["rows","columns"].filter(N=>s.kind!=="field"||n.spec[N].some(f=>f.id===s.id)).map(N=>e.jsxs("section",{"aria-label":s.kind==="field"?`Field ${s.id}`:N==="rows"?"Rows":"Columns",className:(s==null?void 0:s.kind)==="field"?"space-y-2":"space-y-2 border-b p-3",children:[(s==null?void 0:s.kind)!=="field"&&e.jsx("h2",{className:"text-xs font-semibold",children:N==="rows"?"Rows":"Columns"}),n.spec[N].filter(f=>s.kind==="field"&&f.id===s.id).map(f=>{const g=bt.getMatrixLevelLabel(f,n.presentation),D=F=>b({kind:"structure",[N]:n.spec[N].map(E=>E.id===f.id?F:E)}),I=m(f.field),w=I==="date"||I==="datetime",S=n.presentation.levelFormats[f.id],M=(S==null?void 0:S.type)==="temporal_bucket"?S:et.AUTOMATIC_TEMPORAL_BUCKET_FORMAT,A=f.grain?et.getTemporalBucketAuthoringSelection(M,f.grain):void 0;return e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"min-w-0":"min-w-0 border-b pb-2",children:[e.jsx("div",{className:"flex min-w-0 items-center justify-between gap-1",children:e.jsx("span",{className:"truncate text-xs font-medium",title:g,children:g})}),e.jsxs("details",{open:(s==null?void 0:s.kind)==="field"?!0:void 0,children:[e.jsxs("summary",{className:`cursor-pointer py-1 text-xs text-muted-foreground ${(s==null?void 0:s.kind)==="field"?"hidden":""}`,children:[g," settings"]}),e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"space-y-2 pt-2":"space-y-2 py-2",children:[e.jsx(Et,{label:"Level label",value:n.presentation.levelLabels[f.id]??"",onChange:F=>{const E={...n.presentation.levelLabels};F?E[f.id]=F:delete E[f.id],h({levelLabels:E})}}),e.jsx(Xe,{label:"Axis",value:N,options:[{value:"rows",label:"Rows"},{value:"columns",label:"Columns"}],onChange:F=>{F!==N&&b(Dt.moveMatrixLevel(n.spec,f.id,F))}}),w&&e.jsx(Xe,{label:"Time grain",value:f.grain??"none",options:[{value:"none",label:"No grouping"},...a.getGranularityOptionsForFieldType(I).map(F=>({value:F,label:F}))],onChange:F=>D({...f,grain:F==="none"?void 0:F})}),f.grain?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Date format",value:A.value,options:et.getTemporalBucketAuthoringOptions(f.grain,M),onChange:F=>p("levelFormats",f.id,F==="auto"?void 0:et.resolveTemporalBucketAuthoringFormat(f.grain,F,A.customPattern))}),A.value==="custom"&&e.jsx(Et,{label:"Date pattern",value:A.customPattern,onChange:F=>{F.trim()&&p("levelFormats",f.id,{type:"temporal_bucket",presentation:{mode:"pattern",pattern:F}})}})]}):j(f.id,"levelFormats"),e.jsx(Kn,{label:"Subtotal",value:n.presentation.totals[N].levels[f.id],onChange:F=>h({totals:{...n.presentation.totals,[N]:{...n.presentation.totals[N],levels:{...n.presentation.totals[N].levels,[f.id]:F}}}})}),e.jsx(Tl,{axis:N,level:f,value:n,change:b,scopeSelection:i})]})]})]},f.id)}),(s==null?void 0:s.kind)!=="field"&&e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer py-1 text-xs text-muted-foreground",children:[N==="rows"?"Row":"Column"," totals and expansion"]}),e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Kn,{label:"Grand total",value:n.presentation.totals[N].grand,onChange:f=>h({totals:{...n.presentation.totals,[N]:{...n.presentation.totals[N],grand:f}}})}),e.jsx(Xe,{label:"Default expanded levels",value:String(Math.min(n.defaultView[N].depth,Math.max(0,n.spec[N].length-1))),options:Array.from({length:Math.max(1,n.spec[N].length)},(f,g)=>({value:String(g),label:g===0?"Collapsed":String(g)})),onChange:f=>b({kind:"defaults",defaultView:{...n.defaultView,[N]:{...n.defaultView[N],depth:Number(f)}}})})]})]})]},N)),s.kind==="field"&&n.spec.measures.some(N=>N.id===s.id)&&e.jsx("section",{"aria-label":"Values",className:"space-y-2",children:n.spec.measures.filter(N=>N.id===s.id).map(N=>{const f=bt.getMatrixMeasureLabel(N,n.presentation);return e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"min-w-0":"min-w-0 border-b pb-2",children:[e.jsx("div",{className:"flex min-w-0 items-center justify-between gap-1",children:e.jsxs("span",{className:"truncate text-xs font-medium",title:f,children:[f,N.kind==="aggregate"?` (${N.aggregate})`:""]})}),e.jsxs("details",{open:(s==null?void 0:s.kind)==="field"?!0:void 0,children:[e.jsxs("summary",{className:`cursor-pointer py-1 text-xs text-muted-foreground ${(s==null?void 0:s.kind)==="field"?"hidden":""}`,children:[f," settings"]}),e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"space-y-2 pt-2":"space-y-2 py-2",children:[e.jsx(Et,{label:"Measure label",value:n.presentation.measureLabels[N.id]??"",onChange:g=>{const D={...n.presentation.measureLabels};g?D[N.id]=g:delete D[N.id],h({measureLabels:D})}}),N.kind==="aggregate"&&e.jsx(Xe,{label:"Aggregation",value:N.aggregate,options:et.getFieldAggregationOptions(m(N.field)).filter(g=>at.matrixAggregateSchema.safeParse(g.value).success).map(({value:g})=>({value:g,label:g})),onChange:g=>b({kind:"structure",measures:n.spec.measures.map(D=>D.id===N.id?{...N,aggregate:at.matrixAggregateSchema.parse(g)}:D)})}),j(N.id,"measureFormats")]})]})]},N.id)})}),s.kind==="table"&&e.jsxs("section",{"aria-label":"Presentation",className:"space-y-2 border-b p-3",children:[e.jsx("h2",{className:"text-xs font-semibold",children:"Presentation"}),e.jsx(Xe,{label:"Row layout",value:n.presentation.layout.kind,options:[{value:"compact",label:"Compact"},{value:"tabular",label:"Tabular"}],onChange:N=>h({layout:N==="compact"?{kind:"compact"}:{kind:"tabular",repeatLabels:!1}})}),n.presentation.layout.kind==="tabular"&&e.jsx(Bs,{label:"Repeat row labels",checked:n.presentation.layout.repeatLabels,onChange:N=>h({layout:{kind:"tabular",repeatLabels:N}})}),e.jsx(Et,{label:"Empty cell text",value:n.presentation.absence.emptyText,onChange:N=>h({absence:{...n.presentation.absence,emptyText:N}})}),e.jsx(Et,{label:"Null cell text",value:n.presentation.absence.nullText,onChange:N=>h({absence:{...n.presentation.absence,nullText:N}})})]}),s.kind==="conditional-formatting"&&e.jsxs("section",{"aria-label":"Conditional formatting",className:"min-w-0 space-y-2 p-3",children:[e.jsx("h2",{className:"text-xs font-semibold",children:"Conditional formatting"}),e.jsx(El,{value:n,change:b,scopeSelection:i})]})]})}function Is({fieldId:s,section:n="table"}){const r=t.useEditorStore(l=>l.card),o=t.useEditorStore(l=>l.actions.updateCard),i=t.useEditorStore(l=>l.matrixSelection),d=a.useMatrixEditorCatalog(r),c=je.readMatrixEditorConfig(r);return c.status==="invalid"?e.jsx("div",{role:"alert",className:"p-3 text-xs text-destructive",children:"Invalid Matrix configuration. Repair or reset the card definition."}):c.status==="absent"?e.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:"No fields selected"}):e.jsx(Il,{value:c.config,section:s?{kind:"field",id:s}:{kind:n},scopeSelection:(i==null?void 0:i.cardId)===r.id?i.coordinate:void 0,bindings:r.controlBindings,availableFields:d.catalog.map(l=>({...l.field,dataType:at.normalizeAnalyticsCatalogDataType(l.resolvedField.dataType)})),onChange:(l,u,x,m)=>{const b=a.applyMatrixEditorResult(r,{config:l,notices:u,bindings:m});o(r.id,b.card)}})}const Dl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function kl(s){return s&&(Dl[s]??s)}function Ma({value:s,onChange:n,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:i=>n({displayMode:i}),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:i=>{if(i.target.value===""){n({precision:void 0});return}const d=Number(i.target.value);Number.isInteger(d)&&d>=0&&d<=6&&n({precision:d})},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:i=>n({indicatorStyle:i}),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:i=>n({position:i}),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:i=>n({showColor:i})})]}),s.showColor!==!1&&e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase","#16a34a"],["decrease","Decrease","#dc2626"],["neutral","No change","#6b7280"]].map(([i,d,c])=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:d}),e.jsx(a.ColorField,{value:kl(o[i]||c),onChange:l=>n({colors:{...o,[i]:l||c}}),defaultValue:c,ariaLabel:`${d} color`,allowEmpty:!1})]},i))}),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:i=>n({conditionalLabel:i})})]}),s.conditionalLabel?e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase"],["decrease","Decrease"],["neutral","No change"]].map(([i,d])=>{var c;return e.jsx(t.Input,{"aria-label":`${d} label`,value:((c=s.conditionalLabels)==null?void 0:c[i])||d,onChange:l=>n({conditionalLabels:{...s.conditionalLabels,[i]:l.target.value}}),className:"h-7 text-xs"},i)})}):e.jsx(t.Input,{"aria-label":"Comparison label",value:s.labelName||"",onChange:i=>n({labelName:i.target.value}),placeholder:"Previous",className:"h-7 text-xs"})]})}function Ml(){var b,h,p,j,N;const s=t.useEditorStore(f=>f.card),{setCardPreferences:n}=t.useEditorActions(),r=a.useEffectiveEditorCardType(),o=((b=s.config)==null?void 0:b.metricColumns)||[],i=o.length===2&&(((h=s.config)==null?void 0:h.groupByColumns)||[]).length===0,d=o.some(f=>{var g;return((g=f.comparison)==null?void 0:g.mode)==="explicit"});if(!a.COMPARISON_PRESENTATION_SUPPORTED_CHART_TYPES.includes(r))return null;const l=((p=s.preferences)==null?void 0:p.comparisonPresentation)||{},u=f=>n({...s.preferences,comparisonPresentation:{...l,...f}}),x=r==="kpi"&&((j=s.preferences)==null?void 0:j.metricPairComparisonEnabled)===!0,m=d||x;return e.jsxs(a.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(a.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(Cr,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(a.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:((N=s.preferences)==null?void 0:N.inheritGlobalComparison)!==!1,onCheckedChange:f=>{const g={...s.preferences};f?delete g.inheritGlobalComparison:g.inheritGlobalComparison=!1,n(g)}})]}),r==="kpi"&&i&&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:x,onCheckedChange:f=>n({...s.preferences,metricPairComparisonEnabled:f})})]}),d&&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:l.showComparison!==!1,onCheckedChange:f=>u({showComparison:f})})]}),m&&e.jsx(Ma,{value:l,onChange:u,showPosition:r==="kpi"&&i})]})]})}function Aa({cardType:s,queryResultColumns:n,focusSection:r,focusRequestId:o}){var V,$,Q;const i=t.useEditorStore(U=>U.card),d=t.useEditorStore(U=>U.queryResultColumns),c=t.useEditorStore(U=>U.queryResultColumnKeyMap),l=t.useEditorStore(U=>{var J;return(J=U.card)==null?void 0:J.preferences}),u=l==null?void 0:l.tablePrefs,x=t.useEditorStore(U=>U.actions.setCardPreferences),m=t.useEditorStore(U=>U.actions.updateTableConditionalFormatting),b=((V=i.config)==null?void 0:V.metricColumns)||[],h=s??i.type,p=n??d,j=i.type===h?i:{...i,type:h},N=a.getTableConditionalFormattingColumnOptions(j,p,c),f=a.getTableOutputColumnOptions(j,p),g=h==="matrixTable"||a.supportsTableConditionalFormatting(h),D=h==="table",I=h==="table",w=(($=N[0])==null?void 0:$.value)||"",S=a.resolveTableConditionalFormatting(a.normalizeConditionalFormatting((Q=l==null?void 0:l.tablePrefs)==null?void 0:Q.conditionalFormatting),a.resolveTableFormattingColumns(j,p,c)),M=a.resolveTablePresentationStyle(u),A=a.isEligibleFlatTableTotalsCard(j),F=a.hasFlatTableTotalsBehavior(j),[E,C]=v.useState("style");v.useEffect(()=>{if(r==="style"){C("style");return}if(r==="columns"&&I){C("columns");return}r==="conditional-formatting"&&g&&C("conditional-formatting")},[I,g,o,r]);const T=b.some(U=>{var J;return((J=U.comparison)==null?void 0:J.mode)==="explicit"}),L=(l==null?void 0:l.comparisonPresentation)||{},k=U=>{x({...l,comparisonPresentation:{...L,...U}})},R=U=>{m({version:1,rules:U})},y=U=>{x({...l,tablePrefs:{...u,density:U}})},_=U=>{x({...l,tablePrefs:{...u,tableStyle:{...u==null?void 0:u.tableStyle,...U}}})},O=U=>{var J;_({totals:{...(J=u==null?void 0:u.tableStyle)==null?void 0:J.totals,...U}})},P=U=>{var J;x({...l,tablePrefs:{...u,tableStyle:{...u==null?void 0:u.tableStyle,totals:{...(J=u==null?void 0:u.tableStyle)==null?void 0:J.totals,enabled:U}}}})},B=(U,J)=>{x({...l,tablePrefs:{...u,columnVisibility:a.setTableColumnVisibility(u==null?void 0:u.columnVisibility,U,J)}})},Y=()=>{x({...l,tablePrefs:{...u,columnVisibility:a.showAllTableColumns()}})},q=()=>{x({...l,tablePrefs:{...u,density:a.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:a.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:a.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:a.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:a.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:A?F:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},z=T?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:U=>k({showComparison:U})})]}),e.jsx(Ma,{value:L,onChange:k})]}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:E,onValueChange:U=>C(U),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),I?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!g,children:"Conditional formatting"})]}),e.jsxs(t.TabsContent,{value:"style",className:"mt-0",children:[e.jsx(a.TablePresentationSettings,{style:M,onDensityChange:y,onStyleChange:_,showFullStyle:D,showBorderStyle:!1,totals:D&&A?{enabled:F,onEnabledChange:P,onStyleChange:O}:void 0,extraSection:z,onReset:D?q:void 0}),h==="matrixTable"&&e.jsx(Is,{section:"table"})]}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:I?e.jsx(a.TableColumnVisibilitySettings,{columns:f,columnVisibility:u==null?void 0:u.columnVisibility,onColumnVisibilityChange:B,onShowAllColumns:Y}):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:h==="matrixTable"?e.jsx(Is,{section:"conditional-formatting"}):g?w?e.jsx(a.DataTableConditionalFormattingSettings,{columnId:w,availableColumns:N,conditionalRules:S.rules,onConditionalRulesChange:R,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 Al(){var i;const s=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:n}=t.useEditorStore(d=>d.actions),r=(i=s==null?void 0:s.textVisualOptions)!=null&&i.isDynamicText?"dynamic":"static";function o(d){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:d==="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 Ll(){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(Al,{}),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 Fl({color:s,onColorChange:n,onClose:r}){const[o,i]=v.useState(0),[d,c]=v.useState(100),[l,u]=v.useState(50),[x,m]=v.useState(s);v.useEffect(()=>{const f=Un(s);if(f){const g=Gn(f.r,f.g,f.b);i(g.h),c(g.s),u(g.l),m(s)}},[s]);const b=f=>{i(f),p(f,d,l)},h=f=>{const g=f.currentTarget.getBoundingClientRect(),D=Math.max(0,Math.min(1,(f.clientX-g.left)/g.width)),I=Math.max(0,Math.min(1,(f.clientY-g.top)/g.height)),w=D*100,S=(1-I)*100;c(w),u(S),p(o,w,S)},p=(f,g,D)=>{const I=Pl(f,g,D),w=Rl(I.r,I.g,I.b);m(w)},j=f=>{if(m(f),/^#[0-9A-Fa-f]{6}$/.test(f)){const g=Un(f);if(g){const D=Gn(g.r,g.g,g.b);i(D.h),c(D.s),u(D.l)}}},N=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:h,onMouseMove:f=>{f.buttons===1&&h(f)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-l}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:f=>b(Number(f.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:x,onChange:f=>j(f.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:x}}),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:N,children:"OK"})]})]})}function Un(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Rl(s,n,r){return"#"+((1<<24)+(s<<16)+(n<<8)+r).toString(16).slice(1)}function Gn(s,n,r){s/=255,n/=255,r/=255;const o=Math.max(s,n,r),i=Math.min(s,n,r);let d=0,c=0;const l=(o+i)/2;if(o!==i){const u=o-i;switch(c=l>.5?u/(2-o-i):u/(o+i),o){case s:d=((n-r)/u+(n<r?6:0))/6;break;case n:d=((r-s)/u+2)/6;break;case r:d=((s-n)/u+4)/6;break}}return{h:Math.round(d*360),s:Math.round(c*100),l:Math.round(l*100)}}function Pl(s,n,r){s/=360,n/=100,r/=100;let o,i,d;if(n===0)o=i=d=r;else{const c=(x,m,b)=>(b<0&&(b+=1),b>1&&(b-=1),b<.16666666666666666?x+(m-x)*6*b:b<.5?m:b<.6666666666666666?x+(m-x)*(.6666666666666666-b)*6:x),l=r<.5?r*(1+n):r+n-r*n,u=2*r-l;o=c(u,l,s+1/3),i=c(u,l,s),d=c(u,l,s-1/3)}return{r:Math.round(o*255),g:Math.round(i*255),b:Math.round(d*255)}}const Ol=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Bl(){var S,M,A,F,E,C,T,L,k,R;const s=t.useEditorStore(y=>y.card),n=t.useEditorStore(y=>{var _;return(_=y.card)==null?void 0:_.preferences}),r=a.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:i}=t.useEditorActions(),d=v.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:c}=a.useEditorCardQuery(d),[l,u]=v.useState({}),[x,m]=v.useState(null),[b,h]=v.useState(null),p=v.useMemo(()=>{var P,B,Y,q,z,V,$;if(!(c!=null&&c.records)||c.records.length===0)return[];const y=r==="stackedBar"||r==="stackedLine",_=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",O=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((y||_)&&O){if(c.pivotSchema&&Array.isArray(c.pivotSchema)){const Q=new Set;return c.pivotSchema.forEach(U=>{U.alias&&Q.add(U.alias)}),Array.from(Q)}if(c.records.length>0){const Q=c.records[0],U=Object.keys(Q),J=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(ue=>{J.add(ue.label||ue.name),J.add(ue.alias||ue.name)});const W=new Set;return(Y=s==null?void 0:s.config)!=null&&Y.metricColumns&&s.config.metricColumns.forEach(ue=>{const fe=ue.alias||ue.name;W.add(fe),W.add(`${fe}_count`),W.add(`${fe}_sum`),W.add(`${fe}_avg`),W.add(`${fe}_min`),W.add(`${fe}_max`);const be=ue.entityName||ue.qualifiedEntityName;be&&(W.add(`${be}_${fe}`),W.add(`${be}_${fe}_count`))}),U.filter(ue=>!J.has(ue)&&!W.has(ue))}}if((_||y)&&!O&&((z=(q=s==null?void 0:s.config)==null?void 0:q.metricColumns)!=null&&z.length))return s.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if(($=(V=s==null?void 0:s.config)==null?void 0:V.groupByColumns)!=null&&$.length){const Q=s.config.groupByColumns[0],U=Q.label||Q.name,J=new Set;return c.records.forEach(W=>{const ee=W[U];ee!=null&&J.add(String(ee))}),Array.from(J)}return[]},[c,(S=s==null?void 0:s.config)==null?void 0:S.groupByColumns,(M=s==null?void 0:s.config)==null?void 0:M.pivotByColumns,(A=s==null?void 0:s.config)==null?void 0:A.metricColumns,r]),j=v.useMemo(()=>a.getDefaultChartColors(),[]);v.useEffect(()=>{const y={};p.forEach((_,O)=>{y[_]=a.getColorForValue(_,O,n==null?void 0:n.colorConfig)}),u(y)},[p,n==null?void 0:n.colorConfig,j]);const N=(y,_)=>{const O={...l,[y]:_};u(O);const P={...n||{},colorConfig:{segments:O}};o(P);const B={...s,preferences:P};i(B)},f=(y,_)=>{var z;const O=j[_%j.length],{[y]:P,...B}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},Y={...n||{},colorConfig:{segments:B}};o(Y);const q={...s,preferences:Y};i(q),u(V=>({...V,[y]:O}))};if(!p.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((E=(F=s==null?void 0:s.config)==null?void 0:F.groupByColumns)==null?void 0:E.length)||((T=(C=s==null?void 0:s.config)==null?void 0:C.pivotByColumns)==null?void 0:T.length):(k=(L=s==null?void 0:s.config)==null?void 0:L.groupByColumns)==null?void 0:k.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const I=()=>{const y={...n||{},colorConfig:{segments:{}}};o(y);const _={...s,preferences:y};i(_);const O={};p.forEach((P,B)=>{O[P]=a.getColorForValue(P,B,void 0)}),u(O)},w=Object.keys(((R=n==null?void 0:n.colorConfig)==null?void 0:R.segments)||{}).length>0;return e.jsxs(a.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(a.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(hr.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(a.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:w&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:I,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:p.map((y,_)=>{const O=a.isDefaultColor(l[y],_),P=!O;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===y,onOpenChange:B=>m(B?y: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:l[y]}})}),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:j.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",l[y]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{N(y,B),m(null)},children:[Y===_%j.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:Ol.map((B,Y)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",l[y]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{N(y,B),m(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:()=>{h({value:y,color:l[y]}),m(null)},children:"Custom color"}),!O&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{f(y,_),m(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:y}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},y)})}),b&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>h(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Fl,{color:b.color,onColorChange:y=>{N(b.value,y),h(null)},onClose:()=>h(null)})})]})]})})]})}function lt({value:s,onSave:n,placeholder:r="",type:o="text",className:i=""}){const[d,c]=v.useState(s??""),[l,u]=v.useState(!1);v.useEffect(()=>{c(s??"")},[s]);const x=()=>{n(d),u(!1)},m=()=>{c(s??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:l?d:s??"",onChange:b=>{c(b.target.value),u(!0)},onFocus:()=>u(!0),onClick:b=>b.stopPropagation(),className:"h-8 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.stopPropagation(),b.key==="Enter"&&l&&d!==s?x():b.key==="Escape"&&m()},"aria-label":r||"Edit field"}),l&&d!==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:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(le.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function vs({axis:s,label:n,type:r,config:o,onChange:i,defaultTitle:d,hidePosition:c}){var j,N,f,g,D,I,w,S,M,A,F,E,C,T;const l=a.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),u=(L,k)=>{i({...o??{},[L]:k})},x=(L,k)=>{var O,P,B,Y;const R=L==="enabled"&&k===!0,y=(O=o==null?void 0:o.name)==null?void 0:O.text,_=R&&!y&&d;i({...o??{},name:{...o==null?void 0:o.name,enabled:L==="enabled"?k:((P=o==null?void 0:o.name)==null?void 0:P.enabled)??!1,text:L==="text"?k:_?d:y,fontSize:L==="fontSize"?k:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:L==="fontWeight"?k:(Y=o==null?void 0:o.name)==null?void 0:Y.fontWeight}})},m=(L,k)=>{var R,y;i({...o??{},labels:{enabled:L==="enabled"?k:((R=o==null?void 0:o.labels)==null?void 0:R.enabled)??!0,rotation:L==="rotation"?k:(y=o==null?void 0:o.labels)==null?void 0:y.rotation}})},b=(L,k)=>{i({...o??{},scale:{...o==null?void 0:o.scale,[L]:k===""?"auto":Number(k)}})},h=s==="x"?["auto","top","bottom"]:["auto","left","right"],p=["auto","0","45","90","-45","-90"];return e.jsxs(a.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(a.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:n})})}),e.jsx(t.Switch,{size:"sm",checked:(o==null?void 0:o.enabled)!==!1,onCheckedChange:L=>u("enabled",L),onClick:L=>L.stopPropagation()})]}),e.jsxs(a.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(a.Checkbox,{id:`${s}-title-enabled`,checked:((j=o==null?void 0:o.name)==null?void 0:j.enabled)??!1,onCheckedChange:L=>x("enabled",L===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((N=o==null?void 0:o.name)==null?void 0:N.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(lt,{placeholder:`${n} title`,value:((f=o==null?void 0:o.name)==null?void 0:f.text)||"",onSave:L=>x("text",L),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(lt,{type:"number",placeholder:"12",value:String(((g=o==null?void 0:o.name)==null?void 0:g.fontSize)||12),onSave:L=>x("fontSize",Number(L)||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:((D=o==null?void 0:o.name)==null?void 0:D.fontWeight)||"normal",onValueChange:L=>x("fontWeight",L),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"})]})]})]})]})]})]}),!c&&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:L=>u("position",L),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(L=>e.jsx(t.SelectItem,{value:L,className:"text-xs",children:L==="auto"?"Auto (Default)":t.titleCase(L)},L))})]})]}),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:((I=o==null?void 0:o.labels)==null?void 0:I.enabled)!==!1,onCheckedChange:L=>m("enabled",L)})]}),((w=o==null?void 0:o.labels)==null?void 0:w.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(((S=o==null?void 0:o.labels)==null?void 0:S.rotation)||"auto"),onValueChange:L=>m("rotation",L==="auto"?"auto":Number(L)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(L=>e.jsx(t.SelectItem,{value:L,className:"text-xs",children:L==="auto"?"Auto (Default)":`${L}°`},L))})]})]})]}),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:l==="override",onCheckedChange:L=>i({...o,formatMode:L?"override":"inherit"})})]}),l==="override"&&e.jsx(Ut,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:L=>i({...o,formatMode:"override",formatOptions:L}),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(lt,{type:"number",placeholder:"auto",value:((M=o==null?void 0:o.scale)==null?void 0:M.min)==="auto"||((A=o==null?void 0:o.scale)==null?void 0:A.min)===void 0?"":String(o.scale.min),onSave:L=>b("min",L),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(lt,{type:"number",placeholder:"auto",value:((F=o==null?void 0:o.scale)==null?void 0:F.max)==="auto"||((E=o==null?void 0:o.scale)==null?void 0:E.max)===void 0?"":String(o.scale.max),onSave:L=>b("max",L),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(lt,{type:"number",placeholder:"auto",value:((C=o==null?void 0:o.scale)==null?void 0:C.stepSize)==="auto"||((T=o==null?void 0:o.scale)==null?void 0:T.stepSize)===void 0?"":String(o.scale.stepSize),onSave:L=>b("stepSize",L),className:""})})]})]})]})]})]})}function ys(s,n,r){var d,c,l;if(s==="x"){const u=(c=(d=n==null?void 0:n.config)==null?void 0:d.groupByColumns)==null?void 0:c[0];return(u==null?void 0:u.label)||(u==null?void 0:u.name)||""}const o=((l=n==null?void 0:n.config)==null?void 0:l.metricColumns)||[],i=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const u=o.filter((x,m)=>{const b=i.find(h=>h.idx===m);return!b||b.yAxisId!=="y2"});return u.length===1&&(u[0].label||u[0].name)||""}if(s==="y2"){const u=o.filter((x,m)=>{const b=i.find(h=>h.idx===m);return(b==null?void 0:b.yAxisId)==="y2"});return u.length===1&&(u[0].label||u[0].name)||""}return""}function Vl(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),i=a.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(i))return null;const d=a.AxisConfigurator.getAxisInfo(i,n);if(!d.hasXAxis&&!d.hasYAxis)return null;const c=(u,x)=>{let m;u==="x"?m="xAxisConfig":u==="y"?m="yAxisConfig":m="secondaryYAxisConfig";const b={...n||{},[m]:x};r(b);const h={...s,preferences:b};o(h)},l=d.hasY2Axis&&i==="combo";return e.jsxs(a.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(a.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(a.AccordionContent,{className:"pt-2",children:e.jsxs(a.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[d.hasXAxis&&e.jsx(vs,{axis:"x",label:"X-Axis",type:d.xAxisType,config:a.mergeAxisConfig(a.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:u=>c("x",u),defaultTitle:ys("x",s,n)}),d.hasYAxis&&e.jsx(vs,{axis:"y",label:l?"Y-Axis (Left)":"Y-Axis",type:d.yAxisType,config:a.mergeAxisConfig(a.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:u=>c("y",u),defaultTitle:ys("y",s,n)}),l&&e.jsx(vs,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:a.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:u=>c("y2",u),defaultTitle:ys("y2",s,n),hidePosition:!0})]})})]})}function _l(){const s=t.useEditorStore(b=>b.card),n=a.useEffectiveEditorCardType(),r=t.useEditorStore(b=>{var h,p,j,N;return(N=(j=(p=(h=b.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:j.plugins)==null?void 0:N.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!a.chartSupportsLegend(n))return null;const i=a.getDefaultLegendConfig(n),d=(i==null?void 0:i.display)??!0,c=(i==null?void 0:i.position)??"top",l=(i==null?void 0:i.align)??"center",u=(b,h)=>{const p={...r,[b]:h};o(p)},x=["top","bottom","left","right"],m=["start","center","end"];return e.jsxs(a.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(a.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(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(a.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)??d,onCheckedChange:b=>u("display",b)})]}),((r==null?void 0:r.display)??d)&&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)||c,onValueChange:b=>u("position",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]}),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)||l,onValueChange:b=>u("align",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]})]})]})})]})}function Yl(){var k,R,y,_,O,P,B;const s=t.useEditorStore(Y=>Y.card),n=a.useEffectiveEditorCardType(),r=t.useEditorStore(Y=>{var q,z;return(z=(q=Y.card)==null?void 0:q.preferences)==null?void 0:z.dataLabelsConfig}),o=t.useEditorStore(Y=>{var q;return(q=Y.card)==null?void 0:q.preferences}),{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!a.chartSupportsDataLabels(n))return null;const c=n==="bullet"?((k=o==null?void 0:o.bulletConfig)==null?void 0:k.orientation)??(((R=o==null?void 0:o.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,l=c!=null?c==="horizontal":((y=o==null?void 0:o.chartOptions)==null?void 0:y.indexAxis)==="y",u=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",m=n==="bubble"||n==="scatter",b=(O=(_=o==null?void 0:o.chartOptions)==null?void 0:_.plugins)==null?void 0:O.datalabels,h=(b==null?void 0:b.display)!==!1&&((b==null?void 0:b.anchor)||(b==null?void 0:b.align)),p=a.getDefaultDataLabelsConfig(n,s.preferences),j=r??p,N=(p==null?void 0:p.enabled)??h??!1,f=(r==null?void 0:r.enabled)!==void 0?r.enabled:N,g=(Y,q)=>{const $={...p??{},...r??{},[Y]:q};Y==="enabled"&&($.display=q,q&&m&&!$.position&&($.position="bottom")),Y==="position"&&m&&($.position="bottom"),Y==="formatMode"&&q==="inherit"&&($.format=void 0,$.formatOptions=void 0);const Q={...s.preferences||{},dataLabelsConfig:$};i(Q);const U={...s,preferences:Q};d(U)},D=(Y,q)=>{const z=r??{},$={...p??{},...z,font:{...z.font||{},[Y]:q}},Q={...s.preferences||{},dataLabelsConfig:$};i(Q);const U={...s,preferences:Q};d(U)},I=()=>{const Y=n;return Y==="stackedBar"||Y==="stackedLine"||Y==="pie"||Y==="doughnut"?"center":l?"right":"top"},w=n!=="treemap"&&n!=="heatmap",S=n!=="treemap",M=I();let A=[];if(w)if(m)A=["bottom"];else if(u||x)A=["center"];else{const Y=l?["center","left","right"]:["center","top","bottom"];A=["auto",...n==="bullet"?Y:Y.filter(z=>z!==M),"custom"]}const F=()=>t.titleCase(M),E=["center","start","end"],C=["center","start","end","top","bottom"],T=(j==null?void 0:j.formatMode)||(j!=null&&j.format&&!["auto"].includes(j.format)?"override":"inherit"),L=(j==null?void 0:j.format)==="none";return e.jsxs(a.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(a.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(Rr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(a.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:f,onCheckedChange:Y=>g("enabled",Y)})]}),f&&e.jsxs(e.Fragment,{children:[w&&!u&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:m?(j==null?void 0:j.position)||"bottom":(j==null?void 0:j.position)||"auto",onValueChange:Y=>g("position",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:Y==="auto"?F():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=>g("showTotal",Y)})]}),(j==null?void 0:j.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:(j==null?void 0:j.anchor)||"center",onValueChange:Y=>g("anchor",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.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((j==null?void 0:j.align)||"center"),onValueChange:Y=>g("align",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:C.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:T==="override",onCheckedChange:Y=>g("formatMode",Y?"override":"inherit")})]}),T==="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:L,onCheckedChange:Y=>{const q=r??{},V={...p??{},...q,formatMode:"override",format:Y?"none":void 0,formatOptions:Y?void 0:q.formatOptions},$={...s.preferences||{},dataLabelsConfig:V};i($),d({...s,preferences:$})}})]}),!L&&e.jsx(Ut,{formatOptions:(j==null?void 0:j.formatOptions)||{},onFormatOptionsChange:Y=>{const V={...p??{},...r??{},formatMode:"override",format:Y.type&&Y.type!=="auto"?Y.type:void 0,formatOptions:Y},$={...s.preferences||{},dataLabelsConfig:V};i($),d({...s,preferences:$})},showTitle:!1})]})]}),S&&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(lt,{type:"number",placeholder:"12",value:String(((P=j==null?void 0:j.font)==null?void 0:P.size)||12),onSave:Y=>D("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=j==null?void 0:j.font)==null?void 0:B.weight)||"normal",onValueChange:Y=>D("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:(j==null?void 0:j.color)==="auto"||!(j!=null&&j.color)?"auto":"custom",onValueChange:Y=>{Y==="auto"&&g("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(lt,{type:"number",placeholder:"0",value:String((j==null?void 0:j.rotation)||0),onSave:Y=>g("rotation",Number(Y)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function zl(){var d;const s=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.type}),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",i=c=>{const l={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:c}};r(l)};return e.jsxs(a.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(a.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(a.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(a.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(a.RadioGroup,{value:o,onValueChange:c=>i(c??"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(a.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(a.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 ql=Object.keys(a.HEATMAP_PRESET_PALETTES);function $l(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},d=i.colorPalette??"green",c=i.legendPosition??"bottom",l=v.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...a.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),u=h=>{const p={...i,...h};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...a.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...n||{},heatmapConfig:p})},x=h=>{u({colorPalette:h,colorRange:h==="custom"?i.colorRange??[...a.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(h,p)=>{const j=[...l];j[h]=p,u({colorPalette:"custom",colorRange:j})},b=h=>{u({legendPosition:h})};return o?e.jsxs(a.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(a.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(a.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(a.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(a.RadioGroup,{value:d,onValueChange:h=>x(h??"blue"),className:"space-y-3",children:[ql.map(h=>{const p=a.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(a.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="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(a.ColorField,{value:l[0],onChange:h=>m(0,h??"#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(a.ColorField,{value:l[1],onChange:h=>m(1,h??"#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:c,onValueChange:h=>b(h??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const Hn=["poor","satisfactory","good"];function Qn(s){if(!s)return;const n={...s};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function Kl(){var k,R;const s=t.useEditorStore(y=>y.card.preferences),n=t.useEditorStore(y=>y.card),r=t.useEditorStore(y=>y.isDevMode),{setCardPreferences:o,setChartOrientation:i}=t.useEditorActions(),d=v.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),l=je.hasValidCardConfig(n==null?void 0:n.config)&&!r,[u,x]=v.useState(d.showRanges??!1),[m,b]=v.useState(d.rangesArePercentages??!1),h=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!l,[p,j]=v.useState(h);v.useEffect(()=>{x(d.showRanges??!1)},[d.showRanges]),v.useEffect(()=>{b(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const N=d.targetValue===void 0?"":String(d.targetValue);v.useEffect(()=>{const y=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!l;j(y)},[d.disableAutoComparative,d.comparativeMetricKey,l]);const f=v.useMemo(()=>{var y,_;return((_=(y=n==null?void 0:n.config)==null?void 0:y.metricColumns)==null?void 0:_.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(k=n==null?void 0:n.config)==null?void 0:k.metricColumns]);v.useEffect(()=>{var z,V;if(!s||f.length===0)return;const y={};let _=!1;const O=(z=f[1])==null?void 0:z.value;!d.targetMetricKey&&O&&(y.targetMetricKey=O,_=!0);const P=(V=f[2])==null?void 0:V.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&P&&(y.comparativeMetricKey=P,_=!0);const B=f.slice(3),Y={...d.rangeKeys||{}};let q=!1;if(Hn.forEach(($,Q)=>{!Y[$]&&B[Q]&&(Y[$]=B[Q].value,q=!0)}),q&&(y.rangeKeys=Y,_=!0,d.showRanges===void 0&&(y.showRanges=!0)),_){const $=Qn({...d,...y});o({...s,bulletConfig:$})}},[f,d,s,o]);const g=y=>{const _=Qn({...d,...y});o({...s,bulletConfig:_})},D=(y,_)=>{const O={...d.rangeKeys||{},[y]:_.trim()};_.trim()||delete O[y],g({rangeKeys:Object.keys(O).length>0?O:void 0})},I=(y,_)=>{const O=_===""?void 0:Number(_),P={...d.ranges||{}};O===void 0||Number.isNaN(O)?delete P[y]:P[y]=O,g({ranges:Object.keys(P).length?P:void 0})},w=y=>{if(y===""){g({targetValue:void 0});return}const _=Number(y);g({targetValue:Number.isNaN(_)?void 0:_})},S=(y,_)=>{const O=_.trim(),P={...d.rangeLabels||{}};O?P[y]=O:delete P[y],g({rangeLabels:Object.keys(P).length>0?P:void 0})},M=y=>{x(y),g({showRanges:y})},A=y=>{b(y),g({rangesArePercentages:y})},F=d.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),E=y=>{g({orientation:y}),i(y==="horizontal"?"y":"x")},C=[{value:"__none",label:"None"},...f.map(y=>({value:y.value,label:y.label}))],T=C,L=y=>{if(j(y),!y){g({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!l){g({disableAutoComparative:!1});return}if(d.comparativeMetricKey)g({disableAutoComparative:!1});else{const _=f.find(O=>O.value!==d.targetMetricKey);g({comparativeMetricKey:_==null?void 0:_.value,disableAutoComparative:!1})}};return e.jsxs(a.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(a.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(a.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(a.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:F,onValueChange:y=>E(y),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"})]})]})]}),l&&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:d.targetMetricKey||"__none",onValueChange:y=>g({targetMetricKey:y==="__none"?void 0:y}),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"}),f.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),l?e.jsxs(t.Select,{value:d.comparativeMetricKey||"__none",onValueChange:y=>g({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:C.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.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:p,onCheckedChange:y=>L(y)})]}),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(tt,{type:"number",className:"h-8 text-xs",value:N,onCommit:w,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:M})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!u,onChange:y=>A(y.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:Hn.map(y=>{var _,O,P,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:[y," LABEL"]}),e.jsx(tt,{placeholder:`Display label (${y})`,value:((_=d.rangeLabels)==null?void 0:_[y])||"",onCommit:q=>S(y,q),className:"h-8 text-xs"})]}),l?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(t.Select,{value:((O=d.rangeKeys)==null?void 0:O[y])||"__none",onValueChange:q=>{q==="__none"?D(y,""):D(y,q)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:T.map(q=>e.jsx(t.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN KEY"]}),e.jsx(tt,{placeholder:"Column key",value:((P=d.rangeKeys)==null?void 0:P[y])||"",onCommit:q=>D(y,q),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:[y," VALUE"]}),e.jsx(tt,{type:"number",placeholder:m?"0.80":"Static value",value:((B=d.ranges)==null?void 0:B[y])===void 0?"":String((Y=d.ranges)==null?void 0:Y[y]),onCommit:q=>I(y,q),className:"h-8 text-xs"})]})]},y)})})]})]})]})}function Jn(s){if(!s)return;const n={...s};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function Ul(){var S,M,A,F,E,C,T,L,k,R,y,_;const s=t.useEditorStore(O=>O.card.preferences),n=t.useEditorStore(O=>O.card),r=a.useEffectiveEditorCardType(),o=t.useEditorStore(O=>O.isDevMode),{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions(),c=r==="bubble",l=r==="scatter",u=v.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),m=je.hasValidCardConfig(n==null?void 0:n.config)&&!o,b=v.useMemo(()=>{var O,P;return((P=(O=n==null?void 0:n.config)==null?void 0:O.metricColumns)==null?void 0:P.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(S=n==null?void 0:n.config)==null?void 0:S.metricColumns]),h=v.useMemo(()=>{var O,P;return((P=(O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)==null?void 0:P.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(M=n==null?void 0:n.config)==null?void 0:M.groupByColumns]),p=v.useMemo(()=>u.enableGrouping!==void 0?u.enableGrouping:!o&&h.length>=2,[u.enableGrouping,o,h.length]),[j,N]=v.useState(p);v.useEffect(()=>{N(p)},[p]);const f=O=>{const P={...s||{},bubbleScatterConfig:O};i(P),n&&d({...n,preferences:P})},g=O=>{i(O),n&&d({...n,preferences:O})};v.useEffect(()=>{if(!s||b.length===0)return;const O={};let P=!1;if(!u.xMetricKey&&b[0]&&(O.xMetricKey=b[0].value,P=!0),!u.yMetricKey&&b[1]&&(O.yMetricKey=b[1].value,P=!0),c&&!u.radiusMetricKey&&b[2]&&(O.radiusMetricKey=b[2].value,P=!0),!u.labelKey&&h[0]&&(O.labelKey=h[0].value,P=!0),p&&!u.groupKey&&h[1]&&(O.groupKey=h[1].value,O.enableGrouping=!0,P=!0),P){const B=Jn({...u,...O});f(B)}},[b,h,u,s,i,c,p]);const D=O=>{const P=Jn({...u,...O});f(P)},I=O=>{N(O),D({enableGrouping:O,groupKey:O?u.groupKey:void 0})};if(!c&&!l)return null;const w=c?a.Circle:a.ChartScatter;return e.jsxs(a.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(a.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(w,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[c?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(a.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"}),m?e.jsxs(t.Select,{value:u.labelKey||"",onValueChange:O=>D({labelKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for labels",value:u.labelKey||"",onCommit:O=>D({labelKey:O})})]}),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:j,onCheckedChange:I})]}),j&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),m?e.jsxs(t.Select,{value:u.groupKey||"",onValueChange:O=>D({groupKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:u.groupKey||"",onCommit:O=>D({groupKey:O})})]})]}),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"}),m?e.jsxs(t.Select,{value:u.xMetricKey||"",onValueChange:O=>D({xMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:u.xMetricKey||"",onCommit:O=>D({xMetricKey:O})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),m?e.jsxs(t.Select,{value:u.yMetricKey||"",onValueChange:O=>D({yMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:u.yMetricKey||"",onCommit:O=>D({yMetricKey:O})})]}),c&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),m?e.jsxs(t.Select,{value:u.radiusMetricKey||"",onValueChange:O=>D({radiusMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for radius",value:u.radiusMetricKey||"",onCommit:O=>D({radiusMetricKey:O})})]})]}),c&&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:O=>D({radiusScale:O}),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(tt,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((A=u.minRadius)==null?void 0:A.toString())||"",onCommit:O=>D({minRadius:O?Number(O):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(tt,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((F=u.maxRadius)==null?void 0:F.toString())||"",onCommit:O=>D({maxRadius:O?Number(O):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(a.Slider,{value:[u.fixedRadius||10],onValueChange:([O])=>D({fixedRadius:O}),min:3,max:30,step:1,className:"py-2"})]})]}),l&&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(a.Slider,{value:[u.fixedRadius||5],onValueChange:([O])=>D({fixedRadius:O}),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:((C=(E=s==null?void 0:s.xAxisConfig)==null?void 0:E.name)==null?void 0:C.enabled)??!1,onCheckedChange:O=>{var Y,q,z,V;const P=u.xMetricKey||"X Axis",B=u.yMetricKey||"Y Axis";g({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:O,text:((q=(Y=s==null?void 0:s.xAxisConfig)==null?void 0:Y.name)==null?void 0:q.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:O,text:((V=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:V.text)||B}}})}})]}),((L=(T=s==null?void 0:s.xAxisConfig)==null?void 0:T.name)==null?void 0:L.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(tt,{className:"h-8 text-xs",placeholder:u.xMetricKey||"X Axis",value:((R=(k=s==null?void 0:s.xAxisConfig)==null?void 0:k.name)==null?void 0:R.text)||"",onCommit:O=>{var P;g({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:O||u.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(tt,{className:"h-8 text-xs",placeholder:u.yMetricKey||"Y Axis",value:((_=(y=s==null?void 0:s.yAxisConfig)==null?void 0:y.name)==null?void 0:_.text)||"",onCommit:O=>{var P;g({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:O||u.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Gl=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Hl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},d=i.percentMode??"percentOfTotal",c=i.shrinkFraction??1,l=i.labelThreshold??0,u=h=>{const p={...i,...h};r({...n||{},funnelConfig:p})},x=h=>{u({percentMode:h})},m=h=>{u({shrinkFraction:h[0]})},b=h=>{u({labelThreshold:h[0]})};return o?e.jsxs(a.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(a.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(a.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(a.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(a.RadioGroup,{value:d,onValueChange:h=>x(h),className:"space-y-2",children:Gl.map(h=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(a.RadioGroupItem,{id:`funnel-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(a.Slider,{value:[c],onValueChange:m,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(c*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(a.Slider,{value:[l],onValueChange:b,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:l===0?"Showing all labels":`Hide labels below ${l}%`})]})]})]}):null}function os(){const s=t.useEditorStore(c=>c.card),{data:n,comparisonMetadata:r}=a.useEditorCardQuery(s),{keys:o}=a.getKeys((n==null?void 0:n.records)||[],r),i=o.slice(1).filter(c=>!je.METADATA_KEYS.includes(c));let d=i;if(["stackedBar","stackedLine"].includes(s.type)){const c=a.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:o[0],pivotKey:o[1],valueKey:o[2]}),{keys:l}=a.getKeys(c);d=l.slice(1)}return{transformedMetricKeys:d,dimensionKeys:o.slice(0,1),keys:o,defaultMetricKeys:i}}const Ql=[{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"}],Jl=[{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)"}],Wl=["center","start","end"],Xl=["center","start","end","top","bottom"];function ls({config:s,onChange:n,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:i,showAppearance:d=!0}){var j,N,f,g,D,I;const c=i??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),l=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],u=(w,S)=>{const M={...s,[w]:S};n(M)},x=(w,S)=>{const M={...s,font:{...(s==null?void 0:s.font)||{},[w]:S}};n(M)},m=(w,S)=>{const M={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[w]:S}};n(M)},b=()=>r?"Right":"Top",h=s||{},p=h.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:h.position||"auto",onValueChange:w=>u("position",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"?b():w==="custom"?"Custom (Advanced)":t.titleCase(w)},w))})]})]}),h.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:h.anchor||"center",onValueChange:w=>u("anchor",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(h.align||"center"),onValueChange:w=>u("align",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]})]}),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:p,onValueChange:w=>u("format",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"&&o?"Auto (Use Axis)":w==="none"?"None (Raw Value)":t.titleCase(w)},w))})]})]}),!["auto","none"].includes(p)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(p)&&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(lt,{type:"number",placeholder:"0",value:String(((j=h.formatOptions)==null?void 0:j.decimalPlaces)??(p==="currency"?2:p==="percent"?1:0)),onSave:w=>m("decimalPlaces",Number(w)),className:""})})]}),p==="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:((N=h.formatOptions)==null?void 0:N.currency)||"USD",onValueChange:w=>m("currency",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]}),["number","currency"].includes(p)&&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:((f=h.formatOptions)==null?void 0:f.useSuffix)??!1,onCheckedChange:w=>m("useSuffix",w)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((g=h.formatOptions)==null?void 0:g.locale)||"en-US",onValueChange:w=>m("locale",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]}),d&&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(lt,{type:"number",placeholder:"12",value:String(((D=h.font)==null?void 0:D.size)||12),onSave:w=>x("size",Number(w)),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:((I=h.font)==null?void 0:I.weight)||"normal",onValueChange:w=>x("weight",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:h.color==="auto"||!h.color?"auto":"custom",onValueChange:w=>{w==="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(lt,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:w=>u("rotation",Number(w)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Zl=[{type:"bar",icon:a.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:a.ChartLine,label:"Line"}],ei=[0,1,2,3,4,5,6,8,10],ti=[{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 │"}],si=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ni(){return t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(a.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(ai,{})})]})}function ai(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(ri,{metricKey:n,idx:r},n))})}function ri({metricKey:s,idx:n}){var g;const[r,o]=v.useState(!1),i=t.useEditorStore(D=>{var I;return(I=D.card)==null?void 0:I.preferences}),d=t.useEditorStore(D=>{var I,w;return(w=(I=D.card)==null?void 0:I.preferences)==null?void 0:w.datasetOptions}),c=d==null?void 0:d.find(D=>D.idx===n),{setCardPreferences:l}=t.useEditorStore(D=>D.actions),u=(c==null?void 0:c.type)||"bar",x=(c==null?void 0:c.yAxisId)||"y",m=((g=c==null?void 0:c.dataLabels)==null?void 0:g.enabled)??!1,b=u==="line"?a.ChartLine:a.ChartColumnIncreasing;function h(D){const I={idx:n,type:u,yAxisId:x,dataLabels:c==null?void 0:c.dataLabels,...D};if(!c)l({...i||{},datasetOptions:[...d||[],I]});else{const w=d==null?void 0:d.map(S=>S.idx===n?{...S,...I}:S);l({...i||{},datasetOptions:w})}}function p(D){h({type:D})}function j(D){h({yAxisId:D})}function N(D){h({dataLabels:{...c==null?void 0:c.dataLabels,enabled:D}})}function f(D){h({dataLabels:D})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(b,{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:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(a.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:Zl.map(({type:D,icon:I,label:w})=>{const S=u===D;return e.jsxs("button",{onClick:()=>p(D),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",S?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(I,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:w})]},D)})})]}),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:x,onValueChange:D=>j(D),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:(c==null?void 0:c.lineStyle)||"solid",onValueChange:D=>h({lineStyle:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:si.map(({value:D,label:I})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:I},D))})]})]}),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((c==null?void 0:c.pointRadius)??3),onValueChange:D=>h({pointRadius:Number(D)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ei.map(D=>e.jsx(t.SelectItem,{value:String(D),className:"text-xs",children:D===0?"None":D},D))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(c==null?void 0:c.pointStyle)||"circle",onValueChange:D=>h({pointStyle:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ti.map(({value:D,label:I})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:I},D))})]})]})]})]}),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:N})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ls,{config:c==null?void 0:c.dataLabels,onChange:f,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Cs=[{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"}],oi=[0,1,2,3,4,5,6,8,10],li=[{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 │"}],ii=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ci(s){return s==null?"origin":s===!1?"false":s}function di(){const s=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(a.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(ui,{})})]})}function ui(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(mi,{metricKey:n,idx:r},n))})}function mi({metricKey:s,idx:n}){var N;const[r,o]=v.useState(!1),i=t.useEditorStore(f=>{var g;return(g=f.card)==null?void 0:g.preferences}),d=t.useEditorStore(f=>{var g,D;return(D=(g=f.card)==null?void 0:g.preferences)==null?void 0:D.datasetOptions}),c=d==null?void 0:d.find(f=>f.idx===n),{setCardPreferences:l}=t.useEditorStore(f=>f.actions),u=ci(c==null?void 0:c.fill),x=((N=c==null?void 0:c.dataLabels)==null?void 0:N.enabled)??!1,m=Cs.find(f=>f.value===u)||Cs[0];function b(f){const g={idx:n,fill:u,dataLabels:c==null?void 0:c.dataLabels,...f};if(!c)l({...i||{},datasetOptions:[...d||[],g]});else{const D=d==null?void 0:d.map(I=>I.idx===n?{...I,...g}:I);l({...i||{},datasetOptions:D})}}function h(f){b({fill:f==="false"?!1:f})}function p(f){b({dataLabels:{...c==null?void 0:c.dataLabels,enabled:f}})}function j(f){b({dataLabels:f})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(a.ChartArea,{className:"h-3 w-3"}),m.label.split(" ")[0]]})})]})}),e.jsx(a.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:f=>h(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cs.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:f.label})})},f.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:(c==null?void 0:c.lineStyle)||"solid",onValueChange:f=>b({lineStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ii.map(({value:f,label:g})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:g},f))})]})]}),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((c==null?void 0:c.pointRadius)??3),onValueChange:f=>b({pointRadius:Number(f)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:oi.map(f=>e.jsx(t.SelectItem,{value:String(f),className:"text-xs",children:f===0?"None":f},f))})]})]}),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:(c==null?void 0:c.pointStyle)||"circle",onValueChange:f=>b({pointStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:li.map(({value:f,label:g})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:g},f))})]})]})]})]}),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(ls,{config:c==null?void 0:c.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const xi=[0,1,2,3,4,5,6,8,10],hi=[{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 │"}],Ns=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function pi(){return t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type})!=="line"?null:e.jsxs(a.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(fi,{})})]})}function fi(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(gi,{metricKey:n,idx:r},n))})}function gi({metricKey:s,idx:n}){var f;const[r,o]=v.useState(!1),i=t.useEditorStore(g=>{var D;return(D=g.card)==null?void 0:D.preferences}),d=t.useEditorStore(g=>{var D,I;return(I=(D=g.card)==null?void 0:D.preferences)==null?void 0:I.datasetOptions}),c=d==null?void 0:d.find(g=>g.idx===n),{setCardPreferences:l}=t.useEditorStore(g=>g.actions),u=(c==null?void 0:c.lineStyle)||"solid",x=(c==null?void 0:c.pointRadius)??3,m=(c==null?void 0:c.pointStyle)||"circle",b=((f=c==null?void 0:c.dataLabels)==null?void 0:f.enabled)??!1,h=Ns.find(g=>g.value===u)||Ns[0];function p(g){const D={idx:n,lineStyle:u,pointRadius:x,pointStyle:m,dataLabels:c==null?void 0:c.dataLabels,...g};if(!c)l({...i||{},datasetOptions:[...d||[],D]});else{const I=d==null?void 0:d.map(w=>w.idx===n?{...w,...D}:w);l({...i||{},datasetOptions:I})}}function j(g){p({dataLabels:{...c==null?void 0:c.dataLabels,enabled:g}})}function N(g){p({dataLabels:g})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(Pr,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(a.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:g=>p({lineStyle:g}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(({value:g,label:D})=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:D},g))})]})]}),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(x),onValueChange:g=>p({pointRadius:Number(g)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xi.map(g=>e.jsx(t.SelectItem,{value:String(g),className:"text-xs",children:g===0?"None":g},g))})]})]}),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:m,onValueChange:g=>p({pointStyle:g}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hi.map(({value:g,label:D})=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:D},g))})]})]})]})]}),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:b,onCheckedChange:j})]}),b&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ls,{config:c==null?void 0:c.dataLabels,onChange:N,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const bi=[0,2,4,6,8,10,12,16,20];function ji(){const s=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(a.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(vi,{})})]})}function vi(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(yi,{metricKey:n,idx:r},n))})}function yi({metricKey:s,idx:n}){var j;const[r,o]=v.useState(!1),i=t.useEditorStore(N=>{var f;return(f=N.card)==null?void 0:f.type}),d=t.useEditorStore(N=>{var f;return(f=N.card)==null?void 0:f.preferences}),c=t.useEditorStore(N=>{var f,g;return(g=(f=N.card)==null?void 0:f.preferences)==null?void 0:g.datasetOptions}),l=c==null?void 0:c.find(N=>N.idx===n),{setCardPreferences:u}=t.useEditorStore(N=>N.actions),x=(l==null?void 0:l.borderRadius)??0,m=((j=l==null?void 0:l.dataLabels)==null?void 0:j.enabled)??!1;function b(N){const f={idx:n,borderRadius:x,dataLabels:l==null?void 0:l.dataLabels,...N};if(!l)u({...d||{},datasetOptions:[...c||[],f]});else{const g=c==null?void 0:c.map(D=>D.idx===n?{...D,...f}:D);u({...d||{},datasetOptions:g})}}function h(N){b({dataLabels:{...l==null?void 0:l.dataLabels,enabled:N}})}function p(N){b({dataLabels:N})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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:x>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:",x]})})]})}),e.jsx(a.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(x),onValueChange:N=>b({borderRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bi.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":`${N}px`},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(ls,{config:l==null?void 0:l.dataLabels,onChange:p,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ci=[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 │"}],Si=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function wi(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=a.useEffectiveEditorCardType(),o=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const c=(l,u)=>{const x={...n||{},lineStyleConfig:{...o,[l]:u}};i(x),d({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(a.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(Ar,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(a.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:l=>c("lineStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Si.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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:l=>c("pointRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ci.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":l},l))})]})]}),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:l=>c("pointStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ni.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}const Ti=[0,2,4,6,8,10,12,16,20],Ei=[{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%"}],Ii=[{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 Di(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=a.useEffectiveEditorCardType(),o=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const c=(l,u)=>{const x={...n||{},barStyleConfig:{...o,[l]:u}};i(x),d({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(a.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(a.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:l=>c("borderRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ti.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":`${l}px`},l))})]})]}),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:l=>c("barPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ei.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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:l=>c("categoryPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ii.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}function ki(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(a.AccordionItem,{value:"stacked-sort",children:[e.jsx(a.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(a.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(gt,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{n(r)}})]})})]})}const Mi=["kpi"],Ss=2;function Tt(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 Ai(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Li(s){return{...s,role:"groupby"}}function Fi(){var D,I;const s=t.useEditorStore(w=>w.card),n=t.useEditorStore(w=>w.actions.updateCardConfig),r=a.useEffectiveEditorCardType(),{scopedFields:o}=a.useScopedFields(),i=((D=s.config)==null?void 0:D.metricColumns)||[],d=((I=s.config)==null?void 0:I.summary)||{},c=d.breakdownDimensions||[],l=c.length>0,u=Mi.includes(r),x=i.length>0,m=d.enabled===!0,b=u&&x,h=Array.from(new Map(o.filter(Ai).map(w=>[Tt(w),Li(w)])).values()),p=new Set(h.map(w=>Tt(w))),j=new Set(c.map(w=>Tt(w)).filter(w=>w&&p.has(w)));if(!u)return null;const N=w=>{n(s.id,{summary:{...d,...w}})},f=(w,S)=>{const M=Tt(w),A=h.filter(E=>j.has(Tt(E))),F=S?j.has(M)?A:[...A,w].slice(0,Ss):A.filter(E=>Tt(E)!==M);N({breakdownDimensions:F,...F.length>0?{showOnCard:!0}:{}})},g=w=>{if(!w){N({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}N({enabled:!0,showOnCard:d.showOnCard??!0,includeInDashboardSummary:d.includeInDashboardSummary??!0})};return e.jsxs(a.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(a.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(a.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]}),e.jsx(t.Switch,{size:"xs",checked:m,disabled:!b,onClick:w=>w.stopPropagation(),onPointerDown:w=>w.stopPropagation(),onCheckedChange:g,"aria-label":"Enable summary"})]}),e.jsx(a.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!m&&"opacity-60"),children:[!b&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:x?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Checkbox,{id:"summary-show-on-card",checked:d.showOnCard===!0,disabled:!m,onCheckedChange:w=>N({showOnCard:w===!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(a.Checkbox,{id:"summary-include-rollup",checked:d.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:w=>N({includeInDashboardSummary:w===!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:[c.length,"/",Ss]})]}),h.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:h.map(w=>{const S=Tt(w),M=j.has(S),A=j.size>=Ss,F=!m||!M&&A;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(a.Checkbox,{id:`summary-breakdown-${S}`,checked:M,disabled:F,onCheckedChange:E=>f(w,E===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${S}`,className:"cursor-pointer text-xs",children:w.label||w.name})]},S)})})]})]})})]})}const Ri=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Pi(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=a.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:i}=t.useEditorActions();if(!s||!Ri.has(r||""))return null;const d=n==null?void 0:n.tooltipConfig,c=(d==null?void 0:d.formatMode)||(d==null?void 0:d.mode)||"inherit",l=u=>{const x={...n||{},tooltipConfig:{...d||{},...u}};o(x),i({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(a.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(a.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:c==="override",onCheckedChange:u=>l({formatMode:u?"override":"inherit",mode:u?"override":"inherit"})})]}),c==="override"&&e.jsx(Ut,{formatOptions:(d==null?void 0:d.formatOptions)||{},onFormatOptionsChange:u=>l({formatMode:"override",mode:"override",formatOptions:u}),showTitle:!1})]})]})}function La({mode:s}){const n=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return a.isTableChartType(n)?null:e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(ni,{}),(n==="area"||n==="stackedArea")&&e.jsx(di,{}),n==="line"&&e.jsx(pi,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(ji,{}),e.jsx(wi,{}),e.jsx(Di,{}),e.jsx(zl,{}),s==="config"&&e.jsx(Ml,{}),s==="config"&&e.jsx(Fi,{}),e.jsx($l,{}),n==="bullet"&&e.jsx(Kl,{}),n==="funnel"&&e.jsx(Hl,{}),(n==="bubble"||n==="scatter")&&e.jsx(Ul,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(ki,{}),e.jsx(Bl,{}),e.jsx(Vl,{}),e.jsx(_l,{}),e.jsx(Yl,{}),e.jsx(Pi,{})]})}function Oi(){const s=t.useEditorStore(r=>r.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Os,{chartType:n}),e.jsx(a.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(La,{mode:"dev"})})]}):null}function Bi({focusSection:s,focusRequestId:n}){const r=t.useEditorStore(c=>c.card),o=r.type;if(t.getVisualizationMode(r)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(a.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(a.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(a.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 d(){if(a.supportsRegularTableSettings(o))return e.jsx(Aa,{cardType:o,focusSection:s,focusRequestId:n});switch(o){case"kpi":return e.jsx(bl,{});case"map":return e.jsx(Nl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ta,{})});case"text":return e.jsx(Ll,{});default:return e.jsx(Oi,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[d(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}const Wn=32;function Vi(){const s=v.useRef(null),n=v.useRef(null),r=t.useEditorStore(g=>g.isShowingVisual),o=t.useEditorStore(g=>g.isDevMode),i=t.useEditorStore(g=>g.showAIDialog),[d,c]=v.useState(!1),[l,u]=v.useState({section:null,id:0}),x=r&&!i,m=x&&(!o||d),b=o&&x,h=()=>c(g=>!g),p=g=>{g&&u(D=>({section:g,id:D.id+1})),o&&c(!0)};v.useEffect(()=>{var g,D,I,w;i?((g=s.current)==null||g.resize(0),(D=n.current)==null||D.resize(0)):((I=s.current)==null||I.resize(Wn),(w=n.current)==null||w.resize(25))},[i]);const[j,N]=v.useState(!1),f=x?{show:b,isOpen:m,onToggle:h,onOpen:p}:void 0;return e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(a.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:g=>e.jsx(gs,{mode:"toolbar",inlineToolbar:!0,overflowActions:g,visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})})})})}),e.jsx(a.ResizableHandle,{}),e.jsx(a.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:m?e.jsxs(a.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(a.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(gs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})}),!i&&e.jsx(a.ResizableHandle,{}),e.jsx(a.ResizablePanel,{ref:s,className:"flex",defaultSize:Wn,maxSize:45,children:e.jsx(Bi,{focusSection:l.section,focusRequestId:l.id})})]}):e.jsx(gs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})})]})}function _i(s){var ae;t.useAIInteractionStore(K=>K.currentAIContext);const[n,r]=v.useState(""),[o,i]=v.useState(null),{authToken:d,tokenProps:c}=a.useSemaphorContext(),l=t.useEditorStore(K=>K.card.id),u=t.useEditorStore(K=>{var ie;return(ie=K==null?void 0:K.card)==null?void 0:ie.sql}),x=t.useEditorStore(K=>K.isDevMode),m=t.useEditorStore(K=>{var ie;return(ie=K==null?void 0:K.card)==null?void 0:ie.python}),{setCardPython:b,setCardSql:h,setRunSql:p,switchCardType:j,setQueryConfig:N}=t.useEditorActions(),f=t.useEditorStore(K=>K.currentAssitantScope)||[],g=t.useEditorStore(K=>K.userInputForAI),D=t.useEditorStore(K=>K.triggerAIRun),I=t.useEditorStore(K=>K.card),w=t.useEditorStore(K=>K.selectedDatabaseName),S=t.useEditorStore(K=>K.selectedTableName),M=t.useEditorStore(K=>K.selectedConnectionId),A=t.useEditorStore(K=>K.selectedSchemaName),F=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:E,refetch:C,data:T}=a.useEditorCardQuery(I),{setTriggerAIRun:L,setCurrentAssitantScope:k,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:y,connectionType:_,selectedDatamodelId:O}=a.useEditorAside(),P=(ae=a.useDashboardQuery().data)==null?void 0:ae.assistantProfileId,B=v.useRef(a.createAssistantConversationId()),Y=v.useRef(null),q=v.useRef(l),z=v.useRef(!1),V=()=>{const K=Y.current;K&&(Y.current=null,B.current=a.createAssistantConversationId(),K==="clear"&&Q([]))},{messages:$,setMessages:Q,regenerate:U,error:J,sendMessage:W,status:ee,addToolResult:ue,stop:fe,clearError:be}=a.useChat({transport:new a.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:B.current,assistantRequestId:a.createAssistantRequestId(),isDevMode:x,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:ie})=>({body:{...ie,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var ie;if(z.current=!1,K.name==="AbortError"||(ie=K.message)!=null&&ie.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),V();return}console.error("[Editor Assistant] Stream error:",K),V()},onToolCall:ke,onFinish({isAbort:K,isDisconnect:ie,isError:Ce}){z.current=!1,r(""),console.log(K?"[Editor Assistant] Stream aborted by user":ie?"[Editor Assistant] Stream disconnected (network error)":Ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),V()}}),ge=v.useCallback(K=>{z.current=!0;try{const ie=W(K);return a.isPromiseLike(ie)?ie.catch(Ce=>{throw z.current=!1,Ce}):ie}catch(ie){throw z.current=!1,ie}},[W]),Pe=v.useCallback(()=>{z.current=!0;try{const K=U();return a.isPromiseLike(K)?K.catch(ie=>{throw z.current=!1,ie}):K}catch(K){throw z.current=!1,K}},[U]),Oe=K=>{let ie=!1;Q(Ce=>{const re=typeof K=="function"?K(Ce):K;if(re.length===0){if(z.current)return Y.current="clear",ie=!0,Ce;Y.current=null,B.current=a.createAssistantConversationId()}return re}),ie&&fe()};v.useEffect(()=>{if(q.current!==l){if(q.current=l,z.current){Y.current!=="clear"&&(Y.current="rotate"),fe();return}Y.current=null,B.current=a.createAssistantConversationId()}},[l,fe]),v.useEffect(()=>{D&&g&&(ge({role:"user",parts:[{type:"text",text:g}]}),L(!1))},[D,g,ge,L]);async function ke({toolCall:K}){var ie,Ce,re,he,Ye,Z,Fe,me,qe,Le,Ke,Se,oe,Ie,Re,De;if(["createChartFromSql","createForecast"].includes(K.toolName)){const te=((ie=K.input)==null?void 0:ie.sql)??((Ce=K.args)==null?void 0:Ce.sql),ve=((re=K.input)==null?void 0:re.python)??((he=K.args)==null?void 0:he.python),ye=((Ye=K.input)==null?void 0:Ye.chartType)??((Z=K.args)==null?void 0:Z.chartType);j(ye),h(te),b(ve),p(!0),ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!u){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:u,python:m||""}})}else if(K.toolName==="generateQueryConfig"){r("Generating query config...");const te=((Fe=K.input)==null?void 0:Fe.chartType)??((me=K.args)==null?void 0:me.chartType),ve=((qe=K.input)==null?void 0:qe.queryConfig)??((Le=K.args)==null?void 0:Le.queryConfig);((Ke=K.input)==null?void 0:Ke.cardConfig)??((Se=K.args)==null||Se.cardConfig),j(te),R(ve),h(void 0),b(void 0);const ye=await C();if((oe=ye==null?void 0:ye.data)!=null&&oe.error){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:ve,message:(Ie=ye==null?void 0:ye.data)==null?void 0:Ie.error.message}});return}if((Re=ye==null?void 0:ye.data)!=null&&Re.records){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized"}});return}ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized",records:(De=ye==null?void 0:ye.data)==null?void 0:De.records}})}else r("Analyzing...")}function Te(K){const ie=a.removeFromScopeArray(f,K);_e(ie)}function _e(K){const ie=a.sanitizeAIScope(K);k(ie),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(ie)}`}]}])}function ze(){const K={databaseName:w||"",schemaName:A||"",tableName:S||"",datamodelId:O||"",datamodelName:t.resolveDatamodelName(y),connectionId:M||"",connectionType:_||""},ie=a.dedup([...f,K]);_e(ie)}function Be(){const K={databaseName:w||"",schemaName:A||"",tableName:S||"",datamodelName:t.resolveDatamodelName(y),connectionId:M||"",connectionType:_||"",datamodelId:O||""};if(!a.isInAiScopeArray([...F||[],...f],K)||f.length===0){const Ce=a.dedup([...F||[],...f,K]).filter(re=>re.connectionId===K.connectionId);_e(Ce)}}const Ae=!["ready","error"].includes(ee),Me=a.getErrorMessage(J);return{messages:$,setMessages:Oe,sendMessage:ge,regenerate:Pe,isLoading:Ae,handleSetAIScope:Be,handleAddCurrentTableToScope:ze,removeFromCurrentSelections:Te,currentAssitantScope:f,setCurrentAssitantScope:k,stop:fe,status:ee,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:Me,clearError:be}}const Yi=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Xn({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:r}){const o=v.useRef(null),i=v.useRef(!1),[d,c]=v.useState(!1),[l,u]=v.useState(je.isDevEnv),[x,m]=v.useState(!1),[b,h]=v.useState(!1),[p,j]=v.useState(!1),[N,f]=v.useState(0),g=s??p,D=t.useCurrentAIContext(),{setCurrentAIContext:I,setHasEditorEntitySelectionOverride:w}=t.useAIActions(),{clearQueue:S}=t.useQueueActions(),{clearFileAttachments:M}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:F}=a.useAssistantContextEntities("editor"),E=t.useEditorStore(re=>re.card.id),C=t.useEditorStore(re=>re.card.dataSource),T=t.useEditorStore(re=>{var he;return(he=re.card.dataSource)==null?void 0:he.selectedEntities}),L=t.useEditorStore(re=>re.actions.setCardSql),k=t.useEditorStore(re=>re.actions.setRunSql),R=t.useEditorStore(re=>re.showAIDialog),y=t.useDashboardStore(re=>re.handleOpenAssistantProfile),{setShowAIDialog:_,setCardPython:O}=t.useEditorActions(),{assistantProfile:P}=a.useAssistantProfile(),{messages:B,setMessages:Y,sendMessage:q,isLoading:z,stop:V,status:$,llmUsage:Q,errorMessage:U,clearError:J}=_i(),[W,ee]=v.useState(""),ue=re=>{ee(re.target.value)},fe=re=>{re.preventDefault();const he=W.trim();if(!he&&A.length===0)return;const Ye=[];he&&Ye.push({type:"text",text:he}),A.forEach(Z=>{Z.data&&Ye.push({type:"file",mediaType:Z.type,filename:Z.name,url:`data:${Z.type};base64,${Z.data}`})}),q({role:"user",parts:Ye}),ee(""),M("editor"),be()},be=v.useCallback(()=>{f(re=>re+1)},[]);v.useEffect(()=>{var re;R&&!i.current&&((re=o.current)==null||re.focus()),i.current=R},[R]),v.useEffect(()=>{R&&(w(!1),I({selectedEntities:T||[]}))},[E,T,I,w,R]),a.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:z,sendMessage:q});const{hasActiveTools:ge,activeToolText:Pe}=a.useActiveToolStatus(B),Oe=v.useCallback(re=>{n==null||n(re),s===void 0&&j(re)},[s,n]);v.useEffect(()=>{if(!g)return;function re(he){he.key==="Escape"&&Oe(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[g,Oe]);const ke=v.useCallback(re=>{q({role:"user",parts:[{type:"text",text:re}]}),be()},[be,q]),Te=v.useCallback(async()=>{const re=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),t.ue.success("Conversation copied")}catch(he){console.error("Failed to copy conversation",he),t.ue.error("Unable to copy conversation")}},[B]),_e=v.useCallback(()=>{Oe(!g)},[g,Oe]);function ze(re,he){he==="sql"?(L(re),k(!0)):he==="python"&&(O(re),k(!0))}function Be(){D.selectedEntities.length===0&&I({selectedEntities:F})}function Ae(re){Be();const he={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};q(he),be()}function Me(re){Be(),q({role:"user",parts:[{type:"text",text:re}]}),be()}function ae(){return e.jsxs(a.DropdownMenu,{children:[e.jsx(a.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(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",children:[e.jsx(a.DropdownMenuLabel,{children:"Options"}),e.jsx(a.DropdownMenuSeparator,{}),e.jsx(a.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:c,children:"Token usage"}),e.jsx(a.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"Tool invocations"}),e.jsx(a.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:m,children:"System message"})]})]})}function K(){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 ie=(W==null?void 0:W.length)===0&&(B==null?void 0:B.filter(re=>re.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",g&&"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:[K(),y&&e.jsx(t.Button,{variant:"outline",size:"xs",className:"min-w-0 shrink",onClick:y,children:e.jsx("span",{className:"truncate",children:(P==null?void 0:P.name)||"Default profile"})}),e.jsxs("div",{"data-role":"header-actions",className:"flex shrink-0 items-center gap-1.5",children:[ae(),l&&e.jsx(t.Button,{variant:"ghost",size:"xs",className:"text-muted-foreground hover:text-foreground",onClick:Te,children:"Copy conversation"}),e.jsx(a.IconButton,{tooltip:g?"Exit fullscreen":"Expand",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:_e,children:g?e.jsx($e.Minimize2,{className:"h-3.5 w-3.5"}):e.jsx($e.Maximize2,{className:"h-3.5 w-3.5"})}),e.jsx(a.IconButton,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",tooltip:"New chat",onClick:()=>{Y([]),S("editor"),J()},children:e.jsx(a.SquarePen,{className:"h-3.5 w-3.5"})}),e.jsx(a.IconButton,{tooltip:"Close",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>{_(!1)},children:e.jsx(le.X,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(a.AssistantVirtualizedMessages,{messages:B,showTools:l,handleRun:ze,showSystemMessage:x,onQuickReply:ke,disableQuickReplies:z,status:$,errorMessage:U,activeToolText:z&&ge?Pe:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:R?"bottom-24 right-8":"hidden",scrollToEndSignal:N}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ie&&!P&&e.jsx(a.Placeholders,{onClick:Ae,placeholders:Yi}),e.jsx("div",{children:ie&&P&&e.jsx(a.SeedQuestions,{seedQuestions:P.seedQuestions||[],handleSeedQuestionClick:Me})})]}),e.jsx(a.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(a.ChatInputWithContext,{ref:o,setInput:ee,stop:V,input:W,handleInputChange:ue,handleSubmit:re=>{Be(),fe(re)},isLoading:z,status:$,assistantType:"editor",onFocus:()=>{}})]}),Q&&d&&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(a.AddDataPicker,{incomingSelectedEntities:F,open:b,onOpenChange:h,dataSource:C||a.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:re=>{w(!0),I({...D,selectedEntities:re})}})]});return g&&r?dr.createPortal(e.jsx(a.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 Vs({children:s,className:n,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",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function Fa({id:s,label:n,dataType:r,calculated:o,open:i,onOpenChange:d,onRemove:c,sortDirection:l,onSortDirectionChange:u,badge:x,children:m}){const{attributes:b,listeners:h,setNodeRef:p,transform:j,transition:N,isDragging:f}=a.useSortable({id:s});return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:d,children:[e.jsxs("div",{ref:p,style:{transform:a.CSS.Transform.toString(j),transition:N},className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",i?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",f&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...b,...h,"aria-label":`Drag ${n}`,className:t.cn(a.GRIP_REVEAL_CLASS,"text-muted-foreground hover:text-foreground"),onClick:g=>g.stopPropagation(),children:e.jsx(a.GripVertical,{className:"h-3 w-3"})}),e.jsx(a.TypeGlyph,{dataType:r,calculated:o}),e.jsx(Vs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n}),x,u&&e.jsx("button",{type:"button","aria-label":l==="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 hover:bg-muted hover:text-foreground",onClick:g=>{g.stopPropagation(),u(l==="asc"?"desc":"asc")},children:l==="asc"?e.jsx(a.ArrowUp,{className:"h-3 w-3"}):e.jsx(a.ArrowDown,{className:"h-3 w-3"})}),m&&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 hover:bg-muted hover:text-foreground data-[state=open]:bg-muted",onClick:g=>g.stopPropagation(),children:e.jsx(a.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 hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:g=>{g.stopPropagation(),c()},children:e.jsx(le.X,{className:"h-3 w-3"})})]}),m&&e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsx("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:m})})]})}function zi(s,n){var o;if(n.status==="blocked"||(o=s.sql)!=null&&o.trim())return!1;const r=new Set(n.mappingDispositions.flatMap(i=>i.status==="apply"?[i.filterValue.filterId]:[]));return n.cardFilterValues.some(i=>{const d=n.queryFilterDefinitions.find(u=>u.id===i.filterId);if(!t.hasFiniteDateComparisonRange(i))return!1;if(!(r.has(i.filterId)||(d==null?void 0:d.kind)==="global-date"))return!!(d&&qi([d],n.resolvedPrimaryDateField,[i]));const l=t.buildExecutedDateFilterDefinition(i);return!!(l&&t.resolveFieldDateComparisonCandidate({card:s,filter:l,filterValue:i,effectiveFilterValue:i,temporalBinding:n.resolvedPrimaryDateField}).status==="eligible")})}function qi(s,n,r){if(!n)return!1;const o=n.qualifiedFieldName,i=n.qualifiedEntityName,d=i&&n.name?`${i}.${n.name}`:o;return s.some(c=>{if(!(t.getDataType(c.dataType||"")==="date"))return!1;const u=a.getSelectedDateFilterColumn(c,r),x=u.split("."),m=x[x.length-1]||u,b=x.length>1?x.slice(0,-1).join("."):void 0,h=c.qualifiedTableName||b,p=h?`${h}.${m}`:void 0;return o?p?p===d||p.endsWith(`.${o}`):m===n.name:p?p===d:m===n.name})}function $i(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 Ki({aliasTemplate:s,onAliasTemplateChange:n}){var u;const[r,o]=v.useState(s),[i,d]=v.useState(!1),c=(u=t.useEditorStore(x=>{var m;return(m=x.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],l=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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:l,value:i?r:s,onChange:x=>{o(x.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&r!==s?(n(r),d(!1)):x.key==="Escape"&&(o(s),d(!1))},"aria-label":"Edit alias template"}),i&&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:()=>{n(r),d(!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),d(!1)},children:e.jsx(le.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Ui({valueAliases:s,onValueAliasesChange:n}){const[r,o]=v.useState(null),[i,d]=v.useState(""),[c,l]=v.useState(""),u=()=>{n({...s,"":""})},x=b=>{const h={...s};delete h[b],n(h)},m=b=>{const h={...s};delete h[b],h[i]=c,n(h),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(([b,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:r===b?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:i,onChange:j=>d(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(b):j.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:c,onChange:j=>l(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(b):j.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:()=>m(b),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(le.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:b,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(b),d(b),l(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(b),d(b),l(h)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(b),"aria-label":"Remove value alias",children:e.jsx(le.X,{className:"h-3 w-3"})})]})},b+p)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(a.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Gi({idx:s}){var l;const n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=t.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.datasetOptions}),o=t.useEditorStore(u=>u.actions.setCardPreferences),i=(l=n==null?void 0:n.chartOptions)==null?void 0:l.indexAxis,d=r==null?void 0:r.find(u=>u.idx===s);function c(u,x){(u==="end"||u==="start")&&je.getContrastColor(je.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!d)o({...n,datasetOptions:[...r||[],{idx:x,datalabels:m}]});else{const b={...d};b.datalabels=m;const h=r==null?void 0:r.map(p=>p.idx===x?b:p);o({...n,datasetOptions:h})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(a.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:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(le.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Tr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function Hi(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function Qi({col:s,idx:n,className:r,iconClassName:o,children:i}){const d=t.useEditorStore(m=>{var b;return(b=m.card)==null?void 0:b.preferences}),c=t.useEditorStore(m=>{var b,h;return(h=(b=m.card)==null?void 0:b.preferences)==null?void 0:h.datasetOptions}),l=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:u}=t.useEditorStore(m=>m.actions);function x(m){if(!l)u({...d,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const b={...l};b.type=m==="area"?"line":m,b.fill=m==="area"?"origin":"";const h=c==null?void 0:c.map(p=>p.idx===n?b:p);u({...d,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[i||e.jsx(Vs,{className:"max-w-[100px]",title:s,children:Hi(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(a.ChartColumnIncreasing,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(a.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(a.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(Gi,{idx:n})]})]})}function Ji(){const s=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>l.isDevMode),r=t.useEditorStore(l=>l.card.preferences),{setCardPreferences:o}=t.useEditorStore(l=>l.actions);function i(l){var m;const u={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(m=r==null?void 0:r.chartOptions)==null?void 0:m.plugins,...u}}};o(x)}function d(){var l,u,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 c(){var l,u,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?d():c()})}function Wi({column:s}){const n=t.useEditorStore(u=>u.card.type),r=t.useEditorStore(u=>{var x,m;return(m=(x=u.card)==null?void 0:x.config)==null?void 0:m.metricColumns}),o=(r==null?void 0:r.map(u=>u.label))||[],i=o==null?void 0:o.find(u=>u===s.label||u===s.name),d=i?o.indexOf(i):-1;function c(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(Qi,{idx:d,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function l(){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(Ji,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&l()]})}function Xi({field:s,searchQuery:n="",limit:r=500}){const{authToken:o,tokenProps:i}=a.useSemaphorContext(),d=t.useDashboardStore(m=>{var b;return((b=m.reportContext)==null?void 0:b.calendar)??null}),c=t.useEditorStore(m=>m.card),l=c==null?void 0:c.dataSource,u=["attribute-values",s.entityName,s.name,n,r,d],x=a.useQuery({queryKey:u,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const m={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:r},b={connection_id:l.connectionId,cardConfig:m,cardDataSource:l,cache_config:t.getCacheConfig({card:c}),calendarContext:d};console.log("requestBody",b);const h=await t.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",b);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=s.name;return((h==null?void 0:h.records)||[]).map(N=>{const f=N[p]||N[s.alias||p]||N[s.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},enabled:!!s&&!!(l!=null&&l.connectionId)&&!!d,staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:x.data||[],isLoading:x.isLoading,isFetching:x.isFetching,isError:x.isError,error:x.error,refetch:x.refetch}}const Zi=new Set;function Ra({open:s,onOpenChange:n,availableFields:r,existingFilters:o,editingCondition:i,onSave:d}){const c=!!i,[l,u]=v.useState(c?"values":"fields"),[x,m]=v.useState(""),[b,h]=v.useState({id:(i==null?void 0:i.id)||je.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),p=r.filter(I=>{var S;return c?!1:!((S=o==null?void 0:o.conditions)==null?void 0:S.some(M=>M.field.id===I.id))}),j=I=>{h({...b,field:I}),u("values")},N=()=>{if(b.field&&b.selectedValues.length>0){const I={id:b.id,field:b.field,operator:"in",value:b.selectedValues};let w;if(c){const S=((o==null?void 0:o.conditions)||[]).map(M=>M.id===i.id?I:M);w={...o,conditions:S}}else{const S=(o==null?void 0:o.conditions)||[];w={id:(o==null?void 0:o.id)||je.v4(),logicalOperator:"AND",negate:!1,conditions:[...S,I],groups:[]}}d(w),n(!1)}},f=()=>{if(!c||!i)return;const I=((o==null?void 0:o.conditions)||[]).filter(w=>w.id!==i.id);if(I.length>0){const w={...o,conditions:I};d(w)}else d(void 0);n(!1)},g=I=>{h({...b,selectedValues:I})},D=()=>{c&&i?(h({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),u("values")):(h({id:je.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return v.useEffect(()=>{s&&D()},[s,c,i]),e.jsx(a.Dialog,{open:s,onOpenChange:n,children:e.jsxs(a.DialogContent,{className:"max-w-2xl",children:[e.jsx(a.DialogHeader,{children:e.jsx(a.DialogTitle,{children:c?`Edit Filter: ${b.field?a.getFieldDisplayLabel(b.field):""}`:l==="fields"?"Select Field to Filter":`Select Values for ${b.field?a.getFieldDisplayLabel(b.field):""}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&l==="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(I=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[a.getFieldDisplayLabel(I.field),":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(I.value)?`${I.value.length} values`:String(I.value)})]},I.id))})]}),l==="fields"&&!c?e.jsx("div",{className:"flex flex-col",children:e.jsx(a.FieldOptionList,{fields:p,selectedIds:Zi,onSelect:j,query:x,onQueryChange:m,density:"compact",listLabel:"Filterable fields",listClassName:"max-h-[400px]",autoFocusSearch:!0,emptyMessage:x?`No fields found matching "${x}"`:r.length>0?"All available fields are already filtered":void 0})}):e.jsx(ec,{field:b.field,selectedValues:b.selectedValues,onValuesChange:g,onBack:c?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(t.Button,{variant:"destructive",onClick:f,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:D,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:N,disabled:!b.field||b.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function ec({field:s,selectedValues:n,onValuesChange:r,onBack:o}){const[i,d]=v.useState(""),{values:c,isLoading:l,isFetching:u}=Xi({field:s,searchQuery:i,limit:500}),x=i?c.filter(h=>String(h.value).toLowerCase().includes(i.toLowerCase())):c,m=h=>{const p=n.includes(h);r(p?n.filter(j=>j!==h):[...n,h])},b=()=>{n.length===x.length&&x.length>0?r([]):r(x.map(h=>h.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 ",a.getFieldDisplayLabel(s)]})]}),e.jsxs("div",{className:"relative",children:[e.jsx($e.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:i,onChange:h=>d(h.target.value),className:"pl-10"})]}),l||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(a.Checkbox,{checked:n.length===x.length&&x.length>0,onCheckedChange:b}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(a.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(Vs,{className:"text-sm",children:h.label})]},h.id))})]})]})}function tc(s,n){return s==="pivotBy"&&(n==="table"||n==="pivotTable")}const sc=[];function nc({field:s,zone:n,index:r,sortDirection:o,onSortDirectionChange:i,hasPivotColumns:d=!1,cardType:c}){var Us,Gs,Hs,Qs,Js,Ws,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;const l=t.useEditorStore(G=>G.card),u=t.useEditorStore(G=>G.frame),x=t.useDashboardStore(G=>G.isVisualEditing),m=t.useDashboardStore(G=>G.selectedSheetId),b=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),h=t.useDashboardStore(G=>G.actions.updateDashboardCalculatedFields),j=t.useDashboardStore(G=>{var Ee;return G.visualEditPendingDashboardCalculatedFields??((Ee=G.dashboard)==null?void 0:Ee.calculatedFields)})??sc,{scopedFields:N,valuePickFilterableFields:f,isLoading:g,hasError:D}=a.useFilterableFields(),{userContext:I}=a.useCurrentUserInfo(),{tokenProps:w}=a.useSemaphorContext(),S=a.canEditLocalCalculatedFields(I),M=a.useTimezone()??void 0,A=a.useResolvedTemporalStylePreferences()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES,{updateLabel:F,handleAggregationChange:E,handleDetailDateFormatChange:C,handleDimensionFormatChange:T,handleTemporalBucketFormatChange:L,handleGranularityChange:k,handleAliasTemplateChange:R,handlePivotMemberOrderChange:y,handleValueAliasesChange:_,handleMetricFormatChange:O,removeField:P,handleMetricComparisonChange:B,handleMetricComparisonSpecChange:Y,handleMetricComparisonPolarityChange:q,handleMetricWindowTransformChange:z,handleMetricWindowOrderByChange:V,handleMetricWindowDirectionChange:$,handleMetricWindowPartitionToggle:Q,handleMetricMovingAverageWindowSizeChange:U,handleMetricMovingAverageMinPeriodsChange:J,handleMetricPreviousPeriodDeltaModeChange:W,handleMetricPercentOfTotalScopeChange:ee,handleMetricPercentOfTotalOutputChange:ue,handleMetricTargetValueChange:fe}=a.useFieldManagement(l),[be,ge]=v.useState(!1),[Pe,Oe]=v.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[ke,Te]=v.useState(!1),[_e,ze]=v.useState(!1),[Be,Ae]=v.useState(null),Me=v.useMemo(()=>{const G=de=>de!=null&&de.startsWith("card-source-")?de.replace("card-source-",""):de,Ee=G(s.id),X=N.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 Ne=G(de.id);return!!(Ee&&Ne&&Ee===Ne)});return{dataType:(X==null?void 0:X.dataType)||s.dataType,resolvedFromScopedField:!!X}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,N]),ae=a.getGranularityOptionsForFieldType(Me.dataType),K=v.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=n==="groupBy"?K.ok&&ae.includes(K.granularity)?K.granularity:void 0:ae.includes(s.granularity)?s.granularity:"day",Ce=K.ok?K.selection:{value:"auto",customPattern:"",format:et.AUTOMATIC_TEMPORAL_BUCKET_FORMAT},[re,he]=v.useState(n==="groupBy"?Ce.value:s.dateFormat||"YYYY-MM-DD"),[Ye,Z]=v.useState(n==="groupBy"?Ce.customPattern:s.customFormat||""),Fe=re==="custom",[me,qe]=v.useState(s.aliasTemplate||""),[Le,Ke]=v.useState(s.valueAliases||{}),[Se,oe]=v.useState((Us=s.parameters)==null?void 0:Us.filters),Ie=G=>{var X;if(n==="groupBy"&&!ie)return;const Ee=ie??"day";if(G==="custom"){const de=n==="groupBy"?et.getTemporalBucketAuthoringOptions(Ee,Ce.format,A).find(Ge=>Ge.value==="custom"):void 0,Ne=n==="groupBy"?Ye||(((X=de==null?void 0:de.format)==null?void 0:X.presentation.mode)==="pattern"?de.format.presentation.pattern:""):Ye;he(G),Z(Ne),n==="groupBy"&&L(r,et.resolveTemporalBucketAuthoringFormat(Ee,G,Ne))}else he(G),n==="groupBy"?L(r,et.resolveTemporalBucketAuthoringFormat(Ee,G)):n==="detailColumns"&&C(r,G,"")},Re=G=>{if(n==="groupBy"&&!ie)return;const Ee=ie??"day";Z(G),n==="groupBy"?L(r,et.resolveTemporalBucketAuthoringFormat(Ee,"custom",G)):n==="detailColumns"&&C(r,"custom",G)},De=G=>{if(n==="groupBy"){const Ee=et.reconcileTemporalBucketAuthoringFormat(Ce.format,G),X=t.readTemporalBucketAuthoringSelection({fieldId:s.id,dataType:s.dataType,granularity:G,format:Ee,semanticTemporalPresentation:s.semanticTemporalPresentation});he(X.value),Z(X.customPattern),k(r,G)}},te=G=>{qe(G),n==="metrics"&&R(r,G)},ve=G=>{n==="pivotBy"&&y(r,G)},ye=G=>{Ke(G),n==="metrics"&&_(r,G)},Qe=G=>{F(n,r,G)},st=a.getExpressionFieldKind(s);a.getFieldExpressionAnnotation(s);const ut=a.isManagedCalculatedExpressionField(s),it=s.role==="metric"&&ut,kt=ut&&(st==="user_calculated"||st==="inline_expression"&&s.fieldScope!=="domain"),nt=kt?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(u==null?void 0:u.calculatedFields)||[],dashboardFields:j}):void 0,vt=kt&&(nt==null?void 0:nt.scope)==="sheet",Gt=kt&&(nt==null?void 0:nt.scope)==="dashboard",mt=st==="domain_calculated"||s.fieldScope==="domain",Ht=mt?a.resolveDomainCalculatedFieldForEdit(s,N):void 0,ht=mt?"domain":vt?"sheet":Gt?"dashboard":"card",yt=mt?Ht||s:(vt||Gt)&&(nt!=null&&nt.matchedField)?nt.matchedField:s,Bt=mt?Ht?"effective":g?"loading":D?"unavailable":"unverified":void 0,Mt=G=>{var Ee;if(oe(G),n==="metrics"){const X={...s,parameters:{...s.parameters,filters:G}},de=[...((Ee=l.config)==null?void 0:Ee.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:de})}Te(!1)},Vt=()=>{P(n,r)},Ct=t.getDataType(Me.dataType||s.dataType),pt=Ct==="date",Qt=c==="kpi",At=n==="detailColumns",Jt=(Gs=l.config)==null?void 0:Gs.metricColumns,xt=(Hs=l.config)==null?void 0:Hs.groupByColumns,Nt=a.useCardQueryContext(l),Lt=t.useDashboardStore(G=>G.semanticExecutionPayload),_t=n==="groupBy"&&ie?et.getTemporalBucketAuthoringOptions(ie,Ce.format,A):n==="detailColumns"?$i(ie??"day"):[],is=Fe?"custom":!ie&&n==="groupBy"?void 0:_t.some(G=>G.value===re)?re:((Qs=_t[0])==null?void 0:Qs.value)??"YYYY-MM-DD",Wt=!!c&&a.COMPARISON_SUPPORTED_CHART_TYPES.includes(c),cs=!!c&&a.COMPARISON_TARGET_SUPPORTED_CHART_TYPES.includes(c),St=v.useMemo(()=>xt==null?void 0:xt.find(G=>t.getDataType(G.dataType||"")==="date"),[xt]),ct=v.useMemo(()=>t.resolveCardPrimaryDateField({card:l,cardConfig:l.config||{},semanticExecutionPayload:Lt}),[l,Lt]),Je=v.useMemo(()=>St||(ct?{...ct,id:`semantic-primary:${ct.entityId}:${ct.name}`,label:ct.name,role:"groupby",granularity:ct.defaultGranularity||"day"}:void 0),[St,ct]),H=je.getAuthoredCardFilters(l),ne=v.useMemo(()=>{if(!Je)return!1;const G=H;if(!G)return!1;const Ee=de=>{const Ne=de.field;return Ne?Je.id&&Ne.id===Je.id||Je.qualifiedFieldName&&Ne.qualifiedFieldName===Je.qualifiedFieldName?!0:Ne.name===Je.name:!1},X=de=>de.conditions.some(Ge=>t.getDataType(Ge.field.dataType||"")==="date"&&Ee(Ge))?!0:de.groups.some(Ge=>X(Ge));return X(G)},[H,Je]),se=v.useMemo(()=>zi(l,a.compileDashboardCardFilters({card:l,cardConfig:Nt.queryRelevantConfig,input:Nt.filterCompilationInput,resolvedFields:Nt.resolvedDateFields,semanticExecutionPayload:Lt,timezone:M})),[l,Nt,Lt,M]),we=ne||se,ce=s,pe=((Js=ce.comparison)==null?void 0:Js.mode)==="explicit"?ce.comparison.spec:void 0,Ue=((Xs=(Ws=ce.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.function)||"none",Ve=a.isMetricTransformEnabled(ce),He=Ve?Ue:null,ft=a.supportsMetricTransformForMetric({cardType:c||"table",cardConfig:l.config||{},metric:ce,transformMode:He||"running_total"}),dt=((Zs=ce.comparison)==null?void 0:Zs.mode)==="explicit",We=a.getRunningTotalOrderByCandidates(xt||[]),rt=((sn=(tn=(en=ce.parameters)==null?void 0:en.windowTransform)==null?void 0:tn.orderBy)==null?void 0:sn.fieldId)||"",ds=((rn=(an=(nn=ce.parameters)==null?void 0:nn.windowTransform)==null?void 0:an.orderBy)==null?void 0:rn.direction)||"asc",Xt=We.find(G=>G.id===rt),us=He==="running_total"||He==="moving_average"||He==="previous_period_delta",Ya=Ve&&us&&!!Xt&&t.getDataType(Xt.dataType||"")!=="date",za=a.getDefaultRunningTotalPartitionByFieldIds({cardType:c||"table",cardConfig:l.config||{},orderByFieldId:rt||void 0}),qa=new Set(((ln=(on=ce.parameters)==null?void 0:on.windowTransform)==null?void 0:ln.partitionByFieldIds)||za),$a=c==="pivotTable"||a.isSubtotalEnabledAggregateTable(c||"table",l.config||{}),zs=[...(xt||[]).filter(G=>G.id&&(!us||G.id!==rt)),...$a?(((cn=l.config)==null?void 0:cn.pivotByColumns)||[]).filter(G=>G.id):[]],qs=((mn=(un=(dn=ce.parameters)==null?void 0:dn.windowTransform)==null?void 0:un.movingAverage)==null?void 0:mn.windowSize)||7,Ka=((pn=(hn=(xn=ce.parameters)==null?void 0:xn.windowTransform)==null?void 0:hn.movingAverage)==null?void 0:pn.minPeriods)||1,Ua=((bn=(gn=(fn=ce.parameters)==null?void 0:fn.windowTransform)==null?void 0:gn.previousPeriodDelta)==null?void 0:bn.mode)||"absolute",$s=((yn=(vn=(jn=ce.parameters)==null?void 0:jn.windowTransform)==null?void 0:vn.percentOfTotal)==null?void 0:yn.scope)||"grand_total",Ga=((Sn=(Nn=(Cn=ce.parameters)==null?void 0:Cn.windowTransform)==null?void 0:Nn.percentOfTotal)==null?void 0:Sn.output)||"percent",Ha=v.useMemo(()=>(Jt||[]).some(()=>!1),[Jt]);v.useEffect(()=>{Ve&&Oe(!0)},[Ve]);const Qa=n!=="pivotBy"&&n!=="sortBy",Ja=tc(n,c),Wa=s.memberOrder??"auto",Xa=pt&&n==="groupBy"&&(!Qt||Ha),Za=!Qt&&pt&&(n==="groupBy"||At),er=n==="metrics",tr=!Qt&&Ct==="number"&&(n==="groupBy"||At)&&a.isTableNumericPresentationCardType(c),Zt=Wt&&!l.sql&&!l.python&&n==="metrics",sr=()=>{const G=s,Ee=n==="metrics"&&it;return e.jsxs("div",{className:"space-y-1",children:[!Ee&&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}`}),Ee&&G.calculatedFormula&&e.jsxs("div",{title:a.formatDisplayFormula(G.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:["= ",a.formatDisplayFormula(G.calculatedFormula)]})]})},nr=()=>Qa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(lt,{value:s.label??"",onSave:Qe,placeholder:"Display label...",type:"text"})]}):null,ar=()=>n!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:o||"asc",onValueChange:G=>i(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),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:Wa,onValueChange:G=>ve(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"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,Ks=()=>Xa?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:De,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:ae.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,or=()=>Za?e.jsxs(e.Fragment,{children:[Ks(),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:is,onValueChange:Ie,disabled:n==="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:_t.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),Fe&&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:Ye,onChange:G=>{G.stopPropagation(),Re(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,lr=()=>tr?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(Es,{value:s.format,onChange:G=>T(At?"detailColumns":"groupBy",r,G),cardType:c,showTitle:!1})]}):null,ir=()=>{var Ee;if(!er)return null;const G=it;return e.jsxs(e.Fragment,{children:[G&&S&&!mt&&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:()=>ze(!0),children:[e.jsx(a.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=>{E(r,X)},disabled:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsx(t.SelectContent,{children:et.getFieldAggregationOptions(s.dataType).map(X=>e.jsx(t.SelectItem,{className:"text-xs",value:X.value,children:X.label},X.value))})]})]}),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(Es,{value:ce.format,onChange:X=>O(r,X),cardType:c,showTitle:!1})]}),e.jsx(a.Collapsible,{open:Pe,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(a.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:[!Pe&&e.jsx("span",{className:"mr-2",children:Ve?t.toTitleCase(Ue.replace(/_/g," ")):"None"}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Pe?"rotate-180":"")})]})]})}),e.jsxs(a.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:Ve?Ue:"none",onValueChange:X=>z(r,X),disabled:!ft.supported&&!Ve,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:dt,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:dt,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:dt,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:dt,children:"Percent of Total"})]})]}),!ft.supported&&!Ve&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ft.reason}),dt&&!Ve&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Ve&&e.jsxs(e.Fragment,{children:[us&&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:rt,onValueChange:X=>V(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:We.filter(X=>!!X.id).map(X=>e.jsx(t.SelectItem,{value:X.id,className:"text-xs",children:X.label||X.name},X.id))})]}),!rt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Ya&&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:ds,onValueChange:X=>$(r,X),disabled:!rt,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"})]})]})]})]}),He==="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:qs,onChange:X=>U(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:qs,className:"h-8 text-xs",value:Ka,onChange:X=>J(r,Number(X.target.value))})]}),He==="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:Ua,onValueChange:X=>W(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"})]})]})]}),He==="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:$s,onValueChange:X=>ee(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=>ue(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"})]})]})]})]}),(He==="running_total"||He==="moving_average"||He==="previous_period_delta"||He==="percent_of_total"&&$s==="partition_total")&&zs.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:zs.map(X=>{const de=!!X.id&&qa.has(X.id);return e.jsxs("button",{type:"button",onClick:()=>X.id&&Q(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)})})]})]})]})]})}),Zt&&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:ce.comparison?ce.comparison.mode==="off"?"off":ce.comparison.spec.kind:"inherit",disabled:Ve,onValueChange:X=>B(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=!Je||!we,de=Je?we?void 0:"Add a date filter to enable":"Configure a semantic primary date or add a date axis",Ne=(Ge,Ze)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ge,disabled:X,title:de,children:Ze})}),X&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[Ne("previous_period","Previous Period"),Ne("previous_year","Previous Year")]})})(),cs&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]}),!ce.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."})]}),Zt&&pe&&(pe.kind==="previous_period"||pe.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:pe.kind==="previous_year"?"Years back":"Periods back"}),e.jsx(t.Input,{type:"number",min:1,step:1,value:pe.kind==="previous_year"?pe.offsetYears||1:pe.offsetPeriods||1,onChange:X=>{const de=Number(X.target.value);!Number.isSafeInteger(de)||de<=0||(pe.kind==="previous_year"?Y(r,{...pe,offsetYears:de===1?void 0:de}):Y(r,{...pe,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:pe.alignment||"calendar",onValueChange:X=>Y(r,{...pe,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:pe.toDate===!0,onCheckedChange:X=>Y(r,{...pe,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:(Je==null?void 0:Je.label)||(Je==null?void 0:Je.name)}),". The resolved comparison dates appear after the card runs."]})]}),Zt&&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:a.getMetricComparisonPolarity(ce),disabled:!!ce.semanticComparisonPolarity,onValueChange:X=>q(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"})]})]}),ce.semanticComparisonPolarity&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Governed by this metric's semantic definition."})]}),Zt&&((Ee=ce.comparison)==null?void 0:Ee.mode)==="explicit"&&ce.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:ce.comparison.spec.targetValue!==void 0&&ce.comparison.spec.targetValue!==null?String(ce.comparison.spec.targetValue):"",onChange:X=>{const de=X.target.value;if(de===""){fe(r,void 0);return}const Ne=Number(de);fe(r,Number.isFinite(Ne)?Ne:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(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:()=>{Ae(X),Te(!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,Ne)=>e.jsx("div",{children:String(de)},Ne))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var Ge;de.stopPropagation();const Ne=Se.conditions.filter(Ze=>Ze.id!==X.id);if(Ne.length>0){const Ze={...Se,conditions:Ne};Mt(Ze)}else if(oe(void 0),n==="metrics"){const Ze={...s,parameters:{...s.parameters,filters:void 0}},ot=[...((Ge=l.config)==null?void 0:Ge.metricColumns)||[]];ot[r]=Ze,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:ot})}},children:e.jsx(le.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:()=>{Ae(null),Te(!0)},children:[e.jsx(a.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Wi,{column:s}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ki,{aliasTemplate:me,onAliasTemplateChange:te}),e.jsx(Ui,{valueAliases:Le,onValueAliasesChange:ye})]})]})};Se!=null&&Se.conditions&&Se.conditions.length>0;const cr=n!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsx(Fa,{id:s.id,label:a.getMetricDisplayLabel(s),dataType:Ct,calculated:a.getCalculatedGlyphKind(s),open:be,onOpenChange:ge,onRemove:Vt,sortDirection:o,onSortDirectionChange:n==="sortBy"?i:void 0,badge:e.jsx(e.Fragment,{children:n==="metrics"&&((wn=Se==null?void 0:Se.conditions)==null?void 0:wn.length)&&!be&&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(a.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})})}),children:cr&&e.jsxs(e.Fragment,{children:[sr(),ar(),rr(),nr(),c==="kpi"&&Ks(),or(),lr(),ir()]})}),ke&&e.jsx(Ra,{open:ke,onOpenChange:G=>{Te(G),G||Ae(null)},availableFields:f,existingFilters:Se,editingCondition:Be,onSave:G=>{var Ee;if(G)Mt(G);else if(oe(void 0),n==="metrics"){const X={...s,parameters:{...s.parameters,filters:void 0}},de=[...((Ee=l.config)==null?void 0:Ee.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:de})}Ae(null)}}),_e&&n==="metrics"&&it&&e.jsx(a.CalculatedFieldEditor,{open:_e,onOpenChange:ze,availableFields:N,existingField:yt,existingFieldScope:ht,domainDefinitionStatus:Bt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=ht==="dashboard"?j:X.calculatedFields||[],{cardConfigPatch:Ge,nextStoredFields:Ze,nextSharedFields:ot}=a.saveCalculatedFieldToCardScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sharedFields:Ne,updatedField:G,editingField:yt,previousScope:ht});Object.keys(Ge).length&&de.updateCardConfig(l.id,Ge),de.updateCard(l.id,{calculatedFields:Ze}),ht==="dashboard"&&ot!==Ne?h(ot):ot!==Ne&&a.commitSharedCalculatedFields({nextSharedFields:ot,currentSharedFields:Ne,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b})},onSaveToSheet:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=s,Ge=X.calculatedFields||[],{cardConfigPatch:Ze,nextStoredFields:ot,nextSheetFields:ms,nextDashboardFields:wt}=a.saveCalculatedFieldToSheetScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sheetFields:Ge,dashboardFields:j,updatedField:{...G,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:yt,previousScope:ht});a.commitSharedCalculatedFields({nextSharedFields:ms,currentSharedFields:Ge,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),wt&&wt!==j&&h(wt),Object.keys(Ze).length&&de.updateCardConfig(l.id,Ze),de.updateCard(l.id,{calculatedFields:ot})},onSaveToDashboard:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=s,Ge=X.calculatedFields||[],{cardConfigPatch:Ze,nextStoredFields:ot,nextSharedFields:ms,nextSheetFields:wt}=a.saveCalculatedFieldToSharedScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sharedFields:j,sheetFields:Ge,updatedField:{...G,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:yt,previousScope:ht});h(ms),wt&&wt!==Ge&&a.commitSharedCalculatedFields({nextSharedFields:wt,currentSharedFields:Ge,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),Object.keys(Ze).length&&de.updateCardConfig(l.id,Ze),de.updateCard(l.id,{calculatedFields:ot})},cardId:l.id})]})}function ac({field:s,onRemove:n}){const[r,o]=v.useState(!1);return e.jsx(Fa,{id:s.id,label:a.getMetricDisplayLabel(s),dataType:s.dataType,calculated:a.getCalculatedGlyphKind(s),open:r,onOpenChange:o,onRemove:n,children:e.jsx(Is,{fieldId:s.id})})}function rc({concept:s}){const{title:n,description:r}=oc[s];return e.jsxs(a.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${n} 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(a.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(a.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:n}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(lc,{highlight:s})]})]})}const oc={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 lc({highlight:s}){const n=s==="pivotBy",r=s==="groupBy",o=s==="metrics",i="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(d=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",n&&i),children:d},d))]})}),e.jsx("tbody",{children:Zn.map((d,c)=>e.jsxs("tr",{className:t.cn(c!==Zn.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&&i),children:d.label}),d.values.map((l,u)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&i),children:l},u))]},d.label))})]})})}const Zn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],ic={groupBy:a.Rows3,pivotBy:Ds,metrics:Mr,detailColumns:t.Table2,sortBy:sa};function zt({onRemoveField:s,zone:n,fields:r,label:o,placeholder:i,shouldShow:d,hasPivotColumns:c=!1,activeField:l=null}){const{isOver:u,setNodeRef:x}=a.useDroppable({id:n}),{updateSortByColumn:m}=t.useEditorActions(),b=t.useEditorStore(D=>D.card),h=t.useEditorStore(D=>D.card.type),p=r.length>0,j=v.useMemo(()=>!l||!u?!0:a.validateFieldForChartType(l,n,h).isValid,[l,u,n,h]),N=(D,I)=>{var S;!((S=b.config)!=null&&S.sortByColumns)||b.config.sortByColumns.findIndex(M=>M.id===D)===-1||m(b.id,D,{direction:I})};if(n==="sortBy"&&d===!1)return null;const f=n!=="sortBy"&&h!=="kpi",g=ic[n]||a.Plus;return e.jsxs("div",{className:"w-full",role:"group","aria-label":o,children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsx("div",{ref:x,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":u&&j,"border border-destructive/40 bg-destructive/5":u&&!j,"border border-dashed border-border/50 bg-background":!u&&!p}),children:r.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(g,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:i}),f&&e.jsx(rc,{concept:n})]}):e.jsx(a.SortableContext,{id:n,items:r.map(D=>D.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:r.map((D,I)=>{const S=D.direction;return h==="matrixTable"?e.jsx(ac,{field:D,onRemove:()=>s(n,I)},D.id):e.jsx(nc,{field:D,zone:n,index:I,sortDirection:S,onSortDirectionChange:M=>N(D.id,M),hasPivotColumns:c,cardType:h},D.id)})})})})]})}const cc=[];function dc({onRemoveField:s,onResetFields:n,groupByFields:r,pivotByFields:o,metricsFields:i,sortByFields:d,detailFields:c,activeField:l}){var Q,U,J;const[u,x]=v.useState(!1);t.useEditorStore(W=>{var ee;return!!((ee=W.card.customCardPreferences)!=null&&ee.url)});const m=t.useEditorStore(W=>W.card),b=t.useEditorStore(W=>W.frame),h=xe.findCustomVisualConfigCard(b,m),{manifest:p}=a.useCustomVisual(((Q=h==null?void 0:h.customCardPreferences)==null?void 0:Q.url)||""),j=(U=p==null?void 0:p.visuals)==null?void 0:U.find(W=>{var ee;return W.name===((ee=h==null?void 0:h.customCardPreferences)==null?void 0:ee.componentName)}),N=xe.resolveMultiInputType(h,j)==="multiple";N&&((J=h==null?void 0:h.customCardPreferences)!=null&&J.url);const f=xe.getConfigSlotExpectedType(j==null?void 0:j.slots);t.useEditorStore(W=>W.actions.updateCardConfig);const g=t.useEditorStore(W=>W.actions.updateCard),D=t.useEditorStore(W=>W.actions.updateFrame),I=t.useDashboardStore(W=>W.isVisualEditing),w=t.useDashboardStore(W=>W.selectedSheetId),S=t.useDashboardStore(W=>W.actions.updateSheetCalculatedFields),M=t.useDashboardStore(W=>W.actions.updateDashboardCalculatedFields),F=t.useDashboardStore(W=>{var ee;return W.visualEditPendingDashboardCalculatedFields??((ee=W.dashboard)==null?void 0:ee.calculatedFields)})??cc,{scopedFields:E}=a.useScopedFields(),{userContext:C}=a.useCurrentUserInfo(),T=N&&(h==null?void 0:h.id)===m.id&&f?f:m==null?void 0:m.type,L=T==="detailTable",k=r.length>0||i.length>0||c.length>0,R=!L&&(T!=="kpi"||i.length<=2),y=!L,_=!L&&T!=="kpi",O=T!=="kpi"&&T!=="matrixTable"&&k,P=L,B="Drop sort fields here",Y=a.canEditLocalCalculatedFields(C),q=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),z=_&&!q,V=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},$=()=>T==="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"}),k&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:n,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:[R&&e.jsx(zt,{zone:"groupBy",onRemoveField:s,fields:r,label:V().label,placeholder:V().placeholder,activeField:l}),z&&e.jsx(zt,{zone:"pivotBy",onRemoveField:s,fields:o,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:l}),y&&e.jsx(zt,{zone:"metrics",onRemoveField:s,fields:i,label:$().label,placeholder:$().placeholder,hasPivotColumns:o.length>0,activeField:l}),P&&e.jsx(zt,{zone:"detailColumns",onRemoveField:s,fields:c,label:"Columns",placeholder:"Drop columns here"}),i.length>=1&&Y&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>x(!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(a.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),O&&e.jsx(zt,{zone:"sortBy",onRemoveField:s,fields:d,label:"Sort By",placeholder:B,activeField:l})]}),e.jsx(a.CalculatedFieldEditor,{open:u,onOpenChange:x,availableFields:E,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:W=>{if(W.role!=="metric")return;const{nextStoredFields:ee}=a.saveCalculatedFieldToCardScope({storedFields:m.calculatedFields||[],sharedFields:b.calculatedFields||[],updatedField:W,previousScope:"card"});g(m.id,{calculatedFields:ee})},onSaveToSheet:W=>{if(W.role!=="metric")return;const ee=b.calculatedFields||[],{nextSheetFields:ue}=a.saveCalculatedFieldToSheetScope({storedFields:m.calculatedFields||[],sheetFields:ee,updatedField:W,previousScope:"sheet"});a.commitSharedCalculatedFields({nextSharedFields:ue,currentSharedFields:ee,isVisualEditing:I,selectedSheetId:w,updateFrame:D,updateSheetCalculatedFields:S})},onSaveToDashboard:W=>{if(W.role!=="metric")return;const{nextSharedFields:ee}=a.saveCalculatedFieldToSharedScope({storedFields:m.calculatedFields||[],sharedFields:F,updatedField:W,previousScope:"dashboard"});M(ee)},cardId:m.id})]})}function uc(){var D,I,w;const s=t.useEditorStore(S=>{var M;return(M=S.card)==null?void 0:M.type}),n=s==="kpi",[r,o]=v.useState(n),[i,d]=v.useState(!1),c=t.useEditorStore(S=>{var M;return!!((M=S.card.customCardPreferences)!=null&&M.url)}),l=t.useEditorStore(S=>S.card),u=t.useEditorStore(S=>S.frame),x=xe.findCustomVisualConfigCard(u,l),{manifest:m}=a.useCustomVisual(((D=x==null?void 0:x.customCardPreferences)==null?void 0:D.url)||""),b=(I=m==null?void 0:m.visuals)==null?void 0:I.find(S=>{var M;return S.name===((M=x==null?void 0:x.customCardPreferences)==null?void 0:M.componentName)}),p=xe.resolveMultiInputType(x,b)==="multiple"&&!!((w=x==null?void 0:x.customCardPreferences)!=null&&w.url),j=!c||p,N=c||p,f=n?"KPI Settings":"Chart Settings",g=j&&!a.isTableChartType(s);return v.useEffect(()=>{n&&o(!0)},[n]),!g&&!N?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[g&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",n?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(a.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(La,{mode:"config"})})}),g&&e.jsxs("button",{type:"button",onClick:()=>o(S=>!S),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(a.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:f})]}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),N&&i&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Ta,{})}),N&&e.jsxs("button",{type:"button",onClick:()=>d(S=>!S),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",g&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(na,{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(le.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",i&&"rotate-180"),strokeWidth:1.75})]})]})}function mc({onEditJoins:s}){const n=t.useEditorStore(u=>u.card),{autoJoinMetadata:r}=a.useEditorCardQuery(n);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,i=(o==null?void 0:o.joins)||[];if(i.length===0)return null;const d=u=>!u||u.length===0?"No conditions":u.map(x=>{var p,j,N,f;const m=`${(p=x.source)==null?void 0:p.entityName}.${(j=x.source)==null?void 0:j.name}`,b=`${(N=x.target)==null?void 0:N.entityName}.${(f=x.target)==null?void 0:f.name}`,h=x.operator||"=";return`${m} ${h} ${b}`}).join(" AND "),c=u=>!u.joinKeyGroups||u.joinKeyGroups.length===0?"No conditions defined":u.joinKeyGroups.length===1?d(u.joinKeyGroups[0].keys):u.joinKeyGroups.map((x,m)=>({id:m,operator:x.operator,condition:d(x.keys)})),l=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":`${i.length} resolved ${i.length===1?"join":"joins"}`,children:i.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:i.map((u,x)=>{const m=c(u),b=Array.isArray(m);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(a.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:b?m.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},u.id||x)})})})]})});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(a.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"}),l,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(a.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function xc({onRemoveField:s,onResetFields:n,selectedChart:r,onChartChange:o,isVisible:i=!0,onToggleVisibility:d,groupByFields:c,pivotByFields:l,metricsFields:u,sortByFields:x,detailFields:m,activeField:b}){var E;const[h,p]=v.useState(!1),j=t.useEditorStore(C=>C.card),N=t.useEditorStore(C=>C.editorContext),f=t.useEditorStore(C=>C.actions.updateCardConfig),g=(N==null?void 0:N.type)==="documentSection",{autoJoinMetadata:D}=a.useEditorCardQuery(j),I=je.getAuthoredCardJoinPlan(j)||(D!=null&&D.autoResolved?D.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),w=((E=j==null?void 0:j.dataSource)==null?void 0:E.selectedEntities)||[],S=C=>{f(j.id,je.withAuthoredCardJoinPlan(j,C)),p(!1)},M=()=>{f(j.id,je.withAuthoredCardJoinPlan(j,void 0)),p(!1)},A=()=>{p(!1)},F=()=>{p(!0)};return i?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:[!g&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Vo,{selectedChart:r,onChartChange:o})}),d&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(a.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:d,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(a.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(mc,{onEditJoins:F})}),e.jsx(dc,{onRemoveField:s,onResetFields:n,groupByFields:c,pivotByFields:l,metricsFields:u,sortByFields:x,detailFields:m,activeField:b})]}),e.jsx(uc,{}),e.jsx(ra,{open:h,onOpenChange:p,joinPlan:I,availableDataSources:w,onSave:S,onCancel:A,onRemove:M,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:d&&e.jsx(a.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:d,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx($e.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function hc({initialFilters:s,availableFields:n}={}){const[r,o]=v.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(w=>w.card.dataSource);const{filterableFields:i,isLoading:d}=a.useFilterableFields(),c=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const S=M=>{if(M.id===w){const A=c[0]||l,F=t.getDataType(A.dataType)==="date";return{...M,conditions:[...M.conditions,{id:`condition-${Date.now()}`,field:A,operator:F?"between":"=",value:F?[]:""}]}}return{...M,groups:M.groups.map(S)}};o(S(r))},x=w=>{const S=M=>{if(M.id===w){const A=c[0]||l,F=t.getDataType(A.dataType)==="date";return{...M,groups:[...M.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:A,operator:F?"between":"=",value:F?[]:""}],groups:[]}]}}return{...M,groups:M.groups.map(S)}};o(S(r))},m=(w,S)=>{const M=A=>A.id===w?{...A,conditions:A.conditions.filter(F=>F.id!==S)}:{...A,groups:A.groups.map(M)};o(M(r))},b=(w,S)=>{const M=A=>A.id===w?{...A,groups:A.groups.filter(F=>F.id!==S)}:{...A,groups:A.groups.map(M)};o(M(r))},h=(w,S,M,A)=>{if(M==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const F=E=>E.id===w?{...E,conditions:E.conditions.map(C=>C.id===S?{...C,[M]:A}:C)}:{...E,groups:E.groups.map(F)};o(F(r))},p=(w,S,M)=>{const A=F=>F.id===w?{...F,conditions:F.conditions.map(E=>E.id===S?{...E,...M}:E)}:{...F,groups:F.groups.map(A)};o(A(r))},j=(w,S)=>{const M=A=>A.id===w?{...A,logicalOperator:S}:{...A,groups:A.groups.map(M)};o(M(r))},N=(w,S)=>{const M=A=>A.id===w?{...A,negate:S}:{...A,groups:A.groups.map(M)};o(M(r))},f=(w,S,M)=>{const A=F=>F.id===w?{...F,conditions:a.arrayMove(F.conditions,S,M)}:{...F,groups:F.groups.map(A)};o(A(r))},g=(w,S,M)=>{const A=F=>F.id===w?{...F,groups:a.arrayMove(F.groups,S,M)}:{...F,groups:F.groups.map(A)};o(A(r))},D=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const S=A=>{let F="";typeof A.field=="object"?F=A.field.entityName?`${A.field.entityName}.${A.field.name}`:A.field.name:F=String(A.field);const E=A.operator;let C=A.value;if(A.field.dataType==="string"&&!["in","not in"].includes(A.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(A.field.dataType==="date"||A.field.dataType==="datetime"||A.field.dataType==="timestamp")if(A.operator==="between"&&Array.isArray(C)&&C.length===2){const T=C[0]?`'${C[0]}'`:"NULL",L=C[1]?`'${C[1]}'`:"NULL";return`${F} BETWEEN ${T} AND ${L}`}else if((A.operator==="in"||A.operator==="not in")&&Array.isArray(C)){const T=C.map(L=>L?`'${L}'`:"NULL").join(", ");return`${F} ${E} (${T})`}else typeof C=="string"||C instanceof Date?C=`'${C}'`:Array.isArray(C)&&C.length>0&&(C=`'${C[0]}'`);else if(["in","not in"].includes(A.operator)){let T=[];Array.isArray(C)?T=C.map(L=>typeof L=="string"?`'${L}'`:String(L)):typeof C=="string"?T=C.split(",").map(L=>{const k=L.trim();return A.field.dataType==="string"?`'${k}'`:k}):typeof C=="number"&&(T=[String(C)]),C=`(${T.join(", ")})`}switch(E){case"contains":return typeof C=="string"?`${F} LIKE '%${C.replace(/'/g,"")}'`:`${F} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${F} LIKE '${C.replace(/'/g,"")}%'`:`${F} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${F} LIKE '%${C.replace(/'/g,"")}'`:`${F} LIKE '%${String(C)}'`;case"isNull":return`${F} IS NULL`;case"isNotNull":return`${F} IS NOT NULL`;default:return`${F} ${E} ${C}`}},M=A=>{const F=A.conditions.map(S),E=A.groups.map(k=>M(k)),C=[...F,...E].filter(Boolean);if(C.length===0)return"";const T=C.join(` ${A.logicalOperator} `),L=C.length>1?`(${T})`:T;return A.negate?`NOT ${L}`:L};return M(w)},I=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:m,removeGroup:b,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:N,reorderConditions:f,reorderGroups:g,generateSQLPreview:D,hasAnyFilters:I}}function pc({children:s,className:n,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",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function fc({value:s,onValueChange:n,availableFields:r,placeholder:o="Select field",className:i}){const[d,c]=v.useState(!1),l=v.useMemo(()=>new Set(s?[s.id]:[]),[s]),u=s?a.getFieldDisplayLabel(s):null;return e.jsxs(t.Popover,{modal:!0,open:d,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,title:s?`${s.entityName}.${s.name}`:void 0,className:t.cn("min-w-0 justify-between gap-1.5 font-normal",!s&&"text-muted-foreground",i),children:[u?e.jsx(pc,{className:"w-auto min-w-0 flex-1 text-left text-[12px]",children:u}):e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:o}),e.jsx(a.ChevronsUpDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"flex w-80 flex-col rounded-control p-1.5",align:"start",onOpenAutoFocus:x=>{var m,b;x.preventDefault(),(b=(m=x.currentTarget)==null?void 0:m.querySelector('input[type="text"]'))==null||b.focus()},children:e.jsx(a.FieldOptionList,{fields:r,selectedIds:l,onSelect:x=>{n(x),c(!1)},density:"compact",listLabel:"Fields",listClassName:"max-h-80"})})]})}function Pa(s){const n=t.useEditorStore(c=>c.card.dataSource),r=t.useEditorStore(c=>c.card.connectionId),o=t.useEditorStore(c=>c.selectedConnectionId),i=v.useMemo(()=>({id:`card-filter-option:${s.id}`,...ya(s,{dataSource:n,connectionId:o||(n==null?void 0:n.connectionId)||r})}),[r,n,s,o]),d=v.useMemo(()=>a.createExplicitDashboardInputTargetContext({filter:i}),[i]);return a.useFilterOptionBrowse(i,{inputContext:d,currentSelectionPolicy:"exclude"})}function gc({field:s,selected:n,onChange:r,placeholder:o="Select values…",className:i}){const[d,c]=ss.useState(!1),l=Pa(s),u=ss.useMemo(()=>new Set(n.map(h=>a.getFilterOptionValueIdentity(h))),[n]),x=h=>{var p,j;return((j=(p=l.allRecords.find(N=>a.getFilterOptionValueIdentity(N.value)===a.getFilterOptionValueIdentity(h)))==null?void 0:p.label)==null?void 0:j.toString())??h},m=h=>{r(n.filter(p=>p!==h))},b=h=>{c(h),!h&&l.query&&l.setQuery("")};return e.jsx("div",{className:t.cn("w-full",i),children:e.jsxs(t.Popover,{open:d,onOpenChange:b,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,className:"h-auto min-h-7 w-full justify-between gap-1.5 px-2 py-0.5 font-normal",children:[e.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap gap-1",children:n.length>0?n.map(h=>{const p=x(h);return e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-[4px] border border-border/70 bg-muted/40 px-1.5 py-0.5 text-[11px] leading-[14px] text-foreground",children:[e.jsx("span",{className:"truncate",children:p}),e.jsx("span",{role:"button",tabIndex:0,"aria-label":`Remove ${p}`,className:"shrink-0 rounded-[2px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring",onKeyDown:j=>{j.key==="Enter"&&m(h)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),m(h)},children:e.jsx(le.X,{className:"h-3 w-3"})})]},h)}):e.jsx("span",{className:"truncate text-muted-foreground",children:o})}),e.jsx(le.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:h=>{var p,j;h.preventDefault(),(j=(p=h.currentTarget)==null?void 0:p.querySelector('input[type="text"]'))==null||j.focus()},children:e.jsx(a.FilterOptionList,{records:l.displayRecords,selectedIdentities:u,onToggle:h=>{const p=String(h.value);n.includes(p)?m(p):r([...n,p])},browse:l,searchPlaceholder:`Search ${(s.label||s.name).toLowerCase()}`,listLabel:s.label||s.name,density:"compact"})})]})})}function bc({field:s,value:n,onChange:r,placeholder:o="Select value…",className:i}){var b,h;const[d,c]=ss.useState(!1),l=Pa(s),u=ss.useMemo(()=>new Set(n?[a.getFilterOptionValueIdentity(n)]:[]),[n]),x=n?((h=(b=l.allRecords.find(p=>a.getFilterOptionValueIdentity(p.value)===a.getFilterOptionValueIdentity(n)))==null?void 0:b.label)==null?void 0:h.toString())??n:"",m=p=>{c(p),!p&&l.query&&l.setQuery("")};return e.jsxs(t.Popover,{open:d,onOpenChange:m,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,className:t.cn("min-w-0 flex-1 justify-between gap-1.5 px-2 font-normal",i),children:[e.jsx("span",{className:t.cn("truncate",!n&&"text-muted-foreground"),children:n?x:o}),e.jsx(le.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:p=>{var j,N;p.preventDefault(),(N=(j=p.currentTarget)==null?void 0:j.querySelector('input[type="text"]'))==null||N.focus()},children:e.jsx(a.FilterOptionList,{records:l.displayRecords,selectedIdentities:u,onToggle:p=>{r(String(p.value)),m(!1)},selectionMode:"single",browse:l,searchPlaceholder:`Search ${(s.label||s.name).toLowerCase()}`,listLabel:s.label||s.name,density:"compact"})})]})}function jc({value:s,operator:n,onChange:r,className:o}){const i=a.useTimezone(),d=n==="between"||n==="not between",c=v.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=s[0]?new Date(s[0]):void 0,h=s[1]?new Date(s[1]):void 0;if(b&&h)return{from:b,to:h}}},[s,d]),l=v.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;if(!b)return;const h=new Date(b);if(!isNaN(h.getTime()))return h},[s,d]),u=b=>n==="<="||n===">"?t.endOfDayInTimezone(b,i):t.startOfDayInTimezone(b,i),x=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},m=b=>{if(!b){r("");return}const h=u(b);r(h.toISOString())};return e.jsx(a.DateRangePicker,{value:d?c:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:l,onChange:x,onSingleChange:m,timezone:i,showRelativeTab:d,className:t.cn("min-w-0",o),buttonClassName:"h-7 text-[12px] [&>span]:text-[12px]",placeholder:"Select date…"})}const _s=["contains","startsWith","endsWith","like","not like"],vc=["=","!=",">",">=","<","<=",..._s,"in","not in","isNull","isNotNull"],yc=["=","!=",..._s,"in","not in","isNull","isNotNull"],Cc=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Nc=["=","!=","isNull","isNotNull"],Sc=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],wc={"=":"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 ws(s){return wc[s]||t.titleCase(s)}function Tc(s){switch(s){case"string":return yc;case"number":return Cc;case"boolean":return Nc;case"date":return Sc;default:return vc}}const Oa="w-[68px] shrink-0",Ys="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Ba({value:s,onValueChange:n,"aria-label":r}){return e.jsxs(t.Select,{value:s,onValueChange:o=>n(o),children:[e.jsx(t.SelectTrigger,{size:"xs","aria-label":r,className:t.cn(Oa,"font-medium"),children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{className:"min-w-[var(--radix-select-trigger-width)]",children:[e.jsx(t.SelectItem,{value:"AND",className:"text-[12px] font-medium",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",className:"text-[12px] font-medium",children:"OR"})]})]})}function Va({condition:s,index:n,groupId:r,groupLogicalOperator:o,onUpdateCondition:i,onRemoveCondition:d,onUpdateGroupOperator:c,availableFields:l,updateConditionFields:u}){const{attributes:x,listeners:m,setNodeRef:b,transform:h,transition:p,isDragging:j}=a.useSortable({id:s.id}),N={transform:a.CSS.Transform.toString(h),transition:p},f=t.getDataType(s.field.dataType),g=s.operator==="isNull"||s.operator==="isNotNull",D=s.operator==="in"||s.operator==="not in";return e.jsxs("div",{ref:b,style:N,className:t.cn("flex items-center gap-2 rounded-control px-1.5 py-1 transition-colors hover:bg-muted/40",j&&"z-50 opacity-50"),children:[e.jsx("button",{type:"button",...x,...m,"aria-label":"Drag to reorder condition",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:e.jsx(a.GripVertical,{className:"h-3.5 w-3.5"})}),n>0?e.jsx(Ba,{value:o,onValueChange:I=>c(r,I),"aria-label":"Logical operator"}):e.jsx("span",{className:t.cn(Oa,"text-center",Ys),children:"Where"}),e.jsx(fc,{value:s.field,onValueChange:I=>{const w=I,S=t.getDataType(w.dataType)==="date";u(r,s.id,{field:w,value:"",operator:S?"between":"="})},availableFields:l,placeholder:"Select field",className:"w-60 shrink-0"}),e.jsxs(t.Select,{value:s.operator,onValueChange:I=>{I==="in"||I==="not in"?u(r,s.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?u(r,s.id,{operator:I,value:null}):I==="between"||I==="not between"?u(r,s.id,{operator:I,value:[]}):u(r,s.id,{operator:I,value:""})},children:[e.jsx(t.SelectTrigger,{size:"xs","aria-label":"Operator",className:"w-40 shrink-0",children:e.jsx(t.SelectValue,{children:s.operator?ws(s.operator):""})}),e.jsx(t.SelectContent,{children:Tc(f).map(I=>e.jsx(t.SelectItem,{value:I,children:ws(I)},I))})]}),g?e.jsx("div",{className:"min-w-0 flex-1"}):f==="string"?D?e.jsx(gc,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(I=>typeof I=="string")?s.value:[],onChange:I=>u(r,s.id,{value:I}),placeholder:"Select values…",className:"min-w-0 flex-1"}):_s.includes(s.operator)?e.jsx(t.Input,{size:"xs",value:typeof s.value=="string"?s.value:"",onChange:I=>u(r,s.id,{value:I.target.value}),className:"min-w-0 flex-1",placeholder:`${ws(s.operator)}…`}):e.jsx(bc,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:I=>u(r,s.id,{value:I}),placeholder:"Select value…",className:"min-w-0 flex-1"}):f==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:I=>u(r,s.id,{value:I==="true"}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"min-w-0 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"})]})]}):f==="date"?e.jsx(jc,{value:s.value,operator:s.operator,onChange:I=>u(r,s.id,{value:I}),className:"min-w-0 flex-1"}):e.jsx(t.Input,{size:"xs",value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:I=>i(r,s.id,"value",I.target.value),className:"min-w-0 flex-1",placeholder:D?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"xs","aria-label":"Remove condition",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(r,s.id),children:e.jsx(le.X,{className:"h-3.5 w-3.5"})})]})}function _a({onAddCondition:s,onAddGroup:n}){return e.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[e.jsxs(t.Button,{type:"button",size:"xs",variant:"outline",className:"gap-1.5",onClick:s,children:[e.jsx(a.Plus,{className:"h-3 w-3"}),"Add condition"]}),n&&e.jsxs(t.Button,{type:"button",size:"xs",variant:"ghost",className:"gap-1.5 text-muted-foreground hover:text-foreground",onClick:n,children:[e.jsx(a.Plus,{className:"h-3 w-3"}),"Add group"]})]})}function Ec({group:s,depth:n,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:i,onRemoveGroup:d,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:u,onReorderConditions:x,onReorderGroups:m,onAddCondition:b,onAddGroup:h,availableFields:p,renderFilterGroup:j,updateConditionFields:N}){const{attributes:f,listeners:g,setNodeRef:D,transform:I,transition:w,isDragging:S}=a.useSortable({id:s.id}),M={transform:a.CSS.Transform.toString(I),transition:w},A=E=>{const{active:C,over:T}=E;if(T&&C.id!==T.id){const L=s.conditions.findIndex(R=>R.id===C.id),k=s.conditions.findIndex(R=>R.id===T.id);L!==-1&&k!==-1&&x(s.id,L,k)}},F=E=>{const{active:C,over:T}=E;if(T&&C.id!==T.id&&r){const L=s.groups.findIndex(R=>R.id===C.id),k=s.groups.findIndex(R=>R.id===T.id);L!==-1&&k!==-1&&m(r,L,k)}};return e.jsxs("div",{ref:D,style:M,className:t.cn(n>0&&"mt-2 overflow-hidden rounded-[6px] border border-border/60",S&&"z-50 opacity-50"),children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-2 py-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",...f,...g,"aria-label":"Drag to reorder group",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:e.jsx(a.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsx(t.Button,{type:"button",variant:s.negate?"default":"outline",size:"xs","aria-pressed":s.negate,className:"px-2",onClick:()=>i(s.id,!s.negate),children:"NOT"}),e.jsx(Ba,{value:s.logicalOperator,onValueChange:E=>o(s.id,E),"aria-label":"Group logical operator"}),e.jsx("span",{className:Ys,children:"Group"})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"xs","aria-label":"Remove group",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>r&&d(r,s.id),children:e.jsx(a.Trash2,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:t.cn(n>0&&"p-2"),children:[e.jsx(a.DndContext,{sensors:a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),collisionDetection:a.closestCenter,onDragEnd:A,children:e.jsx(a.SortableContext,{items:s.conditions.map(E=>E.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-0.5",children:s.conditions.map((E,C)=>e.jsx(Va,{condition:E,index:C,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:u,onUpdateGroupOperator:o,availableFields:p,updateConditionFields:N},E.id))})})}),e.jsx(a.DndContext,{sensors:a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),collisionDetection:a.closestCenter,onDragEnd:F,children:e.jsx(a.SortableContext,{items:s.groups.map(E=>E.id),strategy:a.verticalListSortingStrategy,children:s.groups.map(E=>j(E,n+1,s.id))})}),s.conditions.length===0&&s.groups.length===0&&e.jsx("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No conditions in this group."}),e.jsx(_a,{onAddCondition:()=>b(s.id),onAddGroup:()=>h(s.id)})]})]})}function Ic({filters:s,availableFields:n,onSave:r,onClearAll:o,onCancel:i}){const{currentFilters:d,availableFields:c,isLoading:l,addCondition:u,addGroup:x,removeCondition:m,removeGroup:b,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:N,reorderConditions:f,reorderGroups:g,generateSQLPreview:D,hasAnyFilters:I,setCurrentFilters:w}=hc({initialFilters:s,availableFields:n}),S=a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),[M,A]=v.useState(!1),F=(T,L,k)=>{const R=y=>y.id===T?{...y,conditions:y.conditions.map(_=>_.id===L?{..._,field:k,dataType:k.dataType}:_)}:{...y,groups:y.groups.map(R)};w(R(d))},E=(T,L=0,k)=>{if(L===0){const R=T.conditions.length===0&&T.groups.length===0;return e.jsxs("div",{children:[e.jsx(a.DndContext,{sensors:S,collisionDetection:a.closestCenter,onDragEnd:y=>{const{active:_,over:O}=y;if(O&&_.id!==O.id){const P=T.conditions.findIndex(Y=>Y.id===_.id),B=T.conditions.findIndex(Y=>Y.id===O.id);P!==-1&&B!==-1&&f(T.id,P,B)}},children:e.jsx(a.SortableContext,{items:T.conditions.map(y=>y.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-0.5",children:T.conditions.map((y,_)=>e.jsx(Va,{condition:y,index:_,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:h,onUpdateField:F,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:p},y.id))})})}),e.jsx(a.DndContext,{sensors:S,collisionDetection:a.closestCenter,onDragEnd:y=>{const{active:_,over:O}=y;if(O&&_.id!==O.id){const P=T.groups.findIndex(Y=>Y.id===_.id),B=T.groups.findIndex(Y=>Y.id===O.id);P!==-1&&B!==-1&&g(T.id,P,B)}},children:e.jsx(a.SortableContext,{items:T.groups.map(y=>y.id),strategy:a.verticalListSortingStrategy,children:T.groups.map(y=>E(y,L+1,T.id))})}),R&&e.jsx("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No filters yet. Add a condition to limit the rows this card shows."}),e.jsx(_a,{onAddCondition:()=>u(T.id),onAddGroup:M?()=>x(T.id):void 0})]},T.id)}return e.jsx(Ec,{group:T,depth:L,parentGroupId:k,onUpdateGroupOperator:j,onUpdateGroupNegate:N,onRemoveGroup:b,onUpdateCondition:h,onUpdateField:F,onRemoveCondition:m,onReorderConditions:f,onReorderGroups:g,onAddCondition:u,onAddGroup:x,availableFields:c,renderFilterGroup:E,updateConditionFields:p},T.id)},C=a.getFilterCount(s);return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:[l?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-[12px] text-muted-foreground",children:[e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Loading columns…"]}):E(d),e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-border/60 pt-3",children:[e.jsx(t.Switch,{size:"xs",id:"advanced-mode",checked:M,onCheckedChange:T=>A(T)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-[12px] font-normal leading-none text-foreground",children:"Advanced mode"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Nest conditions in groups"})]}),I&&e.jsxs("div",{className:"mt-3 border-t border-border/60 pt-3",children:[e.jsx("div",{className:t.cn("mb-1.5",Ys),children:"Where clause"}),e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words rounded-[6px] border border-border bg-muted/40 px-3 py-2 font-mono text-[12px] leading-[1.55] text-foreground",children:D(d)})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-3 py-2.5",children:[e.jsx("div",{children:C>0&&e.jsx(t.Button,{size:"xs",variant:"ghost",className:"text-muted-foreground hover:text-foreground",onClick:o,children:"Clear all"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Button,{size:"xs",variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(t.Button,{size:"xs",onClick:()=>r(I?d:null),children:"Apply filters"})]})]})]})}function Dc({cardId:s,filters:n,onFiltersChange:r,onClearFilters:o,availableFields:i,isOpen:d,onOpenChange:c}){const l=x=>{r(s,x),c(!1)},u=()=>{o(s),c(!1)};return e.jsxs(a.Dialog,{modal:!1,open:d,onOpenChange:c,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-zinc-950/40 backdrop-blur-sm"}),e.jsxs(a.DialogContent,{className:"flex max-h-[80vh] w-[min(880px,92vw)] max-w-none flex-col gap-0 overflow-hidden p-0 [&>button:last-child]:top-3",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border pl-3 pr-10",children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx(a.DialogTitle,{className:"truncate text-[13px] font-medium",children:"Card filters"}),e.jsx(a.DialogDescription,{className:"sr-only",children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Ic,{filters:n,availableFields:i,onSave:l,onCancel:()=>c(!1),onClearAll:u})]})]})}function kc({activeCardId:s,sourceFields:n,getFieldsForContainer:r,setFieldsForContainer:o,moveField:i}){const[d,c]=v.useState(null),l=t.useEditorStore(f=>f.card),u=t.useEditorStore(f=>f.actions.updateCardConfig),x=t.useEditorStore(f=>f.actions.setCardPreferences),m=a.useFieldAvailabilityContext(l),b=[...n,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],h=v.useCallback(f=>f.startsWith("card-source-")?"source":f.startsWith("card-")?null:f.startsWith("source-")||n.find(g=>g.id===f)?"source":r("groupBy").find(g=>g.id===f)?"groupBy":r("metrics").find(g=>g.id===f)?"metrics":r("pivotBy").find(g=>g.id===f)?"pivotBy":r("sortBy").find(g=>g.id===f)?"sortBy":r("detailColumns").find(g=>g.id===f)?"detailColumns":null,[n,r]),p=v.useCallback(f=>{c(f.active.id)},[]),j=v.useCallback(f=>{const{active:g,over:D}=f;if(!D||!s){c(null);return}const I=g.id,w=D.id,S=h(I),M=h(w)||w;if(I===w){c(null);return}const A=S==="source"?n.find(F=>F.id===I):S?r(S).find(F=>F.id===I):void 0;if(A&&S&&(i!=null&&i({field:A,from:S,to:M,...w!==M?{beforeId:w}:{}}))){c(null);return}if(M==="sortBy"){if(S==="source"){const F=n.find(C=>C.id===I);if(!F){c(null);return}if(!(r("groupBy").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName)||r("metrics").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName)||r("detailColumns").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName))){c(null);return}}else if(S==="pivotBy"){c(null);return}else if(S!=="groupBy"&&S!=="metrics"&&S!=="sortBy"&&S!=="detailColumns"){c(null);return}}if(S==="source"&&M==="sortBy"){const F=[...n].find(L=>L.id===I);if(!F){c(null);return}const E=r("sortBy");if(a.fieldAlreadyExists(F,E)){c(null);return}const C=a.validateFieldForChartType(F,"sortBy",l.type);if(!C.isValid){t.ue.error("Invalid Field Type",{description:C.reason,position:"top-center",duration:3e3}),c(null);return}const T=a.getNewField(F,"sortBy",E);c(null),o("sortBy",[...E,T]);return}if(S==="source"&&M!=="source"&&M!=="sortBy"){const F=[...n].find(y=>y.id===I);if(!F){c(null);return}const E=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],C=a.validateEntityConsistency(F,E,m);if(!C.isValid){C.showError&&a.showJoinRequiredNotification(C.fieldState),c(null);return}const T=r(M);if(a.fieldAlreadyExists(F,T)){c(null);return}const L=a.validateFieldForChartType(F,M,l.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),c(null);return}const k=a.getNewField(F,M,T),R=[...T,k];if(c(null),o(M,R),M==="metrics"&&s){const y=a.seedSemanticMetricFormatDefaults(l,k,l.preferences);y&&x(y),a.cleanupKpiMetricComparisonMode(l.type,l.config,u,s,R)}return}if(S&&M&&S!=="source"&&M!=="source"&&S!==M){const F=r(S),E=r(M),C=F.find(y=>y.id===I);if(!C){c(null);return}const T=a.validateFieldForChartType(C,M,l.type);if(!T.isValid){t.ue.error("Invalid Field Type",{description:T.reason,position:"top-center",duration:3e3}),c(null);return}const L=a.getNewField(C,M,E);if(c(null),M==="sortBy"){a.fieldAlreadyExists(C,E)||o(M,[...E,L]);return}const k=F.filter(y=>y.id!==I),R=[...E,L];if(o(S,k),o(M,R),M==="metrics"&&s){const y=a.seedSemanticMetricFormatDefaults(l,L,l.preferences);y&&x(y),a.cleanupKpiMetricComparisonMode(l.type,l.config,u,s,R)}return}if(S&&M&&S===M&&S!=="source"){const F=r(S),E=F.findIndex(T=>T.id===I),C=F.findIndex(T=>T.id===w);if(E!==C){const T=a.arrayMove(F,E,C);o(S,T)}}c(null)},[s,n,r,o,i,h,m,l,u,x]),N=d?b.find(f=>f.id===d):null;return{activeId:d,activeField:N,handleDragStart:p,handleDragEnd:j}}function Mc({activeView:s,onViewChange:n,splitViewEnabled:r,hasQueryError:o=!1}){const i=t.useEditorStore(x=>x.card),{config:d}=v.useContext(a.SemaphorContext).tokenProps,c=(d==null?void 0:d.showInfoTab)!==!1,l=()=>r?!1:t.getVisualizationMode(i)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(i.type),u=[{id:"chart",label:"Chart"}];return l()&&u.push({id:"table",label:"Results"}),c&&u.push({id:"info",label:o?"Error":"Info",isError:o}),e.jsx(t.Tabs,{value:s,onValueChange:x=>n(x),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:u.map(x=>e.jsx(t.TabsTrigger,{value:x.id,className:t.cn("px-0 text-[13px]",x.isError&&"text-destructive hover:text-destructive focus-visible:text-destructive data-[state=active]:border-destructive data-[state=active]:text-destructive"),children:x.label},x.id))})})}const Ac=[{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 Lc(){var u,x;const s=t.useEditorStore(m=>m.card),{updateRowLimit:n}=t.useEditorActions(),[r,o]=v.useState(!1),[i,d]=v.useState(""),c=m=>{if(m==="custom"){o(!0);return}o(!1),n(s.id,parseInt(m))},l=m=>{const b=m.target.value;d(b),b&&!isNaN(parseInt(b))&&n(s.id,parseInt(b))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:i,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(u=s.config)==null?void 0:u.rowLimit)==null?void 0:x.toString())||"100",onValueChange:c,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(a.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:Ac.map(m=>e.jsx(t.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Fc({card:s,queryData:n,isLoading:r,isFetching:o,pagination:i,onPaginationChange:d,onSortChange:c,sortState:l,splitViewEnabled:u,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:m}){var j,N;const b=v.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),h=t.getVisualizationMode(s)==="dynamic",p=e.jsx(It,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Na,{fallbackPreview:e.jsx(It,{}),records:b,title:s.title,isInspectorOpen:x,onInspectorOpenChange:m})});return h?u?e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(a.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:p}),e.jsx(a.ResizableHandle,{withHandle:!0}),e.jsx(a.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)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(a.TableVisual,{card:s,data:b,resultColumns:n==null?void 0:n.columns,columnKeyMap:n==null?void 0:n.columnKeyMap,totalsByColumnId:n==null?void 0:n.tableTotalsByColumnId,comparisonMetadata:(j=n==null?void 0:n.metadata)==null?void 0:j.comparisonMetadata,paginationMetadata:i,onPaginationChange:d,isLoading:r||o,onSortChange:c,sortState:l})]})})]}):p:!u||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(It,{}):e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(a.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(It,{})}),e.jsx(a.ResizableHandle,{withHandle:!0}),e.jsx(a.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)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(a.TableVisual,{card:s,data:b,resultColumns:n==null?void 0:n.columns,columnKeyMap:n==null?void 0:n.columnKeyMap,totalsByColumnId:n==null?void 0:n.tableTotalsByColumnId,comparisonMetadata:(N=n==null?void 0:n.metadata)==null?void 0:N.comparisonMetadata,paginationMetadata:i,onPaginationChange:d,isLoading:r||o,onSortChange:c,sortState:l})]})})]})}function Rc(s,n){const[r,o]=v.useState(()=>{const i=localStorage.getItem(s);return i?JSON.parse(i):n});return v.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const Pc="semaphor-split-view-enabled";function Oc(){return Rc(Pc,!0)}function Bc({showInfoTab:s}){return e.jsx(a.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 Vc({card:s,effectiveCardType:n=s.type,queryResultColumns:r}){return a.supportsRegularTableSettings(n)?e.jsxs(a.Sheet,{modal:!1,children:[e.jsx(a.SheetTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"Table settings",className:"h-7 w-7 rounded-[5px] p-0",buttonProps:{type:"button","aria-label":"Table settings"},children:e.jsx(a.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),e.jsxs(a.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(a.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(a.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(Aa,{cardType:n,queryResultColumns:r,focusSection:"style"})})]})]}):null}function _c({className:s,visible:n}){const r=t.useDashboardStore(l=>l.selectedFrameId),o=a.useManagementStore(l=>l.selectedVisual),i=t.useEditorStore(l=>l.frame),c=!!!(i!=null&&i.visualId||o!=null&&o.id)&&!!r;return!n||c?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(jt.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Yc({activeView:s,onViewChange:n,onFiltersClick:r,activeCard:o,columns:i}){var Me;const d=t.useEditorStore(ae=>ae.card),c=t.useEditorStore(ae=>ae.editorContext),l=t.useEditorStore(ae=>ae.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),u=t.useEditorStore(ae=>ae.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ae=>ae.filterValues),m=t.useDashboardStore(ae=>ae.selectedSheetId),{updateCardConfig:b,setCard:h,updateCardInFrame:p,setShowAIDialog:j}=t.useEditorActions(),N=t.useEditorStore(ae=>ae.showAIDialog),f=t.useEditorStore(ae=>ae.isDevMode),g=t.useDashboardStore(ae=>ae.isVisualEditing),[D,I]=v.useState(!1),[w,S]=v.useState(!1),[M,A]=v.useState(!1),[F,E]=v.useState(null),{config:C}=v.useContext(a.SemaphorContext).tokenProps,T=(C==null?void 0:C.showInfoTab)!==!1,L=(C==null?void 0:C.showQueryDebugTools)!==!1,[k,R]=Oc();t.useEditorStore(ae=>{var K;return!!((K=ae.card.customCardPreferences)!=null&&K.url)});const _=t.getVisualizationMode(d)==="dynamic",O=(c==null?void 0:c.type)==="documentSection",P=a.useEffectiveEditorCardType(),{data:B,errorMessage:Y,isLoading:q,isFetching:z,errorSql:V,pagination:$,refetch:Q,comparisonMetadata:U,queryRequestPayload:J,resolvedPrimaryDateField:W}=a.useEditorCardQuery(o),ee=v.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),ue=v.useMemo(()=>!z&&ee.length>0?Object.keys(ee[0]):[],[z,ee]),[fe,be]=v.useState(!1),ge=a.useMatrixEditorRefresh(o),Pe=t.useEditorStore(ae=>ae.frame),[Oe,ke]=v.useState();v.useEffect(()=>{z||be(!1)},[z]);const Te=()=>{const ae=!k;ae&&s==="table"&&n("chart"),R(ae)},_e=(ae,K)=>{const ie={...o,paginationConfig:{page:ae+1,pageSize:K}};h(ie),p(ie)},ze=ae=>{if(!d.config)return;const K=a.sortStateToSortByColumns(ae,d.config.metricColumns,d.config.groupByColumns,d.config.detailColumns);b(d.id,{...d.config,sortByColumns:K})},Be=v.useMemo(()=>{var ae;return a.sortByColumnsToSortState((ae=d.config)==null?void 0:ae.sortByColumns)},[(Me=d.config)==null?void 0:Me.sortByColumns]),Ae=a.getFilterCount(je.getAuthoredCardFilters(o)||null);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":N&&g}),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"&&N&&!O&&!_&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Bo,{variant:f?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(Mc,{activeView:s,onViewChange:n,splitViewEnabled:k,hasQueryError:!!Y}),!a.isTableType(P)&&e.jsx(Lc,{})]}),P==="kpi"&&e.jsx(_c,{visible:!0,className:"self-center"}),U&&d.type!=="table"&&e.jsx(a.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),N&&e.jsx(jt.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(a.FilterInfo,{cardId:o.id,cardFilters:je.getAuthoredCardFilters(o),cardFilterCount:Ae,onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:l,sheetId:m||"",removeInlineFilterValue:ae=>u(o.id,ae),resolvedPrimaryDateField:W}),s==="chart"&&e.jsx(Vc,{card:o,effectiveCardType:P,queryResultColumns:ue}),s==="chart"&&!_&&e.jsx(Ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),e.jsx(a.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:q||z,onClick:()=>{var ae;if(ge){(ae=ge.refresh)==null||ae.call(ge);return}be(!0),Q()},children:e.jsx(Ts,{className:t.cn("h-3.5 w-3.5",{"animate-spin":(ge==null?void 0:ge.isFetching)??fe})})}),s==="chart"&&e.jsxs(a.DropdownMenu,{modal:!1,children:[e.jsx(a.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsxs(a.DropdownMenuItem,{onSelect:r,children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Card filters",Ae>0&&e.jsx("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:Ae})]}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),e.jsxs(a.DropdownMenuItem,{onClick:Te,children:[k?e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Fr,{className:"h-3.5 w-3.5 text-muted-foreground"}),k?"Hide results table":"Show results table"]}),ge&&e.jsxs(a.DropdownMenuItem,{disabled:ge.isFetching||!ge.hasDelivery,title:ge.hasDelivery?void 0:"Available once the preview has loaded.",onClick:()=>ke(ge.readDelivery()),children:[e.jsx(a.Download,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Download"]}),e.jsx(Sa,{onCustomize:()=>A(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"?Y?e.jsx(Bc,{showInfoTab:T}):e.jsx("div",{className:"flex grow flex-col",children:e.jsx(Fc,{card:o,queryData:B,isLoading:q,isFetching:z,pagination:$,onPaginationChange:_e,onSortChange:ze,sortState:Be,splitViewEnabled:k,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:A})}):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:[(q||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(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(a.TableVisual,{card:o,data:ee,resultColumns:B.columns,columnKeyMap:B.columnKeyMap,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:U,paginationMetadata:$,onPaginationChange:_e,isLoading:q||z,onSortChange:ze,sortState:Be})]}),s==="info"&&T&&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:V,showCardDetails:!0,defaultSqlExpanded:!0,debugPayloads:L?{queryRequest:J,queryResponse:B,columns:i,dashboardFilters:x}:void 0,onSendFeedback:()=>{const ae=a.prepareFeedbackData(a.FeedbackCategory.QUERY_GENERATION,{cardConfig:d.config,dataSource:o.dataSource,dashboardFilters:x,errorMessage:Y,errorSql:V,generatedSql:B==null?void 0:B.sql});E(ae),S(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const ae=t.useEditorStore.getState().actions;ae.setIsDevMode(!0),ae.setCardSql(V||""),setTimeout(()=>{ae.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(wa,{sql:B.sql,showCardDetails:!0,debugPayloads:L?{queryRequest:J,queryResponse:B,columns:i,dashboardFilters:x}:void 0})})})]}),Oe&&o&&Pe&&e.jsx(a.ExportDialog,{isOpen:!0,onClose:()=>ke(void 0),card:o,frame:Pe,matrix:Oe}),F&&e.jsx(a.FeedbackDialog,{open:w,onOpenChange:S,feedbackData:F})]})})}function zc({activeField:s}){const[n,r]=v.useState(!0);if(v.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=a.getCalculatedGlyphKind(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 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(a.TypeGlyph,{dataType:s.dataType,calculated:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const qc=()=>{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 n=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 i;if((i=o.reason)!=null&&i.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",n,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",r,!0)}};function $c({column:s,isSelected:n,onSelect:r,availableFields:o,width:i,onWidthChange:d}){var B,Y;const c=t.useEditorStore(q=>q.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:x,updateFilters:m}=t.useEditorActions(),[b,h]=v.useState(!1),[p,j]=v.useState(!1),N=v.useRef(null),f=v.useCallback(q=>{q.preventDefault(),q.stopPropagation(),j(!0),N.current={startX:q.clientX,startWidth:i||150};const z=$=>{if(!N.current)return;const Q=$.clientX-N.current.startX,U=Math.max(80,N.current.startWidth+Q);d==null||d(s.id,U)},V=()=>{j(!1),N.current=null,document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",V)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",V)},[i,s.id,d]),g=je.getAuthoredCardFilters(c),D=(B=g==null?void 0:g.conditions)==null?void 0:B.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),I=q=>{q?m(c.id,q):l(c.id,{filters:void 0})},{attributes:w,listeners:S,setNodeRef:M,transform:A,transition:F,isDragging:E}=a.useSortable({id:s.id}),C={transform:a.CSS.Transform.toString(A),transition:F},T=t.getDataType(s.dataType),L=Kc(T),k=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.sortByColumns)||[],z=q.findIndex($=>$.name===s.name);if(z!==-1){const $=[...q];$[z]={...$[z],direction:"asc"},l(c.id,{sortByColumns:$})}else l(c.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.sortByColumns)||[],z=q.findIndex($=>$.name===s.name);if(z!==-1){const $=[...q];$[z]={...$[z],direction:"desc"},l(c.id,{sortByColumns:$})}else l(c.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},y=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.groupByColumns)||[];if(!q.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};l(c.id,{groupByColumns:[...q,$]})}},_=q=>{var $;const z=(($=c==null?void 0:c.config)==null?void 0:$.metricColumns)||[];if(!z.some(Q=>Q.name===s.name&&Q.aggregate===q)){const Q={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q,aggregateOrigin:"explicit"};l(c.id,{metricColumns:[...z,Q]})}},O=()=>{s.role==="groupby"?u(c.id,s.id):s.role==="metric"&&x(c.id,s.id)},P={...C,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:M,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",E&&"opacity-50",n&&"bg-primary/10",p&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...w,...S,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(a.GripVertical,{className:"h-3 w-3"})}),e.jsxs(a.DropdownMenu,{children:[e.jsx(a.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",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(L,{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,")"]}),D&&e.jsx(a.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(le.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(a.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(a.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(a.Filter,{className:t.cn("mr-2 h-4 w-4",D&&"text-primary")}),D?"Edit Filter":"Filter"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{onClick:k,children:[e.jsx(gr,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(a.DropdownMenuItem,{onClick:R,children:[e.jsx(fr,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuSub,{children:[e.jsxs(a.DropdownMenuSubTrigger,{children:[e.jsx(a.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(a.DropdownMenuSubContent,{children:[e.jsx(a.DropdownMenuItem,{onClick:()=>_("SUM"),children:"Sum"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("AVG"),children:"Average"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("COUNT"),children:"Count"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("DISTINCT"),children:"Count Distinct"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("MIN"),children:"Min"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("MAX"),children:"Max"})]})]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{onClick:y,children:[e.jsx(a.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(a.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{disabled:!0,children:[e.jsx(a.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(a.DropdownMenuItem,{onClick:O,className:"text-destructive focus:text-destructive",children:[e.jsx(a.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:f,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",p&&"bg-primary")}),e.jsx(Ra,{open:b,onOpenChange:h,availableFields:o.length>0?o:[s],existingFilters:g,editingCondition:D?(Y=g==null?void 0:g.conditions)==null?void 0:Y.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:I})]})}function Kc(s){switch(s){case"number":return a.Hash;case"date":return a.Calendar;case"string":default:return t.Type}}function Uc({selectedColumn:s,onColumnSelect:n,isLoading:r=!1,sourceFields:o=[],filterableFields:i=o}){var E,C,T,L;const d=t.useEditorStore(k=>k.card),{updateCardConfig:c}=t.useEditorActions(),[l,u]=v.useState(null),[x,m]=v.useState({}),[b,h]=v.useState(!1),p=v.useMemo(()=>{var y,_;const k=((y=d==null?void 0:d.config)==null?void 0:y.groupByColumns)||[],R=((_=d==null?void 0:d.config)==null?void 0:_.metricColumns)||[];return[...k,...R]},[(E=d==null?void 0:d.config)==null?void 0:E.groupByColumns,(C=d==null?void 0:d.config)==null?void 0:C.metricColumns]),j=v.useMemo(()=>{const k=new Set(p.map(R=>`${R.qualifiedEntityName}.${R.name}`));return o.filter(R=>!k.has(`${R.qualifiedEntityName}.${R.name}`))},[o,p]),{data:N,isLoading:f}=a.useEditorCardQuery(d),g=(N==null?void 0:N.records)||[],D=v.useCallback((k,R)=>{m(y=>({...y,[k]:R}))},[]),I=v.useCallback(k=>{var O,P;const R=t.getDataType(k.dataType),y=((O=d==null?void 0:d.config)==null?void 0:O.groupByColumns)||[],_=((P=d==null?void 0:d.config)==null?void 0:P.metricColumns)||[];if(R==="number"){const B=a.getNewField(k,"metrics",[...y,..._]);c(d.id,{metricColumns:[..._,B]})}else{const B=a.getNewField(k,"groupBy",[...y,..._]);c(d.id,{groupByColumns:[...y,B]})}h(!1)},[(T=d==null?void 0:d.config)==null?void 0:T.groupByColumns,(L=d==null?void 0:d.config)==null?void 0:L.metricColumns,d.id,c]),w=a.useSensors(a.useSensor(a.PointerSensor,{activationConstraint:{distance:8}})),S=k=>{u(k.active.id)},M=k=>{const{active:R,over:y}=k;if(u(null),!y||R.id===y.id)return;const _=p.findIndex(P=>P.id===R.id),O=p.findIndex(P=>P.id===y.id);if(_!==-1&&O!==-1){const P=a.arrayMove(p,_,O),B=P.filter(q=>q.role==="groupby"),Y=P.filter(q=>q.role==="metric");c(d.id,{groupByColumns:B,metricColumns:Y})}},A=l?p.find(k=>k.id===l):null,F=k=>{let R="";for(;k>=0;)R=String.fromCharCode(k%26+65)+R,k=Math.floor(k/26)-1;return R};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"})}):p.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(a.DndContext,{sensors:w,collisionDetection:a.closestCenter,onDragStart:S,onDragEnd:M,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(a.SortableContext,{items:p.map(k=>k.id),strategy:a.horizontalListSortingStrategy,children:p.map((k,R)=>e.jsx("th",{style:{width:x[k.id]?`${x[k.id]}px`:void 0,minWidth:x[k.id]?`${x[k.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:F(R)},`letter-${k.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(a.SortableContext,{items:p.map(k=>k.id),strategy:a.horizontalListSortingStrategy,children:p.map(k=>e.jsx($c,{column:k,isSelected:(s==null?void 0:s.id)===k.id,onSelect:()=>n(k),availableFields:i,width:x[k.id],onWidthChange:D},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:b,onOpenChange:h,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(a.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search columns..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No columns available."}),e.jsx(a.CommandGroup,{heading:"Available Columns",children:j.map(k=>{const R=t.getDataType(k.dataType),y=R==="number"?a.Hash:R==="date"?a.Calendar:t.Type;return e.jsxs(a.CommandItem,{value:k.label||k.name,onSelect:()=>I(k),children:[e.jsx(y,{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:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):g.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):g.slice(0,100).map((k,R)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",R%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:R+1}),p.map(y=>{const _=k[y.name]??k[y.label??""];return e.jsx("td",{style:{width:x[y.id]?`${x[y.id]}px`:void 0,minWidth:x[y.id]?`${x[y.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===y.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Gc(_,y)})},`${R}-${y.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(a.DragOverlay,{children:A&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:A.label||A.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(g.length,100)," of ",g.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function Gc(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Hc({entityGroups:s,isLoading:n=!1}){var I,w;const r=t.useEditorStore(S=>S.card),{updateCardConfig:o,removeGroupByColumn:i,removeMetricColumn:d}=t.useEditorActions(),[c,l]=v.useState(!0),[u,x]=v.useState(""),[m,b]=v.useState(new Set),h=((I=r==null?void 0:r.config)==null?void 0:I.groupByColumns)||[],p=((w=r==null?void 0:r.config)==null?void 0:w.metricColumns)||[],j=S=>{const M=new Set(m);M.has(S)?M.delete(S):M.add(S),b(M)},N=S=>h.some(M=>M.name===S.name&&M.qualifiedEntityName===S.qualifiedEntityName)||p.some(M=>M.name===S.name&&M.qualifiedEntityName===S.qualifiedEntityName),f=(S,M)=>{if(M)if(t.getDataType(S.dataType)==="number"){const F=a.getNewField(S,"metrics",[...h,...p]);o(r.id,{metricColumns:[...p,F]})}else{const F=a.getNewField(S,"groupBy",[...h,...p]);o(r.id,{groupByColumns:[...h,F]})}else{const A=h.findIndex(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName),F=p.findIndex(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName);A!==-1&&i(r.id,h[A].id),F!==-1&&d(r.id,p[F].id)}},g=S=>{if(!u)return S;const M=u.toLowerCase();return S.filter(A=>A.name.toLowerCase().includes(M)||A.label&&A.label.toLowerCase().includes(M))},D=S=>{switch(t.getDataType(S)){case"number":return a.Hash;case"date":return a.Calendar;default:return t.Type}};return c?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:()=>l(!1),title:"Close panel",children:e.jsx(Ir,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx($e.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:S=>x(S.target.value),className:"h-8 pl-8 text-sm"})]})}),(h.length>0||p.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.length>0&&e.jsxs(a.Collapsible,{defaultOpen:!0,children:[e.jsxs(a.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx($e.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(a.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:h.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(S=>{const M=D(S.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(a.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.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:()=>i(r.id,S.id),children:e.jsx(le.X,{className:"h-3 w-3"})})]},S.id)})})})]}),p.length>0&&e.jsxs(a.Collapsible,{defaultOpen:!0,children:[e.jsxs(a.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx($e.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(a.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:p.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(S=>{const M=D(S.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(a.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.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:()=>d(r.id,S.id),children:e.jsx(le.X,{className:"h-3 w-3"})})]},S.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(S=>{const M=g(S.columns);if(M.length===0)return null;const A=m.has(S.entityId)||u.length>0;return e.jsxs(a.Collapsible,{open:A,onOpenChange:()=>j(S.entityId),children:[e.jsxs(a.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($e.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",A&&"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:S.label||S.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:M.map(F=>{const E=D(F.dataType),C=N(F);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",C&&"bg-primary/5"),children:[e.jsx(a.Checkbox,{checked:C,onCheckedChange:T=>f(F,T),className:"h-3.5 w-3.5"}),e.jsx(E,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:F.label||F.name})]},F.id)})})})]},S.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:()=>l(!0),title:"Open panel",children:e.jsx(Dr,{className:"h-4 w-4"})})})}const Qc=[{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 Jc({value:s,onChange:n,onSubmit:r,onCancel:o,selectedColumn:i,availableColumns:d}){const[c,l]=v.useState(!1),[u,x]=v.useState("column"),m=v.useRef(null);v.useEffect(()=>{const j=N=>{N.key==="Escape"&&s?o():N.key==="Enter"&&s&&!c&&r(s)};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[s,o,r,c]);const b=j=>{const N=`[${j.label||j.name}]`,f=m.current;if(f){const g=f.selectionStart||0,D=f.selectionEnd||0,I=s.slice(0,g)+N+s.slice(D);n(I),setTimeout(()=>{f.setSelectionRange(g+N.length,g+N.length),f.focus()},0)}else n(s+N);l(!1)},h=j=>{const N=m.current;if(N){const f=N.selectionStart||0,g=N.selectionEnd||0,D=s.slice(0,f)+j.syntax+s.slice(g);n(D),setTimeout(()=>{N.setSelectionRange(f+j.name.length+1,f+j.syntax.length-1),N.focus()},0)}else n(s+j.syntax);l(!1)},p=j=>{switch(t.getDataType(j)){case"number":return a.Hash;case"date":return a.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:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:c&&u==="function",onOpenChange:j=>{l(j),j&&x("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(Lr,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search functions..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No functions found."}),e.jsx(a.CommandGroup,{heading:"Functions",children:Qc.map(j=>e.jsx(a.CommandItem,{value:j.name,onSelect:()=>h(j),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:j.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:j.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:j.syntax})]})},j.name))})]})]})})]}),e.jsxs(t.Popover,{open:c&&u==="column",onOpenChange:j=>{l(j),j&&x("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(le.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search columns..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No columns found."}),e.jsx(a.CommandGroup,{heading:"Available Columns",children:d.map(j=>{const N=p(j.dataType);return e.jsxs(a.CommandItem,{value:j.label||j.name,onSelect:()=>b(j),children:[e.jsx(N,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:j.label||j.name})]},j.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:m,value:s,onChange:j=>n(j.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(le.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 Wc({className:s}){var p,j,N,f;const n=t.useEditorStore(g=>g.card),[r,o]=v.useState(null),[i,d]=v.useState(""),{columns:c=[],columnGroups:l=[],isLoading:u}=a.useColumns(),{valuePickFilterableFields:x=[]}=a.useFilterableFields();(p=n==null?void 0:n.config)!=null&&p.groupByColumns,(j=n==null?void 0:n.config)!=null&&j.metricColumns,(N=n==null?void 0:n.config)!=null&&N.groupByColumns,(f=n==null?void 0:n.config)!=null&&f.pivotByColumns;const m=g=>{o(g),d(g?`[${g.label||g.name}]`:"")},b=g=>{console.log("Formula submitted:",g),d(""),o(null)},h=()=>{d(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Jc,{value:i,onChange:d,onSubmit:b,onCancel:h,selectedColumn:r,availableColumns:c}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Uc,{selectedColumn:r,onColumnSelect:m,isLoading:u,sourceFields:c,filterableFields:x})}),e.jsx(Hc,{entityGroups:l,isLoading:u})]})]})}function Xc(){const[s,n]=v.useState("chart"),[r,o]=v.useState(!1),[i,d]=v.useState(!0),[c,l]=v.useState(!0),u=t.useEditorStore(V=>V.showAIDialog),x=t.useDashboardStore(V=>V.isVisualEditing),{setCardType:m}=t.useEditorActions(),b=t.useEditorStore(V=>V.card.type);v.useEffect(()=>qc(),[]);const h=V=>{m(V)},p=t.useEditorStore(V=>V.frame),j=t.useEditorStore(V=>V.card);t.useEditorStore(V=>V.activeTabCardId),t.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:N,removeCard:f,updateCard:g,setActiveCard:D,updateFilters:I,clearFilters:w}=t.useEditorActions(),{columnFields:S=[],scopedFields:M=[],filterableFields:A=[]}=a.useFilterableFields(),F=a.useSensors(a.useSensor(a.PointerSensor,{activationConstraint:{distance:8}})),E=j,{getFieldsForContainer:C,setFieldsForContainer:T,moveField:L,removeField:k,resetFields:R}=a.useFieldManagement(E,M),{activeField:y,handleDragStart:_,handleDragEnd:O}=kc({activeCardId:p.activeCardId,sourceFields:M,getFieldsForContainer:C,setFieldsForContainer:T,moveField:L}),P=(V,$)=>{$&&I(V,$)},B=V=>{w(V)},Y=A,q=V=>{if(!V)return 0;let $=V.conditions.length;return V.groups.forEach(Q=>{$+=q(Q)}),$},z=q(je.getAuthoredCardFilters(E)||null);return e.jsxs(a.DndContext,{sensors:F,collisionDetection:a.closestCenter,onDragStart:_,onDragEnd:O,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(oa,{isVisible:i,onToggleVisibility:()=>d(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:b==="tableBuilder"?e.jsx(Wc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!u&&e.jsx(xc,{onRemoveField:k,onResetFields:R,selectedChart:b,onChartChange:h,groupByFields:C("groupBy"),pivotByFields:C("pivotBy"),metricsFields:C("metrics"),sortByFields:C("sortBy"),detailFields:C("detailColumns"),activeField:y,isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsx(Yc,{selectedChart:b,activeView:s,onViewChange:n,onFiltersClick:()=>o(!0),filterCount:z,activeCard:E,columns:S,getFieldsForContainer:C,cards:p.cards,activeCardId:p.activeCardId,addCard:N,setActiveCard:D})]})}),!i&&x&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(a.Database,{className:"h-4 w-4"})})})]}),E&&e.jsx(Dc,{cardId:E.id,filters:je.getAuthoredCardFilters(E)||null,onFiltersChange:P,onClearFilters:B,availableFields:Y,isOpen:r,onOpenChange:o}),e.jsx(a.DragOverlay,{dropAnimation:null,children:e.jsx(zc,{activeField:y||null})})]})}function Zc({authToken:s,onSave:n,onClose:r}){const o=v.useRef(null),i=t.useEditorStore(A=>A.showAIDialog),d=t.useEditorStore(A=>A.isDevMode),c=a.useAssistantLayoutStore(A=>A.setFullscreen),l=a.useAssistantLayoutStore(A=>A.setPanelOpen),u=a.useAssistantLayoutStore(A=>A.setContainer),x=a.useAssistantPanel("editor"),m=a.useFullscreenAssistant(),b=a.useAssistantContainer("editor"),h=m==="editor",p=a.useDashboardAppearance(),j=v.useCallback(A=>{u("editor",A)},[u]),{setAuthToken:N}=t.useDashboardActions(),{setShowAIDialog:f,setOnSave:g,setOnClose:D}=t.useEditorActions(),{setActiveAssistantType:I}=t.useAIActions();v.useEffect(()=>{n&&g(n),r&&D(r)},[n,g,r,D]),v.useEffect(()=>{s&&s.accessToken&&N(s)},[s,N]),v.useEffect(()=>{var A,F;i?((A=o.current)==null||A.resize(40),l("editor",!0),I("editor")):((F=o.current)==null||F.resize(0),l("editor",!1),m==="editor"&&c(null),I(null))},[i,l,I,c,m]);function w(A){var F;A<1?(f(!1),l("editor",!1),m==="editor"&&c(null),I(null),(F=o.current)==null||F.resize(0)):(i||(f(!0),I("editor")),x.isOpen||l("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(oa,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(a.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(a.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Vi,{})}),e.jsx(a.ResizableHandle,{disabled:!i}),e.jsx(a.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xn,{isFullscreen:h,onFullscreenChange:A=>c(A?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:j,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function M(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(a.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(a.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Xc,{})}),e.jsx(a.ResizableHandle,{disabled:!i}),e.jsx(a.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xn,{isFullscreen:h,onFullscreenChange:A=>c(A?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:j,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(a.ErrorBoundary,{FallbackComponent:a.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:p.dashboardContainerStyle,children:S()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:p.dashboardContainerStyle,children:M()})})}function ed(){t.useDashboardStore(p=>p.selectedCardId);const s=t.useDashboardStore(p=>p.selectedSheetId),n=t.useDashboardStore(p=>p.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(p=>p.actions),i=t.useEditorStore(p=>p.editorContext),{clearEditorContext:d}=t.useEditorStore(p=>p.actions),c=a.useDashboardAppearance(),l=t.useDashboardStore(p=>p.isVisualEditing),u=t.useDashboardStore(p=>p.actions.updateFrame),x=t.useDashboardStore(p=>p.actions.updateDocumentSectionCard),m=a.useResolveExistingFrameSemanticExecutionPayload();async function b(p){var D,I,w;if((i==null?void 0:i.type)==="documentSection"){const S=a.getDocumentSectionEditorCard(p,i.cardId);if(!S){t.ue.error("No document section card found");return}if(!a.isSupportedDocumentTableCardType(S)){t.ue.error("Document table sections support Table and Pivot Table");return}x(i.sheetId,i.sectionId,S,{calculatedFields:p.calculatedFields}),d(),r(!1);return}const j=s?(D=n==null?void 0:n.sheets)==null?void 0:D.some(S=>{var M;return S.id===s&&((M=S.frames)==null?void 0:M.some(A=>A.id===p.id))}):!1,N=(w=(I=n==null?void 0:n.sheets)==null?void 0:I.find(S=>{var M;return(M=S.frames)==null?void 0:M.some(A=>A.id===p.id)}))==null?void 0:w.id,f=j?s:N||null;if(!f)return;const g=t.findDashboardFrameById(n,p.id);try{const S=await m(p,{previousFrame:g});u(f,p,{semanticExecutionPayload:S}),s!==f&&o(f),r(!1)}catch(S){console.error("Failed to resolve semantic metadata on save:",S),t.ue.error(S instanceof Error?S.message:"Failed to resolve semantic metadata for this visual")}}function h(){d(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!l}),style:c.dashboardContainerStyle,children:e.jsx(Zc,{onSave:b,onClose:h})})}exports.default=ed;
172
+ `),Le=new Blob([qe],{type:"text/csv"}),Ke=URL.createObjectURL(Le),Se=document.createElement("a");Se.href=Ke,Se.download=`${x.title}.csv`,Se.click()}if(!x)return e.jsx(e.Fragment,{children:"No Active Card"});const he=r==="both"||r==="toolbar",Ye=r==="both"||r==="canvas",Z=!$&&!Q&&!U&&(V!=null&&V.sql)?e.jsx("div",{className:"inline-flex shrink-0 items-center text-[11px] text-muted-foreground",children:e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:o?e.jsx(a.IconButton,{className:"h-7 w-7 shrink-0 px-0",buttonProps:{"aria-label":"View executed SQL"},children:e.jsx(jr,{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(a.HoverCardContent,{align:"end",collisionPadding:16,className:"w-[500px] overflow-hidden p-0",children:e.jsx(wa,{sql:V.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",!w&&"pt-2")),children:[he&&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?Z:null,p&&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:!h&&!F&&e.jsx(va,{selectedChart:x.type,onChartChange:me=>q(me),compactMore:!0,responsiveCompact:o})})}),!p&&!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:Z,Pe&&Pe.length>0&&e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",className:"h-7 gap-1.5 px-2",children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx(a.Badge,{variant:"secondary",className:"h-4 min-w-4 rounded-[4px] px-1 text-[10px] font-medium",children:Pe.length})]})}),e.jsxs(a.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(Pe,null,2),onValueChange:()=>{},language:"json",readOnly:!0,embedded:!0,wrapLines:!0,dense:!0,hideLineNumbers:!0,ariaLabel:"Active dashboard filters JSON"})})]})]}),!F&&e.jsx("div",{className:o?"hidden @[1250px]:flex":"",children:e.jsx(Ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1})}),(n==null?void 0:n.show)&&e.jsxs(t.Button,{type:"button",variant:"ghost",size:"xs","aria-pressed":n.isOpen,onClick:n.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",n.isOpen&&"bg-accent text-accent-foreground"),children:[e.jsx(a.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75}),e.jsx("span",{className:o?"hidden @[1350px]:inline":"",children:"Settings"})]}),e.jsx(a.IconButton,{tooltip:"Refresh",disabled:$||Q,className:t.cn("h-7 w-7 px-0",o&&"hidden @[1150px]:inline-flex"),onClick:Be,children:e.jsx(Ts,{className:t.cn("h-3.5 w-3.5",{"animate-spin":(Te==null?void 0:Te.isFetching)??Oe})})}),e.jsxs(a.DropdownMenu,{modal:!1,children:[e.jsx(a.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"More Options",className:"h-7 w-7 px-0","aria-label":"More options",children:e.jsx(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",collisionPadding:8,className:"max-h-[var(--radix-dropdown-menu-content-available-height)] w-56 overflow-y-auto overscroll-contain",children:[(o||(i==null?void 0:i.reset))&&e.jsxs(e.Fragment,{children:[o&&e.jsxs(a.DropdownMenuItem,{disabled:$||Q,onSelect:Be,children:[e.jsx(Ts,{className:"h-3.5 w-3.5"}),"Refresh result"]}),i==null?void 0:i.reset,e.jsx(a.DropdownMenuSeparator,{})]}),e.jsx(a.DropdownMenuLabel,{children:"Export"}),Te?e.jsxs(a.DropdownMenuItem,{disabled:$||Q||!Te.hasDelivery,title:Te.hasDelivery?void 0:"Available once the preview has loaded.",onSelect:()=>ze(Te.readDelivery()),className:"gap-2 text-[13px]",children:[e.jsx(a.Download,{className:"h-3.5 w-3.5"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:re,className:"gap-2 text-[13px]",children:[e.jsx(a.Download,{className:"h-3.5 w-3.5"}),"Download CSV"]}),e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:Ce,className:"gap-2 text-[13px]",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Download JSON"]}),e.jsxs(a.DropdownMenuItem,{disabled:!K,onSelect:ie,className:"gap-2 text-[13px]",children:[e.jsx(a.Copy,{className:"h-3.5 w-3.5"}),"Copy JSON"]})]}),e.jsx(a.DropdownMenuSeparator,{}),(i==null?void 0:i.query)&&e.jsxs(e.Fragment,{children:[e.jsx(a.DropdownMenuLabel,{children:"Query"}),i.query,e.jsx(a.DropdownMenuSeparator,{})]}),(o&&(n==null?void 0:n.show)||m||f)&&e.jsxs(e.Fragment,{children:[e.jsx(a.DropdownMenuLabel,{children:"Output"}),o&&(n==null?void 0:n.show)&&e.jsx(a.DropdownMenuCheckboxItem,{checked:n.isOpen,onCheckedChange:()=>n.onToggle(),children:"Settings"}),(m||f)&&e.jsx(a.DropdownMenuCheckboxItem,{checked:!p,onCheckedChange:me=>j(me!==!0),children:"Show raw results"}),e.jsx(a.DropdownMenuSeparator,{})]}),e.jsx(a.DropdownMenuLabel,{children:"Customize"}),!F&&!["table","detailTable","custom"].includes(x.type)&&N&&e.jsx(Mo,{triggerVariant:"menu",className:"w-full"}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),M&&e.jsxs(a.DropdownMenuItem,{onSelect:()=>{var me;return(me=n==null?void 0:n.onOpen)==null?void 0:me.call(n,"style")},className:"gap-2 text-[13px]",children:[e.jsx(Er,{className:"h-3.5 w-3.5"}),"Table settings"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsx(Sa,{onCustomize:()=>L(!0)})]})]}),_e&&e.jsx(a.ExportDialog,{isOpen:!0,onClose:()=>ze(void 0),card:x,frame:u,matrix:_e})]})]}),Ye&&(p?F?e.jsx(It,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Na,{fallbackPreview:e.jsx(It,{}),records:ge,title:x.title,isInspectorOpen:T,onInspectorOpenChange:L})}):e.jsx(It,{}):e.jsxs(a.ResizablePanelGroup,{className:t.cn(g&&"py-2 pl-2 pr-6"),direction:"horizontal",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(a.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:g&&e.jsx(el,{})}),e.jsx(a.ResizableHandle,{})]}),e.jsxs(a.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":g}),children:[Array.isArray(V==null?void 0:V.records)&&!U&&(m?e.jsx(fo,{data:V.records,card:z,paginationMetadata:ue,onPaginationChange:Ae,onPageSizePreferenceChange:B,onSortChange:Me,isLoading:$||Q}):V.records.length>0?e.jsx(a.TableVisual,{card:x,data:ge,resultColumns:V==null?void 0:V.columns,columnKeyMap:V==null?void 0:V.columnKeyMap,totalsByColumnId:V==null?void 0:V.tableTotalsByColumnId,comparisonMetadata:(Fe=V==null?void 0:V.metadata)==null?void 0:Fe.comparisonMetadata,paginationMetadata:ue,onPaginationChange:Ae,onSortChange:Me,isLoading:$||Q}):null),U&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto",children:e.jsx(rs,{error:U,errorSql:J||x.sql||x.python,onDebugWithAssistant:be,showFeedbackButton:!1})})]})]}))]})}function el(){const s=t.useEditorStore(r=>r.pythonStdOut);if(!s)return null;const n=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function tt({value:s,onCommit:n,type:r="text",placeholder:o,className:i}){const[d,c]=v.useState(s),l=v.useRef(!1);v.useEffect(()=>{c(s)},[s]);const u=()=>{if(l.current){l.current=!1;return}d!==s&&n(d)},x=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(l.current=!0,c(s),m.currentTarget.blur())};return e.jsx(t.Input,{type:r,placeholder:o,value:d,onChange:m=>c(m.target.value),onBlur:u,onKeyDown:x,className:i})}function gt({defaultValue:s,label:n,options:r,value:o,onValueChange:i,className:d,icon:c,showPlaceholderLabel:l=!0}){return e.jsxs(t.Select,{defaultValue:s,value:o,onValueChange:i,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",d),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),l&&e.jsx(t.SelectValue,{placeholder:n})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:n}),r.map(u=>e.jsx(t.SelectItem,{value:u.value,children:u.label},u.value))]})})]})}function tl(s,n){return xe.getSlotDefinitionForIndex(s,n)||null}function Yt(s){if(typeof s=="number")return`Tab ${s+1}`;const n=s.match(/^(\d+)-(\d+)$/);if(n){const[,o,i]=n;return`Tabs ${Number(o)+1}-${Number(i)+1}`}const r=s.match(/^(\d+)\+$/);return r?`Tabs ${Number(r[1])+1}+`:`Tab ${s}`}function sl(s){return s?Array.isArray(s)?s:[s]:[]}function bs(s){var o,i;if(!s)return!1;if(s.type==="text")return!!((o=s.description)!=null&&o.trim());const n=!!((i=s.sql)!=null&&i.trim()),r=je.hasValidCardConfig(s.config);return n||r}function nl({slots:s,cards:n,minInputs:r}){const o=[],i=n.filter(Boolean).length;return r&&i<r&&o.push({type:"too-few-inputs",message:`This visual requires at least ${r} tab${r===1?"":"s"}.`}),!s||s.length===0||(s.forEach(d=>{if(!d.required)return;if(typeof d.position=="number"){const u=n[d.position];bs(u)||o.push({type:"missing-required",message:`${Yt(d.position)} ("${d.label}") is required but has no data configured.`});return}const c=d.position.match(/^(\d+)-(\d+)$/);if(c){const[,u,x]=c.map(Number);for(let m=u;m<=x;m+=1){const b=n[m];if(!bs(b)){o.push({type:"missing-required",message:`${Yt(m)} ("${d.label}") is required but has no data configured.`});break}}return}const l=d.position.match(/^(\d+)\+$/);if(l){const u=Number(l[1]);if(n.length<=u){o.push({type:"missing-required",message:`${Yt(u)} ("${d.label}") is required but has no data configured.`});return}for(let x=u;x<n.length;x+=1){const m=n[x];if(!bs(m)){o.push({type:"missing-required",message:`${Yt(x)} ("${d.label}") is required but has no data configured.`});break}}}}),n.forEach((d,c)=>{if(!d)return;const l=tl(s,c);if(!l||!l.expectedType)return;const u=sl(l.expectedType);u.length!==0&&(u.includes(d.type)||o.push({type:"wrong-type",message:`${Yt(c)} ("${l.label}") expects ${u.join(", ")}, but is configured as ${d.type}.`}))})),o}const al={table:({children:s})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:s}),thead:({children:s})=>e.jsx("thead",{className:"bg-muted",children:s}),th:({children:s})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:s}),td:({children:s})=>e.jsx("td",{className:"border border-border px-3 py-2",children:s}),code:({children:s,className:n})=>(n==null?void 0:n.includes("language-"))?e.jsx("pre",{className:"my-3 overflow-x-auto rounded-md bg-muted p-3 text-xs",children:e.jsx("code",{children:s})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:s}),pre:({children:s})=>e.jsx(e.Fragment,{children:s})};function Ta(){var L,k,R;const s=t.useEditorStore(y=>y.card.customCardPreferences),{data:n}=a.usePluginQuery(),r=(n==null?void 0:n.plugins)||[],o=t.useEditorStore(y=>y.card),i=t.useEditorStore(y=>y.frame),{setCustomCardPreferences:d}=t.useEditorActions(),c=v.useMemo(()=>xe.findCustomVisualConfigCard(i,o),[i,o]),l=c==null?void 0:c.customCardPreferences,{components:u,manifest:x}=a.useCustomVisual((l==null?void 0:l.url)||(s==null?void 0:s.url)||""),m=(L=x==null?void 0:x.visuals)==null?void 0:L.find(y=>y.name===((l==null?void 0:l.componentName)||(s==null?void 0:s.componentName))),h=xe.resolveMultiInputType(c||o,m)==="multiple",p=!!c&&c.id===o.id,j=(m==null?void 0:m.minInputs)??((k=c==null?void 0:c.customCardPreferences)==null?void 0:k.minInputs),N=(m==null?void 0:m.maxInputs)??((R=c==null?void 0:c.customCardPreferences)==null?void 0:R.maxInputs),f=v.useMemo(()=>xe.getCustomVisualInputCards({frame:i,configCard:c||o,isMultiInputVisual:h}),[i,c,o,h]),g=v.useMemo(()=>xe.buildSlotOrderedCards(f),[f]),D=v.useMemo(()=>g.map((y,_)=>{if(!y)return null;const O=xe.getSlotIndexForCard(y,_),P=xe.getEffectiveCardTypeForSlot(y,O,m==null?void 0:m.slots);return{...y,type:P??y.type}}),[g,m==null?void 0:m.slots]),I=v.useMemo(()=>nl({slots:m==null?void 0:m.slots,cards:D,minInputs:j}),[m==null?void 0:m.slots,D,j]),w=v.useMemo(()=>{const y=f.findIndex(_=>(_==null?void 0:_.id)===o.id);return y<0?-1:xe.getSlotIndexForCard(o,y)},[f,o]);function S(y){if(typeof y=="number")return`Tab ${y+1}`;const _=y.match(/^(\d+)-(\d+)$/);if(_){const[,P,B]=_;return`Tabs ${Number(P)+1}-${Number(B)+1}`}const O=y.match(/^(\d+)\+$/);return O?`Tabs ${Number(O[1])+1}+`:`Tab ${y}`}function M(y){return y?(Array.isArray(y)?y:[y]).join(", "):null}function A(y,_,O=[],P="",B,Y,q){const z=F({key:_,defaultValue:P,settingsValue:Y,sourceCard:q});return y==="input"?e.jsx(tt,{className:`h-8 w-full ${t.removeRing}`,value:String(z??""),onCommit:V=>{E({key:_,value:V,settingsField:B,settingsValue:Y,sourceCard:q})}},_):y==="select"?e.jsx(gt,{className:"h-8 w-full",label:"",options:O,value:String(z!==void 0?z:P??""),onValueChange:V=>{E({key:_,value:V,settingsField:B,settingsValue:Y,sourceCard:q})}}):null}function F({key:y,defaultValue:_,settingsValue:O,sourceCard:P}){const B=O==null?void 0:O[y];return B!==void 0?B:y==="title"&&(P==null?void 0:P.title)!==void 0?P.title:y==="description"&&(P==null?void 0:P.description)!==void 0?P.description:_}function E({key:y,value:_,settingsField:O,settingsValue:P,sourceCard:B}){const Y={...P||{}},q=y==="title"&&(B==null?void 0:B.title)!==void 0,z=y==="description"&&(B==null?void 0:B.description)!==void 0;q&&_===String((B==null?void 0:B.title)??"")||z&&_===String((B==null?void 0:B.description)??"")?delete Y[y]:Y[y]=_,d({...s||{},[O]:Y})}function C({settingsSchema:y,settingsField:_,settingsValue:O,sourceCard:P,headerLabel:B}){const Y=Object.entries(y||{});return e.jsxs("div",{className:"space-y-3",children:[B&&e.jsx(t.Label,{children:B}),Y.map(([q,z])=>{var V;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}),((V=z.docs)==null?void 0:V.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})})]})})]}),A(z.ui,q,z.options,z.defaultValue,_,O,P)]},q)})]})}function T(){return e.jsxs(e.Fragment,{children:[h&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:m!=null&&m.slots&&m.slots.length>0?e.jsx("div",{className:"space-y-3",children:m.slots.map((y,_)=>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:S(y.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:y.label})]}),y.description&&e.jsx("p",{className:"text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[M(y.expectedType)&&e.jsxs("span",{children:["Expected: ",M(y.expectedType)]}),y.required&&e.jsx("span",{children:"Required"})]})]},`${y.label}-${_}`))}):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."}),(j||N)&&e.jsxs("p",{children:[j?`Min ${j} tabs`:"",j&&N?" • ":"",N?`Max ${N} tabs`:""]})]})})]}),h&&I.length>0&&e.jsx(a.Alert,{className:"mt-3 border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(a.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:I.map((y,_)=>e.jsx("li",{children:y.message},`${y.type}-${_}`))})})}),m&&!h&&m.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:C({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:o})})}),m&&h&&(m.settings||m.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[p&&m.settings&&e.jsx("div",{className:"px-2",children:C({settingsSchema:m.settings,settingsField:"settings",settingsValue:s==null?void 0:s.settings,sourceCard:c||o,headerLabel:"Global Settings"})}),m.slotSettings&&e.jsx("div",{className:"px-2",children:C({settingsSchema:m.slotSettings,settingsField:"slotSettings",settingsValue:s==null?void 0:s.slotSettings,sourceCard:o,headerLabel:(()=>{const y=o.tabTitle||o.title,_=w>=0?w:0,O=p?"Slot 0":`Slot ${_}`;return y?`${O}: ${y} Settings`:`${O} Settings`})()})})]})]})}return e.jsxs(a.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(a.AccordionItem,{value:"plugin-settings",children:[e.jsx(a.AccordionTrigger,{children:"Plugin"}),e.jsx(a.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!h||p)&&e.jsx(gt,{icon:e.jsx(na,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:r,value:(l==null?void 0:l.url)||"",onValueChange:y=>d({...s||{url:"",componentName:""},url:y})}),h&&!p&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&(!h||p)&&e.jsx(e.Fragment,{children:u&&e.jsx(gt,{icon:e.jsx(br,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(u==null?void 0:u.map(y=>({value:y.name,label:y.name})))||[],value:s.componentName||"",onValueChange:y=>{var P;const _=(P=x==null?void 0:x.visuals)==null?void 0:P.find(B=>B.name===y),O=u==null?void 0:u.find(B=>B.name===y);d({...s,componentName:y,visualType:(_==null?void 0:_.visualType)||(O==null?void 0:O.type)||"single",minInputs:_==null?void 0:_.minInputs,maxInputs:_==null?void 0:_.maxInputs,pluginChartType:_==null?void 0:_.chartType})}})})]})})]}),((l==null?void 0:l.componentName)||(s==null?void 0:s.componentName))&&e.jsxs(a.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(a.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(m==null?void 0:m.name)||"Settings"}),(m==null?void 0:m.docs)&&e.jsxs(a.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,onClick:y=>y.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(a.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:[m.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:m.docs.description}),m.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(a.Markdown,{remarkPlugins:[a.remarkGfm],components:al,children:m.docs.dataSchema})})]}),(()=>{var _;const y=(_=m.docs)==null?void 0:_.useCases;return!y||y.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:y.map((O,P)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:O})]},P))})]})})()]})})]})]})}),e.jsx(a.AccordionContent,{children:T()})]})]})}function as(s){return s==="currency"?2:s==="percent"?1:s==="scientific"?2:0}function Ea(s,n,r){if(!n||n==="auto")return{type:"auto"};if(n==="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:n,multiplyBy:n==="percent"?s.multiplyBy:void 0,percentValueMode:n==="percent"?s.percentValueMode:void 0,durationInputUnit:void 0,durationDisplayStyle:void 0,durationLargestUnit:void 0,durationSmallestUnit:void 0,durationMaxUnits:void 0};return n&&["number","currency","percent","scientific"].includes(n)&&s.decimalPlaces===void 0&&s.minimumFractionDigits===void 0&&s.maximumFractionDigits===void 0&&!(n==="currency"&&(r!=null&&r.preserveSparseCurrency))?Ia(o,as(n)):o}function rl(s,n){return{...s,decimalPlaces:void 0,minimumFractionDigits:n,maximumFractionDigits:n}}function Vn(s){const n=s.decimalPlaces;return{...s,currency:void 0,decimalPlaces:void 0,minimumFractionDigits:s.minimumFractionDigits??n,maximumFractionDigits:s.maximumFractionDigits??n}}function ol(s,n){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}:Ea(s,r,n)}function Ia(s,n){return{...s,decimalPlaces:n,minimumFractionDigits:n,maximumFractionDigits:n}}const Rt="__report_default__",ll=["auto","number","currency","percent","scientific","date","duration"],_n=[{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"}],Yn=[{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"}],js=[{value:"millisecond",label:"Milliseconds"},{value:"second",label:"Seconds"},{value:"minute",label:"Minutes"},{value:"hour",label:"Hours"},{value:"day",label:"Days"}],il=[{value:"compact",label:"Compact (6min 32s)"},{value:"digital",label:"Digital (6:32)"},{value:"long",label:"Long (6 minutes 32 seconds)"}],cl=s=>s.charAt(0).toUpperCase()+s.slice(1);function dl(s,n){try{return ea.resolveCurrencyFractionDigits(s,n).maximumFractionDigits??as("currency")}catch{return as("currency")}}function Ut({formatOptions:s={},onFormatOptionsChange:n,showTitle:r=!0,title:o="NUMBER FORMAT",maxDecimalPlaces:i=10,reportDefaults:d,showAutoFormat:c=!0,showLocaleOverride:l=!0}){var T,L;const u=s.type||"auto",x=ol(s,{preserveSparseCurrency:!!d}),m=k=>{k.stopPropagation()},b=(k,R)=>{n({...x,[k]:R})},h=x.decimalPlaces??x.maximumFractionDigits??x.minimumFractionDigits,p=s.currency??(d==null?void 0:d.currency)??"USD",j=s.locale??(d==null?void 0:d.locale)??"en-US",N=u==="currency"?dl(j,p):void 0,f=h??N??as(u),g=u==="currency"&&x.decimalPlaces===void 0&&x.minimumFractionDigits===void 0&&x.maximumFractionDigits===void 0,[D,I]=v.useState(()=>String(f)),[w,S]=v.useState(()=>x.multiplyBy!==void 0?String(x.multiplyBy):""),M=k=>{const R=Ea(s,k,{preserveSparseCurrency:!!d});n(d&&k==="currency"&&s.type!=="currency"?Vn(R):R)},A=k=>d&&u==="currency"?rl(x,k):Ia(x,k),F=((T=_n.find(k=>k.value===(d==null?void 0:d.currency)))==null?void 0:T.label)??(d==null?void 0:d.currency),E=((L=Yn.find(k=>k.value===(d==null?void 0:d.locale)))==null?void 0:L.label)??(d==null?void 0:d.locale),C=u==="number"||u==="currency"||u==="percent"||u==="scientific";return v.useEffect(()=>{I(String(f))},[f]),v.useEffect(()=>{S(x.multiplyBy!==void 0?String(x.multiplyBy):"")},[x.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:u,onValueChange:k=>M(k),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:ll.filter(k=>c||k!=="auto").map(k=>e.jsx(t.SelectItem,{value:k,className:"text-xs",children:k==="auto"?"Auto (Default)":cl(k)},k))})]})]}),u!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent","scientific"].includes(u)&&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:i,placeholder:"0",value:D,onClick:m,onPointerDown:m,onKeyDown:m,onChange:k=>{const R=k.target.value.replace(/[^\d]/g,"");I(R),R!==""&&n(A(Math.max(0,Math.min(i,parseInt(R,10)))))},onBlur:()=>{if(D!=="")return;const k=f;I(String(k)),n(A(k))},className:"h-8 text-xs"}),g&&e.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:"Currency default"})]})]}),u==="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||(d?Rt:"USD"),onValueChange:k=>{if(k===Rt){n(Vn(x));return}b("currency",k)},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:[d&&e.jsxs(t.SelectItem,{value:Rt,className:"text-xs",children:["Report default — ",F]}),_n.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))]})]})]})}),["number","currency"].includes(u)&&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:k=>k.stopPropagation(),onCheckedChange:k=>b("useSuffix",k)})]}),l&&u!=="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||(d&&C?Rt:"en-US"),onValueChange:k=>b("locale",k===Rt?void 0:k),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:[d&&C&&e.jsxs(t.SelectItem,{value:Rt,className:"text-xs",children:["Report default — ",E]}),Yn.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))]})]})]}),u==="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:k=>b("prefix",k.target.value),className:"h-8 text-xs"})})]}),u==="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:k=>b("suffix",k.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(u)&&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:k=>k.stopPropagation(),onCheckedChange:k=>b("negativeInParentheses",k)})]}),u==="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:w,onClick:m,onPointerDown:m,onKeyDown:m,onChange:k=>{const R=k.target.value.replace(/[^0-9.]/g,"");S(R),b("multiplyBy",R?parseFloat(R):void 0)},className:"h-8 text-xs"})})]}),u==="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:k=>b("dateFormat",k.target.value),className:"h-8 text-xs"})})]}),u==="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:k=>b("durationInputUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationDisplayStyle",k),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:il.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationSmallestUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.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:k=>b("durationLargestUnit",k),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:js.map(k=>e.jsx(t.SelectItem,{value:k.value,className:"text-xs",children:k.label},k.value))})]})]})]})]})]})}function zn({colorRanges:s,setColorRanges:n}){const r={start:-1/0,end:100,color:""};function o(c,l,u){const x=[...s];x[c]={...x[c],[l]:u},n(x)}function i(c){const l=[...s];l.splice(c,1),n(l)}function d(){n([...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:d,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(a.Plus,{className:"size-3"})})]}),s.map((c,l)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(t.Input,{onChange:u=>o(l,"start",u.target.value),value:c.start,className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(t.Input,{value:c.end,onChange:u=>o(l,"end",u.target.value),className:t.cn(`h-7 ${t.removeRing}`)}),e.jsx(t.Input,{onChange:u=>o(l,"color",u.target.value),value:c.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:je.colors.green[600]}),e.jsx("option",{children:je.colors.red[500]}),e.jsx("option",{children:je.colors.yellow[400]}),e.jsx("option",{children:je.colors.orange[500]})]}),e.jsx(t.Button,{onClick:()=>i(l),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(le.X,{className:"size-3"})})]},l))]})}const ul=[];function ml(s){return(s==null?void 0:s.enabled)===!1||typeof(s==null?void 0:s.enabled)=="string"&&s.enabled.trim().toLowerCase()==="false"}function xl(s){var r;const n=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(n,{preserveOmittedProperties:!0})||{type:"number",minimumFractionDigits:0,maximumFractionDigits:0}}function qn(s){return{enabled:!0,colorRanges:s==null?void 0:s.colorRanges}}function hl(){var h,p,j,N;const s=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.actions.setCardPreferences),r=t.useEditorStore(f=>{var g,D;return((D=(g=f.card.preferences)==null?void 0:g.formatNumber)==null?void 0:D.colorRanges)??ul}),o=t.useEditorStore(f=>f.actions.setColorRanges),i=a.useResolvedValueFormatLocale()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale,d=a.useResolvedDefaultCurrency()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,c=!a.isSqlBackedKpi(s)&&je.hasValidCardConfig(s.config),l=xl(s.preferences),u=!!t.fromPersistedKpiFormatOptions((p=(h=s.preferences)==null?void 0:h.kpiVisualOptions)==null?void 0:p.formatOptions),x=!ml((j=s.preferences)==null?void 0:j.formatNumber)&&(u||!!((N=s.preferences)!=null&&N.formatNumber)),m=f=>{const g=t.useEditorStore.getState().card.preferences??{};n({...g,formatNumber:qn(g.formatNumber),kpiVisualOptions:{...g.kpiVisualOptions,formatOptions:f}})},b=f=>{const g=t.useEditorStore.getState().card.preferences??{};if(f){n({...g,formatNumber:qn(g.formatNumber),kpiVisualOptions:{...g.kpiVisualOptions,formatOptions:l}});return}n({...g,formatNumber:{...g.formatNumber,enabled:!1}})};return c?e.jsx(zn,{colorRanges:r,setColorRanges:o}):e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(a.Checkbox,{id:"query-kpi-format-number",checked:x,onCheckedChange:f=>b(f===!0)}),e.jsx(t.Label,{htmlFor:"query-kpi-format-number",className:"text-xs",children:"Format number"})]}),x&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Ut,{formatOptions:l,onFormatOptionsChange:m,showTitle:!1,showAutoFormat:!1,reportDefaults:{currency:d,locale:i}}),e.jsx(t.Separator,{className:"my-3"}),e.jsx(zn,{colorRanges:r,setColorRanges:o})]})]})}const pl={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 Da(s){return pl[s]}function fl({chartType:s,showDocsLink:n=!0}){const r=Da(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,i)=>e.jsxs("tr",{className:i<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}),n&&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(a.ExternalLink,{className:"h-3 w-3"})]})]}):null}function gl({chartType:s}){return Da(s)?e.jsxs(a.HoverCard,{openDelay:200,children:[e.jsx(a.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(a.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(fl,{chartType:s})})]}):null}function Os({chartType:s,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-medium",children:n}),e.jsx(gl,{chartType:s})]})}function bl(){const s=t.useEditorStore(i=>!je.hasValidCardConfig(i.card.config)),n=t.useEditorStore(i=>{var d,c;return((c=(d=i.card.preferences)==null?void 0:d.kpiVisualOptions)==null?void 0:c.queryComparisonPolarity)??Tn.DEFAULT_METRIC_COMPARISON_POLARITY}),r=t.useEditorStore(i=>i.actions.setCardPreferences),o=i=>{const d=t.useEditorStore.getState().card.preferences??{},c={...d.kpiVisualOptions,queryComparisonPolarity:i===Tn.DEFAULT_METRIC_COMPARISON_POLARITY?void 0:i};r({...d,kpiVisualOptions:c})};return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx(Os,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(hl,{})}),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:n,onValueChange:i=>o(i),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 $n({children:s,summary:n,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:n}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}function jl(){const[s,n]=v.useState([]),r=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:o,setCardPreferences:i}=t.useEditorStore(x=>x.actions),d=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var m;return(m=x.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),v.useEffect(()=>{d&&n(new Array(d.length).fill(!1))},[d]);function c(x,m){var b,h;m?r!=null&&r.onClickFilter&&((b=r==null?void 0:r.onClickFilter)==null?void 0:b.length)>0?i({...r,onClickFilter:[...r.onClickFilter,{columnIndex:x,expression:""}]}):i({...r,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...r,onClickFilter:(h=r==null?void 0:r.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==x)}),n(p=>{const j=[...p];return j[x]=!1,j}))}function l(x,m){var h;const b=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===x?{...p,expression:m.target.value}:p);i({...r,onClickFilter:b})}function u(x){var m,b,h,p;if(s!=null&&s[x]||(b=(m=r==null?void 0:r.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===x))!=null&&b.expression)return e.jsx(t.Input,{value:(p=(h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===x))==null?void 0:p.expression,onChange:j=>l(x,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:d==null?void 0:d.map((x,m)=>{var b,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(a.Checkbox,{checked:!!((b=r==null?void 0:r.onClickFilter)!=null&&b.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((h=r==null?void 0:r.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(a.Pencil,{onClick:()=>{n(p=>{const j=[...p];return j[m]=!p[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),u(m)]})},x)})})}const vl=[{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"}],yl=["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"],Cl=yl.map(s=>({label:s,value:s}));function Nl(){var u,x,m,b,h,p,j,N,f,g,D,I,w,S,M,A,F,E;const s=t.useEditorStore(C=>C.card),n=(x=(u=s==null?void 0:s.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:x.topoJsonUrl,[r,o]=v.useState(((b=(m=s==null?void 0:s.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:b.customTopoJsonUrl)||""),{setCardPreferences:i}=t.useEditorActions(),{data:d}=a.useTopoJson(s),c=Object.keys((d==null?void 0:d.objects)||{}).map(C=>({label:C,value:C}))||[],l=[{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(Os,{chartType:"map"}),e.jsx($n,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(gt,{className:"h-9",options:l,onValueChange:C=>{console.log("value",C),i({...s.preferences,mapVisualOptions:{topoJsonUrl:C}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(t.Input,{onChange:C=>{o(C.target.value)},onBlur:()=>{var C;console.log("onBlur",r),i({...s.preferences,mapVisualOptions:{...(C=s.preferences)==null?void 0:C.mapVisualOptions,customTopoJsonUrl:r}})},value:r,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(gt,{className:"h-9",options:c,value:((p=(h=s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,objectKey:C}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(gt,{className:"h-9",options:vl,value:((N=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:N.projection)||"",label:"Projection",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projection:C}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(gt,{className:"h-9",options:Cl,value:((g=(f=s.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:g.colorScale)||"",label:"Select Color Scale",onValueChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,colorScale:C}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx($n,{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:((I=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:I.projectionScale)||1,onChange:C=>{var T;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionScale:Number(C.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((M=(S=(w=s.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:M[0])||0,onChange:C=>{var T,L,k,R;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[Number(C.target.value),((R=(k=(L=s.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:R[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((E=(F=(A=s.preferences)==null?void 0:A.mapVisualOptions)==null?void 0:F.projectionOffset)==null?void 0:E[1])||0,onChange:C=>{var T,L,k,R;i({...s.preferences,mapVisualOptions:{...(T=s.preferences)==null?void 0:T.mapVisualOptions,projectionOffset:[((R=(k=(L=s.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:R[0])||0,Number(C.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(jl,{})]})}function Xe({label:s,value:n,options:r,onChange:o,disabled:i}){const d=v.useId();return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx(t.Label,{htmlFor:d,className:"text-xs",children:s}),e.jsxs(t.Select,{value:n,onValueChange:o,disabled:i,children:[e.jsx(t.SelectTrigger,{id:d,"aria-label":s,className:"h-8 min-w-0 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:r.map(c=>e.jsx(t.SelectItem,{value:c.value,className:"text-xs",children:c.label},c.value))})]})]})}function Et({label:s,value:n,onChange:r,type:o="text",min:i,max:d}){const c=v.useId();return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx(t.Label,{htmlFor:c,className:"text-xs",children:s}),e.jsx(t.Input,{id:c,className:"h-8 text-xs",type:o,min:i,max:d,value:n,onChange:l=>r(l.target.value)})]})}function Bs({label:s,checked:n,onChange:r}){const o=v.useId();return e.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 py-1",children:[e.jsx(t.Label,{className:"text-xs",htmlFor:o,children:s}),e.jsx(t.Switch,{id:o,size:"xs",checked:n,onCheckedChange:r})]})}function Sl({label:s,disabled:n,onClick:r,children:o}){return e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0","aria-label":s,title:s,disabled:n,onClick:r,children:o})}function Kn({label:s,value:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Bs,{label:s,checked:n.visible,onChange:o=>r({...n,visible:o})}),e.jsx(Xe,{label:`${s} position`,value:n.position,options:[{value:"before",label:"Before"},{value:"after",label:"After"}],onChange:o=>r({...n,position:o})}),e.jsx(Et,{label:`${s} label`,value:n.label??"",onChange:o=>r({...n,label:o||void 0})})]})}function Es({value:s,onChange:n,cardType:r,showTitle:o=!0,title:i="NUMBER FORMAT",showLocaleOverride:d=!0}){const c=a.supportsLiveNumericPresentation(r),l=a.useResolvedValueFormatLocale(),u=a.useResolvedDefaultCurrency(),x=t.toTFormatOptions(xr.fromSemanticFormat(s,{preserveOmittedProperties:!0}),{preserveOmittedProperties:!0})||{},m=b=>{const h=t.fromTFormatOptions(b,{preserveOmittedProperties:!0});if(!d&&h&&"locale"in h){const{locale:p,...j}=h;n(j)}else n(h)};return e.jsx(Ut,{formatOptions:x,onFormatOptionsChange:m,showTitle:o,title:i,showLocaleOverride:d,reportDefaults:c?{currency:u??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.defaultCurrency,locale:l??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES.locale}:void 0})}function wl(s){switch(s==null?void 0:s.type){case"date":case"datetime":return{...s,type:"date"};case"number":case"currency":case"percent":case"percentage":case"scientific":case"duration":case"string":return s;default:return}}function ka(s,n,r){const o=(r==null?void 0:r.length)&&r.every((i,d)=>{var c;return((c=s[d])==null?void 0:c.id)===i.levelId&&i.member.kind==="value"});return new Map([...n!=null&&n.length?[[at.matrixPathKey(n),n]]:[],...o?[[at.matrixPathKey(r),r]]:[]])}function Tl({axis:s,level:n,value:r,change:o,scopeSelection:i}){const d=r.spec.sorts.find(h=>h.axis===s&&h.levelId===n.id&&h.scope.kind==="level"),c=r.spec.rankings.find(h=>h.axis===s&&h.levelId===n.id),l=s==="rows"?"columns":"rows",u=ka(r.spec[l],c==null?void 0:c.oppositePath,l==="rows"?i==null?void 0:i.rowPath:i==null?void 0:i.columnPath),x=r.spec.measures.map(h=>({value:h.id,label:bt.getMatrixMeasureLabel(h,r.presentation)})),m=h=>{const p=r.spec.sorts.filter(j=>!(j.axis===s&&j.levelId===n.id&&j.scope.kind==="level"));o({kind:"sorts",sorts:h?[...p,{axis:s,levelId:n.id,scope:{kind:"level"},target:{kind:"member"},direction:"asc",nulls:"last",...d,...h}]:p})},b=h=>{if(h&&!r.spec.measures.length)return;const p=r.spec.rankings.filter(j=>!(j.axis===s&&j.levelId===n.id));o({kind:"rankings",rankings:h?[...p,{id:je.v4(),axis:s,levelId:n.id,direction:"top",count:10,measureId:r.spec.measures[0].id,oppositePath:[],others:!1,...c,...h}]:p})};return e.jsxs("div",{className:"space-y-2 border-t pt-2",children:[e.jsx(Xe,{label:"Sort by",value:d?d.target.kind==="member"?"member":d.target.measureId:"default",options:[{value:"default",label:"Default"},{value:"member",label:"Member"},...x],onChange:h=>m(h==="default"?void 0:{target:h==="member"?{kind:"member"}:{kind:"measure",measureId:h,oppositePath:[]}})}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Sort direction",value:d.direction,options:[{value:"asc",label:"Ascending"},{value:"desc",label:"Descending"}],onChange:h=>m({direction:h})}),e.jsx(Xe,{label:"Null order",value:d.nulls,options:[{value:"first",label:"First"},{value:"last",label:"Last"}],onChange:h=>m({nulls:h})})]}),e.jsx(Xe,{label:"Ranking",disabled:!r.spec.measures.length,value:(c==null?void 0:c.direction)??"none",options:[{value:"none",label:"None"},{value:"top",label:"Top"},{value:"bottom",label:"Bottom"}],onChange:h=>b(h==="none"?void 0:{direction:h})}),c&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Ranking count",type:"number",min:1,value:c.count,onChange:h=>{h&&Number.isSafeInteger(Number(h))&&Number(h)>0&&b({count:Number(h)})}}),e.jsx(Xe,{label:"Rank by measure",value:c.measureId,options:x,onChange:h=>b({measureId:h})}),e.jsx(Bs,{label:"Include Others",checked:c.others,onChange:h=>b({others:h})}),e.jsx(Xe,{label:"Ranking context",value:c.oppositePath.length?at.matrixPathKey(c.oppositePath):"total",options:[{value:"total",label:"Grand total"},...[...u].map(([h,p])=>({value:h,label:p.map((j,N)=>ta.matrixMemberLabel(p.slice(0,N+1))).join(" / ")}))],onChange:h=>b({oppositePath:h==="total"?[]:[...u.get(h)]})})]})]})}function El({value:s,change:n,scopeSelection:r}){var f,g,D;const[o,i]=v.useState(((f=s.presentation.conditionalFormatting)==null?void 0:f.rules)??[]),[d,c]=v.useState(s.spec),[l,u]=v.useState(""),x=JSON.stringify(s.presentation.conditionalFormatting??{version:1,rules:[]}),m=v.useRef(x);x!==m.current&&(m.current=x,JSON.stringify(at.matrixConditionalFormattingSchema.safeParse({version:1,rules:o}).data??null)!==x&&i(((g=s.presentation.conditionalFormatting)==null?void 0:g.rules)??[]));const b=o.filter(a.isRuleReadyToApply);v.useEffect(()=>{const I=at.matrixConditionalFormattingSchema.safeParse({version:1,rules:b});if(!I.success)return;const w=JSON.stringify(I.data);w!==m.current&&(m.current=w,n({kind:"presentation",presentation:{...s.presentation,conditionalFormatting:I.data}}))},[b,n,s.presentation]);const h=o.find(I=>!a.isRuleReadyToApply(I)),p=at.matrixConditionalFormattingSchema.safeParse({version:1,rules:b}),j=h?`${h.name||"the new rule"} is incomplete`:p.success?"":((D=p.error.issues[0])==null?void 0:D.message)??"the rule is incomplete";if(d!==s.spec){const I=[],w=Dt.retainMatrixConditionalFormatting(d,s.spec,{version:1,rules:o},I);c(s.spec),I.length&&(i((w==null?void 0:w.rules)??[]),u("Removed rules whose measure, level or member path changed."))}const N=s.spec.measures[0];return N?e.jsxs("div",{className:"min-w-0 space-y-2",children:[l&&e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:l}),j&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Not applied yet: ",j]}),e.jsx(a.DataTableConditionalFormattingSettings,{columnId:N.id,availableColumns:s.spec.measures.map(I=>({value:I.id,label:bt.getMatrixMeasureLabel(I,s.presentation)})),conditionalRules:o,onConditionalRulesChange:i,capabilities:{ruleKinds:["comparison","colorScale","dataBar"],automaticRanges:!1,separateApplyTargets:!0,targetScope:{defaultRowRoles:["member"]}}}),o.map((I,w)=>{var C;const S=I.target.matrix,M=(S==null?void 0:S.axis)==="columns"?"rows":"columns",A=M==="rows"?r==null?void 0:r.rowPath:r==null?void 0:r.columnPath,F=ka(s.spec[M],S==null?void 0:S.oppositePath,A),E=T=>i(L=>L.map(k=>k.id===I.id?{...k,target:{...k.target,matrix:T}}:k));return e.jsxs("fieldset",{className:"min-w-0 space-y-2 border-t pt-2",children:[e.jsxs("legend",{className:"text-xs font-medium",children:[I.name||`Rule ${w+1}`," scope"]}),e.jsx(Xe,{label:"Cell role",value:((C=I.target.rowRoles)==null?void 0:C.length)===1?I.target.rowRoles[0]:"all",options:[{value:"all",label:"All roles"},{value:"member",label:"Detail"},{value:"subtotal",label:"Subtotal"},{value:"grand_total",label:"Grand total"},{value:"others",label:"Others"}],onChange:T=>i(L=>L.map(k=>{if(k.id!==I.id)return k;const{tableParts:R,includeTotals:y,includeSubtotals:_,...O}=k.target;return{...k,target:{...O,rowRoles:T==="all"?void 0:[T]}}}))}),e.jsx(Xe,{label:"Rule axis",value:(S==null?void 0:S.axis)??"all",options:[{value:"all",label:"All cells"},{value:"rows",label:"Rows"},{value:"columns",label:"Columns"}],onChange:T=>E(T==="all"?void 0:{axis:T})}),S&&e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Rule level",value:S.levelId??"all",options:[{value:"all",label:"All levels"},...s.spec[S.axis].map(T=>({value:T.id,label:bt.getMatrixLevelLabel(T,s.presentation)}))],onChange:T=>E({...S,levelId:T==="all"?void 0:T})}),e.jsx(Xe,{label:"Opposite members",value:S.oppositePath===void 0?"all":S.oppositePath.length?at.matrixPathKey(S.oppositePath):"total",options:[{value:"all",label:"All members"},{value:"total",label:"Grand total"},...[...F].map(([T,L])=>({value:T,label:L.map((k,R)=>ta.matrixMemberLabel(L.slice(0,R+1))).join(" / ")}))],onChange:T=>E({...S,oppositePath:T==="all"?void 0:T==="total"?[]:[...F.get(T)]})})]})]},I.id)})]}):e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"No metrics available"})}function Il({section:s,value:n,availableFields:r,bindings:o,scopeSelection:i,onChange:d}){const[c,l]=v.useState([]),[u,x]=v.useState(""),m=N=>je.matrixAuthoringDataType(N,n.spec.source,r),b=N=>{try{const f=Dt.updateMatrixConfig(n,N,o,m,!0);x(""),l(f.notices),d(f.config,f.notices,f.removedBindings,f.bindings)}catch(f){x(f instanceof Error?f.message:"Invalid Matrix settings.")}},h=N=>b({kind:"presentation",presentation:{...n.presentation,...N}}),p=(N,f,g)=>{const D={...n.presentation[N]};if(g===void 0)delete D[f];else{const I=at.semaphorValueFormatSchema.safeParse(g);if(!I.success){x(I.error.message);return}D[f]=I.data}h({[N]:D})},j=(N,f)=>{const g=n.presentation[f][N];return e.jsx(Es,{showLocaleOverride:!1,cardType:"matrixTable",value:wl(g),onChange:D=>p(f,N,D)})};return e.jsxs("aside",{"aria-label":"Matrix authoring",className:"min-w-0 text-foreground",children:[u&&e.jsx("p",{role:"alert",className:"break-words p-3 text-xs text-destructive",children:u}),c.length>0&&e.jsxs("div",{role:"status",className:"border-b p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("strong",{children:"Updated references"}),e.jsx(Sl,{label:"Dismiss cleanup notices",onClick:()=>l([]),children:e.jsx(le.X,{className:"size-3.5"})})]}),e.jsx("ul",{className:"space-y-1",children:c.map((N,f)=>e.jsx("li",{children:N.message},`${N.kind}-${N.id}-${f}`))})]}),s.kind!=="conditional-formatting"&&["rows","columns"].filter(N=>s.kind!=="field"||n.spec[N].some(f=>f.id===s.id)).map(N=>e.jsxs("section",{"aria-label":s.kind==="field"?`Field ${s.id}`:N==="rows"?"Rows":"Columns",className:(s==null?void 0:s.kind)==="field"?"space-y-2":"space-y-2 border-b p-3",children:[(s==null?void 0:s.kind)!=="field"&&e.jsx("h2",{className:"text-xs font-semibold",children:N==="rows"?"Rows":"Columns"}),n.spec[N].filter(f=>s.kind==="field"&&f.id===s.id).map(f=>{const g=bt.getMatrixLevelLabel(f,n.presentation),D=F=>b({kind:"structure",[N]:n.spec[N].map(E=>E.id===f.id?F:E)}),I=m(f.field),w=I==="date"||I==="datetime",S=n.presentation.levelFormats[f.id],M=(S==null?void 0:S.type)==="temporal_bucket"?S:et.AUTOMATIC_TEMPORAL_BUCKET_FORMAT,A=f.grain?et.getTemporalBucketAuthoringSelection(M,f.grain):void 0;return e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"min-w-0":"min-w-0 border-b pb-2",children:[e.jsx("div",{className:"flex min-w-0 items-center justify-between gap-1",children:e.jsx("span",{className:"truncate text-xs font-medium",title:g,children:g})}),e.jsxs("details",{open:(s==null?void 0:s.kind)==="field"?!0:void 0,children:[e.jsxs("summary",{className:`cursor-pointer py-1 text-xs text-muted-foreground ${(s==null?void 0:s.kind)==="field"?"hidden":""}`,children:[g," settings"]}),e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"space-y-2 pt-2":"space-y-2 py-2",children:[e.jsx(Et,{label:"Level label",value:n.presentation.levelLabels[f.id]??"",onChange:F=>{const E={...n.presentation.levelLabels};F?E[f.id]=F:delete E[f.id],h({levelLabels:E})}}),e.jsx(Xe,{label:"Axis",value:N,options:[{value:"rows",label:"Rows"},{value:"columns",label:"Columns"}],onChange:F=>{F!==N&&b(Dt.moveMatrixLevel(n.spec,f.id,F))}}),w&&e.jsx(Xe,{label:"Time grain",value:f.grain??"none",options:[{value:"none",label:"No grouping"},...a.getGranularityOptionsForFieldType(I).map(F=>({value:F,label:F}))],onChange:F=>D({...f,grain:F==="none"?void 0:F})}),f.grain?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{label:"Date format",value:A.value,options:et.getTemporalBucketAuthoringOptions(f.grain,M),onChange:F=>p("levelFormats",f.id,F==="auto"?void 0:et.resolveTemporalBucketAuthoringFormat(f.grain,F,A.customPattern))}),A.value==="custom"&&e.jsx(Et,{label:"Date pattern",value:A.customPattern,onChange:F=>{F.trim()&&p("levelFormats",f.id,{type:"temporal_bucket",presentation:{mode:"pattern",pattern:F}})}})]}):j(f.id,"levelFormats"),e.jsx(Kn,{label:"Subtotal",value:n.presentation.totals[N].levels[f.id],onChange:F=>h({totals:{...n.presentation.totals,[N]:{...n.presentation.totals[N],levels:{...n.presentation.totals[N].levels,[f.id]:F}}}})}),e.jsx(Tl,{axis:N,level:f,value:n,change:b,scopeSelection:i})]})]})]},f.id)}),(s==null?void 0:s.kind)!=="field"&&e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer py-1 text-xs text-muted-foreground",children:[N==="rows"?"Row":"Column"," totals and expansion"]}),e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Kn,{label:"Grand total",value:n.presentation.totals[N].grand,onChange:f=>h({totals:{...n.presentation.totals,[N]:{...n.presentation.totals[N],grand:f}}})}),e.jsx(Xe,{label:"Default expanded levels",value:String(Math.min(n.defaultView[N].depth,Math.max(0,n.spec[N].length-1))),options:Array.from({length:Math.max(1,n.spec[N].length)},(f,g)=>({value:String(g),label:g===0?"Collapsed":String(g)})),onChange:f=>b({kind:"defaults",defaultView:{...n.defaultView,[N]:{...n.defaultView[N],depth:Number(f)}}})})]})]})]},N)),s.kind==="field"&&n.spec.measures.some(N=>N.id===s.id)&&e.jsx("section",{"aria-label":"Values",className:"space-y-2",children:n.spec.measures.filter(N=>N.id===s.id).map(N=>{const f=bt.getMatrixMeasureLabel(N,n.presentation);return e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"min-w-0":"min-w-0 border-b pb-2",children:[e.jsx("div",{className:"flex min-w-0 items-center justify-between gap-1",children:e.jsxs("span",{className:"truncate text-xs font-medium",title:f,children:[f,N.kind==="aggregate"?` (${N.aggregate})`:""]})}),e.jsxs("details",{open:(s==null?void 0:s.kind)==="field"?!0:void 0,children:[e.jsxs("summary",{className:`cursor-pointer py-1 text-xs text-muted-foreground ${(s==null?void 0:s.kind)==="field"?"hidden":""}`,children:[f," settings"]}),e.jsxs("div",{className:(s==null?void 0:s.kind)==="field"?"space-y-2 pt-2":"space-y-2 py-2",children:[e.jsx(Et,{label:"Measure label",value:n.presentation.measureLabels[N.id]??"",onChange:g=>{const D={...n.presentation.measureLabels};g?D[N.id]=g:delete D[N.id],h({measureLabels:D})}}),N.kind==="aggregate"&&e.jsx(Xe,{label:"Aggregation",value:N.aggregate,options:et.getFieldAggregationOptions(m(N.field)).filter(g=>at.matrixAggregateSchema.safeParse(g.value).success).map(({value:g})=>({value:g,label:g})),onChange:g=>b({kind:"structure",measures:n.spec.measures.map(D=>D.id===N.id?{...N,aggregate:at.matrixAggregateSchema.parse(g)}:D)})}),j(N.id,"measureFormats")]})]})]},N.id)})}),s.kind==="table"&&e.jsxs("section",{"aria-label":"Presentation",className:"space-y-2 border-b p-3",children:[e.jsx("h2",{className:"text-xs font-semibold",children:"Presentation"}),e.jsx(Xe,{label:"Row layout",value:n.presentation.layout.kind,options:[{value:"compact",label:"Compact"},{value:"tabular",label:"Tabular"}],onChange:N=>h({layout:N==="compact"?{kind:"compact"}:{kind:"tabular",repeatLabels:!1}})}),n.presentation.layout.kind==="tabular"&&e.jsx(Bs,{label:"Repeat row labels",checked:n.presentation.layout.repeatLabels,onChange:N=>h({layout:{kind:"tabular",repeatLabels:N}})}),e.jsx(Et,{label:"Empty cell text",value:n.presentation.absence.emptyText,onChange:N=>h({absence:{...n.presentation.absence,emptyText:N}})}),e.jsx(Et,{label:"Null cell text",value:n.presentation.absence.nullText,onChange:N=>h({absence:{...n.presentation.absence,nullText:N}})})]}),s.kind==="conditional-formatting"&&e.jsxs("section",{"aria-label":"Conditional formatting",className:"min-w-0 space-y-2 p-3",children:[e.jsx("h2",{className:"text-xs font-semibold",children:"Conditional formatting"}),e.jsx(El,{value:n,change:b,scopeSelection:i})]})]})}function Is({fieldId:s,section:n="table"}){const r=t.useEditorStore(l=>l.card),o=t.useEditorStore(l=>l.actions.updateCard),i=t.useEditorStore(l=>l.matrixSelection),d=a.useMatrixEditorCatalog(r),c=je.readMatrixEditorConfig(r);return c.status==="invalid"?e.jsx("div",{role:"alert",className:"p-3 text-xs text-destructive",children:"Invalid Matrix configuration. Repair or reset the card definition."}):c.status==="absent"?e.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:"No fields selected"}):e.jsx(Il,{value:c.config,section:s?{kind:"field",id:s}:{kind:n},scopeSelection:(i==null?void 0:i.cardId)===r.id?i.coordinate:void 0,bindings:r.controlBindings,availableFields:d.catalog.map(l=>({...l.field,dataType:at.normalizeAnalyticsCatalogDataType(l.resolvedField.dataType)})),onChange:(l,u,x,m)=>{const b=a.applyMatrixEditorResult(r,{config:l,notices:u,bindings:m});o(r.id,b.card)}})}const Dl={green:"#16a34a",red:"#dc2626",neutral:"#6b7280"};function kl(s){return s&&(Dl[s]??s)}function Ma({value:s,onChange:n,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:i=>n({displayMode:i}),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:i=>{if(i.target.value===""){n({precision:void 0});return}const d=Number(i.target.value);Number.isInteger(d)&&d>=0&&d<=6&&n({precision:d})},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:i=>n({indicatorStyle:i}),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:i=>n({position:i}),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:i=>n({showColor:i})})]}),s.showColor!==!1&&e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase","#16a34a"],["decrease","Decrease","#dc2626"],["neutral","No change","#6b7280"]].map(([i,d,c])=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-24 shrink-0 text-xs text-muted-foreground",children:d}),e.jsx(a.ColorField,{value:kl(o[i]||c),onChange:l=>n({colors:{...o,[i]:l||c}}),defaultValue:c,ariaLabel:`${d} color`,allowEmpty:!1})]},i))}),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:i=>n({conditionalLabel:i})})]}),s.conditionalLabel?e.jsx("div",{className:"space-y-1.5",children:[["increase","Increase"],["decrease","Decrease"],["neutral","No change"]].map(([i,d])=>{var c;return e.jsx(t.Input,{"aria-label":`${d} label`,value:((c=s.conditionalLabels)==null?void 0:c[i])||d,onChange:l=>n({conditionalLabels:{...s.conditionalLabels,[i]:l.target.value}}),className:"h-7 text-xs"},i)})}):e.jsx(t.Input,{"aria-label":"Comparison label",value:s.labelName||"",onChange:i=>n({labelName:i.target.value}),placeholder:"Previous",className:"h-7 text-xs"})]})}function Ml(){var b,h,p,j,N;const s=t.useEditorStore(f=>f.card),{setCardPreferences:n}=t.useEditorActions(),r=a.useEffectiveEditorCardType(),o=((b=s.config)==null?void 0:b.metricColumns)||[],i=o.length===2&&(((h=s.config)==null?void 0:h.groupByColumns)||[]).length===0,d=o.some(f=>{var g;return((g=f.comparison)==null?void 0:g.mode)==="explicit"});if(!a.COMPARISON_PRESENTATION_SUPPORTED_CHART_TYPES.includes(r))return null;const l=((p=s.preferences)==null?void 0:p.comparisonPresentation)||{},u=f=>n({...s.preferences,comparisonPresentation:{...l,...f}}),x=r==="kpi"&&((j=s.preferences)==null?void 0:j.metricPairComparisonEnabled)===!0,m=d||x;return e.jsxs(a.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(a.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(Cr,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(a.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:((N=s.preferences)==null?void 0:N.inheritGlobalComparison)!==!1,onCheckedChange:f=>{const g={...s.preferences};f?delete g.inheritGlobalComparison:g.inheritGlobalComparison=!1,n(g)}})]}),r==="kpi"&&i&&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:x,onCheckedChange:f=>n({...s.preferences,metricPairComparisonEnabled:f})})]}),d&&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:l.showComparison!==!1,onCheckedChange:f=>u({showComparison:f})})]}),m&&e.jsx(Ma,{value:l,onChange:u,showPosition:r==="kpi"&&i})]})]})}function Aa({cardType:s,queryResultColumns:n,focusSection:r,focusRequestId:o}){var V,$,Q;const i=t.useEditorStore(U=>U.card),d=t.useEditorStore(U=>U.queryResultColumns),c=t.useEditorStore(U=>U.queryResultColumnKeyMap),l=t.useEditorStore(U=>{var J;return(J=U.card)==null?void 0:J.preferences}),u=l==null?void 0:l.tablePrefs,x=t.useEditorStore(U=>U.actions.setCardPreferences),m=t.useEditorStore(U=>U.actions.updateTableConditionalFormatting),b=((V=i.config)==null?void 0:V.metricColumns)||[],h=s??i.type,p=n??d,j=i.type===h?i:{...i,type:h},N=a.getTableConditionalFormattingColumnOptions(j,p,c),f=a.getTableOutputColumnOptions(j,p),g=h==="matrixTable"||a.supportsTableConditionalFormatting(h),D=h==="table",I=h==="table",w=(($=N[0])==null?void 0:$.value)||"",S=a.resolveTableConditionalFormatting(a.normalizeConditionalFormatting((Q=l==null?void 0:l.tablePrefs)==null?void 0:Q.conditionalFormatting),a.resolveTableFormattingColumns(j,p,c)),M=a.resolveTablePresentationStyle(u),A=a.isEligibleFlatTableTotalsCard(j),F=a.hasFlatTableTotalsBehavior(j),[E,C]=v.useState("style");v.useEffect(()=>{if(r==="style"){C("style");return}if(r==="columns"&&I){C("columns");return}r==="conditional-formatting"&&g&&C("conditional-formatting")},[I,g,o,r]);const T=b.some(U=>{var J;return((J=U.comparison)==null?void 0:J.mode)==="explicit"}),L=(l==null?void 0:l.comparisonPresentation)||{},k=U=>{x({...l,comparisonPresentation:{...L,...U}})},R=U=>{m({version:1,rules:U})},y=U=>{x({...l,tablePrefs:{...u,density:U}})},_=U=>{x({...l,tablePrefs:{...u,tableStyle:{...u==null?void 0:u.tableStyle,...U}}})},O=U=>{var J;_({totals:{...(J=u==null?void 0:u.tableStyle)==null?void 0:J.totals,...U}})},P=U=>{var J;x({...l,tablePrefs:{...u,tableStyle:{...u==null?void 0:u.tableStyle,totals:{...(J=u==null?void 0:u.tableStyle)==null?void 0:J.totals,enabled:U}}}})},B=(U,J)=>{x({...l,tablePrefs:{...u,columnVisibility:a.setTableColumnVisibility(u==null?void 0:u.columnVisibility,U,J)}})},Y=()=>{x({...l,tablePrefs:{...u,columnVisibility:a.showAllTableColumns()}})},q=()=>{x({...l,tablePrefs:{...u,density:a.TABLE_PRESENTATION_DEFAULT_STYLE.density,tableStyle:{headerStyle:a.TABLE_PRESENTATION_DEFAULT_STYLE.headerStyle,headerWrapText:a.TABLE_PRESENTATION_DEFAULT_STYLE.headerWrapText,stripedRows:a.TABLE_PRESENTATION_DEFAULT_STYLE.stripedRows,wrapText:a.TABLE_PRESENTATION_DEFAULT_STYLE.wrapText,totals:{enabled:A?F:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.enabled,backgroundColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.backgroundColor,textColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.textColor,fontWeight:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.fontWeight,borderTop:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTop,borderTopStyle:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopStyle,borderTopColor:a.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE.borderTopColor}}}})},z=T?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:U=>k({showComparison:U})})]}),e.jsx(Ma,{value:L,onChange:k})]}):null;return e.jsx("div",{className:"px-4 py-3",children:e.jsxs(t.Tabs,{value:E,onValueChange:U=>C(U),className:"space-y-4",children:[e.jsxs(t.TabsList,{variant:"underline",children:[e.jsx(t.TabsTrigger,{value:"style",children:"Appearance"}),I?e.jsx(t.TabsTrigger,{value:"columns",children:"Columns"}):null,e.jsx(t.TabsTrigger,{value:"conditional-formatting",disabled:!g,children:"Conditional formatting"})]}),e.jsxs(t.TabsContent,{value:"style",className:"mt-0",children:[e.jsx(a.TablePresentationSettings,{style:M,onDensityChange:y,onStyleChange:_,showFullStyle:D,showBorderStyle:!1,totals:D&&A?{enabled:F,onEnabledChange:P,onStyleChange:O}:void 0,extraSection:z,onReset:D?q:void 0}),h==="matrixTable"&&e.jsx(Is,{section:"table"})]}),e.jsx(t.TabsContent,{value:"columns",className:"mt-0",children:I?e.jsx(a.TableColumnVisibilitySettings,{columns:f,columnVisibility:u==null?void 0:u.columnVisibility,onColumnVisibilityChange:B,onShowAllColumns:Y}):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:h==="matrixTable"?e.jsx(Is,{section:"conditional-formatting"}):g?w?e.jsx(a.DataTableConditionalFormattingSettings,{columnId:w,availableColumns:N,conditionalRules:S.rules,onConditionalRulesChange:R,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 Al(){var i;const s=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:n}=t.useEditorStore(d=>d.actions),r=(i=s==null?void 0:s.textVisualOptions)!=null&&i.isDynamicText?"dynamic":"static";function o(d){n({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:d==="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 Ll(){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(Al,{}),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 Fl({color:s,onColorChange:n,onClose:r}){const[o,i]=v.useState(0),[d,c]=v.useState(100),[l,u]=v.useState(50),[x,m]=v.useState(s);v.useEffect(()=>{const f=Un(s);if(f){const g=Gn(f.r,f.g,f.b);i(g.h),c(g.s),u(g.l),m(s)}},[s]);const b=f=>{i(f),p(f,d,l)},h=f=>{const g=f.currentTarget.getBoundingClientRect(),D=Math.max(0,Math.min(1,(f.clientX-g.left)/g.width)),I=Math.max(0,Math.min(1,(f.clientY-g.top)/g.height)),w=D*100,S=(1-I)*100;c(w),u(S),p(o,w,S)},p=(f,g,D)=>{const I=Pl(f,g,D),w=Rl(I.r,I.g,I.b);m(w)},j=f=>{if(m(f),/^#[0-9A-Fa-f]{6}$/.test(f)){const g=Un(f);if(g){const D=Gn(g.r,g.g,g.b);i(D.h),c(D.s),u(D.l)}}},N=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),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:h,onMouseMove:f=>{f.buttons===1&&h(f)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${d}%`,top:`${100-l}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:o,onChange:f=>b(Number(f.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:x,onChange:f=>j(f.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:x}}),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:N,children:"OK"})]})]})}function Un(s){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(s);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Rl(s,n,r){return"#"+((1<<24)+(s<<16)+(n<<8)+r).toString(16).slice(1)}function Gn(s,n,r){s/=255,n/=255,r/=255;const o=Math.max(s,n,r),i=Math.min(s,n,r);let d=0,c=0;const l=(o+i)/2;if(o!==i){const u=o-i;switch(c=l>.5?u/(2-o-i):u/(o+i),o){case s:d=((n-r)/u+(n<r?6:0))/6;break;case n:d=((r-s)/u+2)/6;break;case r:d=((s-n)/u+4)/6;break}}return{h:Math.round(d*360),s:Math.round(c*100),l:Math.round(l*100)}}function Pl(s,n,r){s/=360,n/=100,r/=100;let o,i,d;if(n===0)o=i=d=r;else{const c=(x,m,b)=>(b<0&&(b+=1),b>1&&(b-=1),b<.16666666666666666?x+(m-x)*6*b:b<.5?m:b<.6666666666666666?x+(m-x)*(.6666666666666666-b)*6:x),l=r<.5?r*(1+n):r+n-r*n,u=2*r-l;o=c(u,l,s+1/3),i=c(u,l,s),d=c(u,l,s-1/3)}return{r:Math.round(o*255),g:Math.round(i*255),b:Math.round(d*255)}}const Ol=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function Bl(){var S,M,A,F,E,C,T,L,k,R;const s=t.useEditorStore(y=>y.card),n=t.useEditorStore(y=>{var _;return(_=y.card)==null?void 0:_.preferences}),r=a.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:i}=t.useEditorActions(),d=v.useMemo(()=>r!==s.type?{...s,type:r}:s,[s,r]),{data:c}=a.useEditorCardQuery(d),[l,u]=v.useState({}),[x,m]=v.useState(null),[b,h]=v.useState(null),p=v.useMemo(()=>{var P,B,Y,q,z,V,$;if(!(c!=null&&c.records)||c.records.length===0)return[];const y=r==="stackedBar"||r==="stackedLine",_=r==="bar"||r==="line"||r==="horizontalBar"||r==="bullet"||r==="combo"||r==="area"||r==="stackedArea",O=((P=s==null?void 0:s.config)==null?void 0:P.pivotByColumns)&&s.config.pivotByColumns.length>0;if((y||_)&&O){if(c.pivotSchema&&Array.isArray(c.pivotSchema)){const Q=new Set;return c.pivotSchema.forEach(U=>{U.alias&&Q.add(U.alias)}),Array.from(Q)}if(c.records.length>0){const Q=c.records[0],U=Object.keys(Q),J=new Set;(B=s==null?void 0:s.config)!=null&&B.groupByColumns&&s.config.groupByColumns.forEach(ue=>{J.add(ue.label||ue.name),J.add(ue.alias||ue.name)});const W=new Set;return(Y=s==null?void 0:s.config)!=null&&Y.metricColumns&&s.config.metricColumns.forEach(ue=>{const fe=ue.alias||ue.name;W.add(fe),W.add(`${fe}_count`),W.add(`${fe}_sum`),W.add(`${fe}_avg`),W.add(`${fe}_min`),W.add(`${fe}_max`);const be=ue.entityName||ue.qualifiedEntityName;be&&(W.add(`${be}_${fe}`),W.add(`${be}_${fe}_count`))}),U.filter(ue=>!J.has(ue)&&!W.has(ue))}}if((_||y)&&!O&&((z=(q=s==null?void 0:s.config)==null?void 0:q.metricColumns)!=null&&z.length))return s.config.metricColumns.map(Q=>Q.alias||Q.label||Q.name);if(($=(V=s==null?void 0:s.config)==null?void 0:V.groupByColumns)!=null&&$.length){const Q=s.config.groupByColumns[0],U=Q.label||Q.name,J=new Set;return c.records.forEach(W=>{const ee=W[U];ee!=null&&J.add(String(ee))}),Array.from(J)}return[]},[c,(S=s==null?void 0:s.config)==null?void 0:S.groupByColumns,(M=s==null?void 0:s.config)==null?void 0:M.pivotByColumns,(A=s==null?void 0:s.config)==null?void 0:A.metricColumns,r]),j=v.useMemo(()=>a.getDefaultChartColors(),[]);v.useEffect(()=>{const y={};p.forEach((_,O)=>{y[_]=a.getColorForValue(_,O,n==null?void 0:n.colorConfig)}),u(y)},[p,n==null?void 0:n.colorConfig,j]);const N=(y,_)=>{const O={...l,[y]:_};u(O);const P={...n||{},colorConfig:{segments:O}};o(P);const B={...s,preferences:P};i(B)},f=(y,_)=>{var z;const O=j[_%j.length],{[y]:P,...B}=((z=n==null?void 0:n.colorConfig)==null?void 0:z.segments)||{},Y={...n||{},colorConfig:{segments:B}};o(Y);const q={...s,preferences:Y};i(q),u(V=>({...V,[y]:O}))};if(!p.length||!((s==null?void 0:s.type)==="stackedBar"||(s==null?void 0:s.type)==="stackedLine"?((E=(F=s==null?void 0:s.config)==null?void 0:F.groupByColumns)==null?void 0:E.length)||((T=(C=s==null?void 0:s.config)==null?void 0:C.pivotByColumns)==null?void 0:T.length):(k=(L=s==null?void 0:s.config)==null?void 0:L.groupByColumns)==null?void 0:k.length)||["table","kpi","text","custom","heatmap"].includes(r))return null;const I=()=>{const y={...n||{},colorConfig:{segments:{}}};o(y);const _={...s,preferences:y};i(_);const O={};p.forEach((P,B)=>{O[P]=a.getColorForValue(P,B,void 0)}),u(O)},w=Object.keys(((R=n==null?void 0:n.colorConfig)==null?void 0:R.segments)||{}).length>0;return e.jsxs(a.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(a.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(hr.Palette,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(a.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:w&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:I,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:p.map((y,_)=>{const O=a.isDefaultColor(l[y],_),P=!O;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Popover,{open:x===y,onOpenChange:B=>m(B?y: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:l[y]}})}),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:j.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",l[y]===B?"border-gray-900":"border-transparent"),style:{backgroundColor:B},onClick:()=>{N(y,B),m(null)},children:[Y===_%j.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:Ol.map((B,Y)=>e.jsx("button",{className:t.cn("h-5 w-5 rounded border transition-all hover:scale-110",l[y]===B?"border-2 border-gray-900":B==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:B},onClick:()=>{N(y,B),m(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:()=>{h({value:y,color:l[y]}),m(null)},children:"Custom color"}),!O&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{f(y,_),m(null)},children:[e.jsx(t.RotateCcw,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:y}),P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},y)})}),b&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>h(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(Fl,{color:b.color,onColorChange:y=>{N(b.value,y),h(null)},onClose:()=>h(null)})})]})]})})]})}function lt({value:s,onSave:n,placeholder:r="",type:o="text",className:i=""}){const[d,c]=v.useState(s??""),[l,u]=v.useState(!1);v.useEffect(()=>{c(s??"")},[s]);const x=()=>{n(d),u(!1)},m=()=>{c(s??""),u(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(t.Input,{placeholder:r,type:o,value:l?d:s??"",onChange:b=>{c(b.target.value),u(!0)},onFocus:()=>u(!0),onClick:b=>b.stopPropagation(),className:"h-8 text-xs",onPointerDown:b=>b.stopPropagation(),onKeyDown:b=>{b.stopPropagation(),b.key==="Enter"&&l&&d!==s?x():b.key==="Escape"&&m()},"aria-label":r||"Edit field"}),l&&d!==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:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:m,children:e.jsx(le.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function vs({axis:s,label:n,type:r,config:o,onChange:i,defaultTitle:d,hidePosition:c}){var j,N,f,g,D,I,w,S,M,A,F,E,C,T;const l=a.normalizeContextFormatMode({formatMode:o==null?void 0:o.formatMode,formatOptions:o==null?void 0:o.formatOptions}),u=(L,k)=>{i({...o??{},[L]:k})},x=(L,k)=>{var O,P,B,Y;const R=L==="enabled"&&k===!0,y=(O=o==null?void 0:o.name)==null?void 0:O.text,_=R&&!y&&d;i({...o??{},name:{...o==null?void 0:o.name,enabled:L==="enabled"?k:((P=o==null?void 0:o.name)==null?void 0:P.enabled)??!1,text:L==="text"?k:_?d:y,fontSize:L==="fontSize"?k:(B=o==null?void 0:o.name)==null?void 0:B.fontSize,fontWeight:L==="fontWeight"?k:(Y=o==null?void 0:o.name)==null?void 0:Y.fontWeight}})},m=(L,k)=>{var R,y;i({...o??{},labels:{enabled:L==="enabled"?k:((R=o==null?void 0:o.labels)==null?void 0:R.enabled)??!0,rotation:L==="rotation"?k:(y=o==null?void 0:o.labels)==null?void 0:y.rotation}})},b=(L,k)=>{i({...o??{},scale:{...o==null?void 0:o.scale,[L]:k===""?"auto":Number(k)}})},h=s==="x"?["auto","top","bottom"]:["auto","left","right"],p=["auto","0","45","90","-45","-90"];return e.jsxs(a.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(a.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:n})})}),e.jsx(t.Switch,{size:"sm",checked:(o==null?void 0:o.enabled)!==!1,onCheckedChange:L=>u("enabled",L),onClick:L=>L.stopPropagation()})]}),e.jsxs(a.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(a.Checkbox,{id:`${s}-title-enabled`,checked:((j=o==null?void 0:o.name)==null?void 0:j.enabled)??!1,onCheckedChange:L=>x("enabled",L===!0)}),e.jsx(t.Label,{htmlFor:`${s}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((N=o==null?void 0:o.name)==null?void 0:N.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(lt,{placeholder:`${n} title`,value:((f=o==null?void 0:o.name)==null?void 0:f.text)||"",onSave:L=>x("text",L),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(lt,{type:"number",placeholder:"12",value:String(((g=o==null?void 0:o.name)==null?void 0:g.fontSize)||12),onSave:L=>x("fontSize",Number(L)||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:((D=o==null?void 0:o.name)==null?void 0:D.fontWeight)||"normal",onValueChange:L=>x("fontWeight",L),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"})]})]})]})]})]})]}),!c&&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:L=>u("position",L),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:h.map(L=>e.jsx(t.SelectItem,{value:L,className:"text-xs",children:L==="auto"?"Auto (Default)":t.titleCase(L)},L))})]})]}),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:((I=o==null?void 0:o.labels)==null?void 0:I.enabled)!==!1,onCheckedChange:L=>m("enabled",L)})]}),((w=o==null?void 0:o.labels)==null?void 0:w.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(((S=o==null?void 0:o.labels)==null?void 0:S.rotation)||"auto"),onValueChange:L=>m("rotation",L==="auto"?"auto":Number(L)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:p.map(L=>e.jsx(t.SelectItem,{value:L,className:"text-xs",children:L==="auto"?"Auto (Default)":`${L}°`},L))})]})]})]}),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:l==="override",onCheckedChange:L=>i({...o,formatMode:L?"override":"inherit"})})]}),l==="override"&&e.jsx(Ut,{formatOptions:(o==null?void 0:o.formatOptions)||{},onFormatOptionsChange:L=>i({...o,formatMode:"override",formatOptions:L}),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(lt,{type:"number",placeholder:"auto",value:((M=o==null?void 0:o.scale)==null?void 0:M.min)==="auto"||((A=o==null?void 0:o.scale)==null?void 0:A.min)===void 0?"":String(o.scale.min),onSave:L=>b("min",L),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(lt,{type:"number",placeholder:"auto",value:((F=o==null?void 0:o.scale)==null?void 0:F.max)==="auto"||((E=o==null?void 0:o.scale)==null?void 0:E.max)===void 0?"":String(o.scale.max),onSave:L=>b("max",L),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(lt,{type:"number",placeholder:"auto",value:((C=o==null?void 0:o.scale)==null?void 0:C.stepSize)==="auto"||((T=o==null?void 0:o.scale)==null?void 0:T.stepSize)===void 0?"":String(o.scale.stepSize),onSave:L=>b("stepSize",L),className:""})})]})]})]})]})]})}function ys(s,n,r){var d,c,l;if(s==="x"){const u=(c=(d=n==null?void 0:n.config)==null?void 0:d.groupByColumns)==null?void 0:c[0];return(u==null?void 0:u.label)||(u==null?void 0:u.name)||""}const o=((l=n==null?void 0:n.config)==null?void 0:l.metricColumns)||[],i=(r==null?void 0:r.datasetOptions)||[];if(s==="y"){const u=o.filter((x,m)=>{const b=i.find(h=>h.idx===m);return!b||b.yAxisId!=="y2"});return u.length===1&&(u[0].label||u[0].name)||""}if(s==="y2"){const u=o.filter((x,m)=>{const b=i.find(h=>h.idx===m);return(b==null?void 0:b.yAxisId)==="y2"});return u.length===1&&(u[0].label||u[0].name)||""}return""}function Vl(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),{setCardPreferences:r,updateCardInFrame:o}=t.useEditorActions(),i=a.useEffectiveEditorCardType();if(!s||["tornado","pyramid","kpi","treemap"].includes(i))return null;const d=a.AxisConfigurator.getAxisInfo(i,n);if(!d.hasXAxis&&!d.hasYAxis)return null;const c=(u,x)=>{let m;u==="x"?m="xAxisConfig":u==="y"?m="yAxisConfig":m="secondaryYAxisConfig";const b={...n||{},[m]:x};r(b);const h={...s,preferences:b};o(h)},l=d.hasY2Axis&&i==="combo";return e.jsxs(a.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(a.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(a.AccordionContent,{className:"pt-2",children:e.jsxs(a.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[d.hasXAxis&&e.jsx(vs,{axis:"x",label:"X-Axis",type:d.xAxisType,config:a.mergeAxisConfig(a.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:u=>c("x",u),defaultTitle:ys("x",s,n)}),d.hasYAxis&&e.jsx(vs,{axis:"y",label:l?"Y-Axis (Left)":"Y-Axis",type:d.yAxisType,config:a.mergeAxisConfig(a.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:u=>c("y",u),defaultTitle:ys("y",s,n)}),l&&e.jsx(vs,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:a.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:u=>c("y2",u),defaultTitle:ys("y2",s,n),hidePosition:!0})]})})]})}function _l(){const s=t.useEditorStore(b=>b.card),n=a.useEffectiveEditorCardType(),r=t.useEditorStore(b=>{var h,p,j,N;return(N=(j=(p=(h=b.card)==null?void 0:h.preferences)==null?void 0:p.chartOptions)==null?void 0:j.plugins)==null?void 0:N.legend}),{setLegendOptions:o}=t.useEditorActions();if(!s||!a.chartSupportsLegend(n))return null;const i=a.getDefaultLegendConfig(n),d=(i==null?void 0:i.display)??!0,c=(i==null?void 0:i.position)??"top",l=(i==null?void 0:i.align)??"center",u=(b,h)=>{const p={...r,[b]:h};o(p)},x=["top","bottom","left","right"],m=["start","center","end"];return e.jsxs(a.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(a.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(Nr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(a.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)??d,onCheckedChange:b=>u("display",b)})]}),((r==null?void 0:r.display)??d)&&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)||c,onValueChange:b=>u("position",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:x.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]}),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)||l,onValueChange:b=>u("align",b),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:m.map(b=>e.jsx(t.SelectItem,{value:b,className:"text-xs",children:t.titleCase(b)},b))})]})]})]})]})})]})}function Yl(){var k,R,y,_,O,P,B;const s=t.useEditorStore(Y=>Y.card),n=a.useEffectiveEditorCardType(),r=t.useEditorStore(Y=>{var q,z;return(z=(q=Y.card)==null?void 0:q.preferences)==null?void 0:z.dataLabelsConfig}),o=t.useEditorStore(Y=>{var q;return(q=Y.card)==null?void 0:q.preferences}),{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!a.chartSupportsDataLabels(n))return null;const c=n==="bullet"?((k=o==null?void 0:o.bulletConfig)==null?void 0:k.orientation)??(((R=o==null?void 0:o.chartOptions)==null?void 0:R.indexAxis)==="x"?"vertical":"horizontal"):void 0,l=c!=null?c==="horizontal":((y=o==null?void 0:o.chartOptions)==null?void 0:y.indexAxis)==="y",u=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",m=n==="bubble"||n==="scatter",b=(O=(_=o==null?void 0:o.chartOptions)==null?void 0:_.plugins)==null?void 0:O.datalabels,h=(b==null?void 0:b.display)!==!1&&((b==null?void 0:b.anchor)||(b==null?void 0:b.align)),p=a.getDefaultDataLabelsConfig(n,s.preferences),j=r??p,N=(p==null?void 0:p.enabled)??h??!1,f=(r==null?void 0:r.enabled)!==void 0?r.enabled:N,g=(Y,q)=>{const $={...p??{},...r??{},[Y]:q};Y==="enabled"&&($.display=q,q&&m&&!$.position&&($.position="bottom")),Y==="position"&&m&&($.position="bottom"),Y==="formatMode"&&q==="inherit"&&($.format=void 0,$.formatOptions=void 0);const Q={...s.preferences||{},dataLabelsConfig:$};i(Q);const U={...s,preferences:Q};d(U)},D=(Y,q)=>{const z=r??{},$={...p??{},...z,font:{...z.font||{},[Y]:q}},Q={...s.preferences||{},dataLabelsConfig:$};i(Q);const U={...s,preferences:Q};d(U)},I=()=>{const Y=n;return Y==="stackedBar"||Y==="stackedLine"||Y==="pie"||Y==="doughnut"?"center":l?"right":"top"},w=n!=="treemap"&&n!=="heatmap",S=n!=="treemap",M=I();let A=[];if(w)if(m)A=["bottom"];else if(u||x)A=["center"];else{const Y=l?["center","left","right"]:["center","top","bottom"];A=["auto",...n==="bullet"?Y:Y.filter(z=>z!==M),"custom"]}const F=()=>t.titleCase(M),E=["center","start","end"],C=["center","start","end","top","bottom"],T=(j==null?void 0:j.formatMode)||(j!=null&&j.format&&!["auto"].includes(j.format)?"override":"inherit"),L=(j==null?void 0:j.format)==="none";return e.jsxs(a.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(a.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(Rr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(a.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:f,onCheckedChange:Y=>g("enabled",Y)})]}),f&&e.jsxs(e.Fragment,{children:[w&&!u&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(t.Select,{value:m?(j==null?void 0:j.position)||"bottom":(j==null?void 0:j.position)||"auto",onValueChange:Y=>g("position",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:A.map(Y=>e.jsx(t.SelectItem,{value:Y,className:"text-xs",children:Y==="auto"?F():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=>g("showTotal",Y)})]}),(j==null?void 0:j.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:(j==null?void 0:j.anchor)||"center",onValueChange:Y=>g("anchor",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:E.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((j==null?void 0:j.align)||"center"),onValueChange:Y=>g("align",Y),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:C.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:T==="override",onCheckedChange:Y=>g("formatMode",Y?"override":"inherit")})]}),T==="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:L,onCheckedChange:Y=>{const q=r??{},V={...p??{},...q,formatMode:"override",format:Y?"none":void 0,formatOptions:Y?void 0:q.formatOptions},$={...s.preferences||{},dataLabelsConfig:V};i($),d({...s,preferences:$})}})]}),!L&&e.jsx(Ut,{formatOptions:(j==null?void 0:j.formatOptions)||{},onFormatOptionsChange:Y=>{const V={...p??{},...r??{},formatMode:"override",format:Y.type&&Y.type!=="auto"?Y.type:void 0,formatOptions:Y},$={...s.preferences||{},dataLabelsConfig:V};i($),d({...s,preferences:$})},showTitle:!1})]})]}),S&&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(lt,{type:"number",placeholder:"12",value:String(((P=j==null?void 0:j.font)==null?void 0:P.size)||12),onSave:Y=>D("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=j==null?void 0:j.font)==null?void 0:B.weight)||"normal",onValueChange:Y=>D("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:(j==null?void 0:j.color)==="auto"||!(j!=null&&j.color)?"auto":"custom",onValueChange:Y=>{Y==="auto"&&g("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(lt,{type:"number",placeholder:"0",value:String((j==null?void 0:j.rotation)||0),onSave:Y=>g("rotation",Number(Y)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function zl(){var d;const s=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.type}),n=t.useEditorStore(c=>{var l;return(l=c.card)==null?void 0:l.preferences}),{setCardPreferences:r}=t.useEditorActions();if(s!=="treemap")return null;const o=((d=n==null?void 0:n.chartOptions)==null?void 0:d.treemapColorMode)??"branch",i=c=>{const l={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:c}};r(l)};return e.jsxs(a.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(a.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(a.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(a.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(a.RadioGroup,{value:o,onValueChange:c=>i(c??"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(a.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(a.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 ql=Object.keys(a.HEATMAP_PRESET_PALETTES);function $l(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},d=i.colorPalette??"green",c=i.legendPosition??"bottom",l=v.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...a.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),u=h=>{const p={...i,...h};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...a.DEFAULT_HEATMAP_CUSTOM_RANGE]),r({...n||{},heatmapConfig:p})},x=h=>{u({colorPalette:h,colorRange:h==="custom"?i.colorRange??[...a.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(h,p)=>{const j=[...l];j[h]=p,u({colorPalette:"custom",colorRange:j})},b=h=>{u({legendPosition:h})};return o?e.jsxs(a.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(a.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(a.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(a.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(a.RadioGroup,{value:d,onValueChange:h=>x(h??"blue"),className:"space-y-3",children:[ql.map(h=>{const p=a.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(a.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(t.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(t.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),d==="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(a.ColorField,{value:l[0],onChange:h=>m(0,h??"#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(a.ColorField,{value:l[1],onChange:h=>m(1,h??"#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:c,onValueChange:h=>b(h??"bottom"),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:["top","bottom","left","right"].map(h=>e.jsx(t.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}const Hn=["poor","satisfactory","good"];function Qn(s){if(!s)return;const n={...s};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function Kl(){var k,R;const s=t.useEditorStore(y=>y.card.preferences),n=t.useEditorStore(y=>y.card),r=t.useEditorStore(y=>y.isDevMode),{setCardPreferences:o,setChartOrientation:i}=t.useEditorActions(),d=v.useMemo(()=>(s==null?void 0:s.bulletConfig)||{},[s==null?void 0:s.bulletConfig]),l=je.hasValidCardConfig(n==null?void 0:n.config)&&!r,[u,x]=v.useState(d.showRanges??!1),[m,b]=v.useState(d.rangesArePercentages??!1),h=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!l,[p,j]=v.useState(h);v.useEffect(()=>{x(d.showRanges??!1)},[d.showRanges]),v.useEffect(()=>{b(d.rangesArePercentages??!1)},[d.rangesArePercentages]);const N=d.targetValue===void 0?"":String(d.targetValue);v.useEffect(()=>{const y=d.disableAutoComparative?!1:d.comparativeMetricKey!==void 0||!l;j(y)},[d.disableAutoComparative,d.comparativeMetricKey,l]);const f=v.useMemo(()=>{var y,_;return((_=(y=n==null?void 0:n.config)==null?void 0:y.metricColumns)==null?void 0:_.map(O=>{const P=O.label||O.name||O.alias||"";return{value:P,label:P}}))||[]},[(k=n==null?void 0:n.config)==null?void 0:k.metricColumns]);v.useEffect(()=>{var z,V;if(!s||f.length===0)return;const y={};let _=!1;const O=(z=f[1])==null?void 0:z.value;!d.targetMetricKey&&O&&(y.targetMetricKey=O,_=!0);const P=(V=f[2])==null?void 0:V.value;!d.comparativeMetricKey&&!d.disableAutoComparative&&P&&(y.comparativeMetricKey=P,_=!0);const B=f.slice(3),Y={...d.rangeKeys||{}};let q=!1;if(Hn.forEach(($,Q)=>{!Y[$]&&B[Q]&&(Y[$]=B[Q].value,q=!0)}),q&&(y.rangeKeys=Y,_=!0,d.showRanges===void 0&&(y.showRanges=!0)),_){const $=Qn({...d,...y});o({...s,bulletConfig:$})}},[f,d,s,o]);const g=y=>{const _=Qn({...d,...y});o({...s,bulletConfig:_})},D=(y,_)=>{const O={...d.rangeKeys||{},[y]:_.trim()};_.trim()||delete O[y],g({rangeKeys:Object.keys(O).length>0?O:void 0})},I=(y,_)=>{const O=_===""?void 0:Number(_),P={...d.ranges||{}};O===void 0||Number.isNaN(O)?delete P[y]:P[y]=O,g({ranges:Object.keys(P).length?P:void 0})},w=y=>{if(y===""){g({targetValue:void 0});return}const _=Number(y);g({targetValue:Number.isNaN(_)?void 0:_})},S=(y,_)=>{const O=_.trim(),P={...d.rangeLabels||{}};O?P[y]=O:delete P[y],g({rangeLabels:Object.keys(P).length>0?P:void 0})},M=y=>{x(y),g({showRanges:y})},A=y=>{b(y),g({rangesArePercentages:y})},F=d.orientation||(((R=s==null?void 0:s.chartOptions)==null?void 0:R.indexAxis)==="y"?"horizontal":"vertical"),E=y=>{g({orientation:y}),i(y==="horizontal"?"y":"x")},C=[{value:"__none",label:"None"},...f.map(y=>({value:y.value,label:y.label}))],T=C,L=y=>{if(j(y),!y){g({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!l){g({disableAutoComparative:!1});return}if(d.comparativeMetricKey)g({disableAutoComparative:!1});else{const _=f.find(O=>O.value!==d.targetMetricKey);g({comparativeMetricKey:_==null?void 0:_.value,disableAutoComparative:!1})}};return e.jsxs(a.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(a.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(a.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(a.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:F,onValueChange:y=>E(y),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"})]})]})]}),l&&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:d.targetMetricKey||"__none",onValueChange:y=>g({targetMetricKey:y==="__none"?void 0:y}),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"}),f.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),l?e.jsxs(t.Select,{value:d.comparativeMetricKey||"__none",onValueChange:y=>g({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select metric"})}),e.jsx(t.SelectContent,{children:C.map(y=>e.jsx(t.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.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:p,onCheckedChange:y=>L(y)})]}),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(tt,{type:"number",className:"h-8 text-xs",value:N,onCommit:w,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:M})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!u,onChange:y=>A(y.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:Hn.map(y=>{var _,O,P,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:[y," LABEL"]}),e.jsx(tt,{placeholder:`Display label (${y})`,value:((_=d.rangeLabels)==null?void 0:_[y])||"",onCommit:q=>S(y,q),className:"h-8 text-xs"})]}),l?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(t.Select,{value:((O=d.rangeKeys)==null?void 0:O[y])||"__none",onValueChange:q=>{q==="__none"?D(y,""):D(y,q)},children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select column"})}),e.jsx(t.SelectContent,{children:T.map(q=>e.jsx(t.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(t.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN KEY"]}),e.jsx(tt,{placeholder:"Column key",value:((P=d.rangeKeys)==null?void 0:P[y])||"",onCommit:q=>D(y,q),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:[y," VALUE"]}),e.jsx(tt,{type:"number",placeholder:m?"0.80":"Static value",value:((B=d.ranges)==null?void 0:B[y])===void 0?"":String((Y=d.ranges)==null?void 0:Y[y]),onCommit:q=>I(y,q),className:"h-8 text-xs"})]})]},y)})})]})]})]})}function Jn(s){if(!s)return;const n={...s};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function Ul(){var S,M,A,F,E,C,T,L,k,R,y,_;const s=t.useEditorStore(O=>O.card.preferences),n=t.useEditorStore(O=>O.card),r=a.useEffectiveEditorCardType(),o=t.useEditorStore(O=>O.isDevMode),{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions(),c=r==="bubble",l=r==="scatter",u=v.useMemo(()=>(s==null?void 0:s.bubbleScatterConfig)||{},[s==null?void 0:s.bubbleScatterConfig]),m=je.hasValidCardConfig(n==null?void 0:n.config)&&!o,b=v.useMemo(()=>{var O,P;return((P=(O=n==null?void 0:n.config)==null?void 0:O.metricColumns)==null?void 0:P.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(S=n==null?void 0:n.config)==null?void 0:S.metricColumns]),h=v.useMemo(()=>{var O,P;return((P=(O=n==null?void 0:n.config)==null?void 0:O.groupByColumns)==null?void 0:P.map(B=>{const Y=B.label||B.name||B.alias||"";return{value:Y,label:Y}}))||[]},[(M=n==null?void 0:n.config)==null?void 0:M.groupByColumns]),p=v.useMemo(()=>u.enableGrouping!==void 0?u.enableGrouping:!o&&h.length>=2,[u.enableGrouping,o,h.length]),[j,N]=v.useState(p);v.useEffect(()=>{N(p)},[p]);const f=O=>{const P={...s||{},bubbleScatterConfig:O};i(P),n&&d({...n,preferences:P})},g=O=>{i(O),n&&d({...n,preferences:O})};v.useEffect(()=>{if(!s||b.length===0)return;const O={};let P=!1;if(!u.xMetricKey&&b[0]&&(O.xMetricKey=b[0].value,P=!0),!u.yMetricKey&&b[1]&&(O.yMetricKey=b[1].value,P=!0),c&&!u.radiusMetricKey&&b[2]&&(O.radiusMetricKey=b[2].value,P=!0),!u.labelKey&&h[0]&&(O.labelKey=h[0].value,P=!0),p&&!u.groupKey&&h[1]&&(O.groupKey=h[1].value,O.enableGrouping=!0,P=!0),P){const B=Jn({...u,...O});f(B)}},[b,h,u,s,i,c,p]);const D=O=>{const P=Jn({...u,...O});f(P)},I=O=>{N(O),D({enableGrouping:O,groupKey:O?u.groupKey:void 0})};if(!c&&!l)return null;const w=c?a.Circle:a.ChartScatter;return e.jsxs(a.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(a.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(w,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsxs("span",{children:[c?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(a.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"}),m?e.jsxs(t.Select,{value:u.labelKey||"",onValueChange:O=>D({labelKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select label column"})}),e.jsx(t.SelectContent,{children:h.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for labels",value:u.labelKey||"",onCommit:O=>D({labelKey:O})})]}),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:j,onCheckedChange:I})]}),j&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Group By"}),m?e.jsxs(t.Select,{value:u.groupKey||"",onValueChange:O=>D({groupKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select group column"})}),e.jsx(t.SelectContent,{children:h.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:u.groupKey||"",onCommit:O=>D({groupKey:O})})]})]}),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"}),m?e.jsxs(t.Select,{value:u.xMetricKey||"",onValueChange:O=>D({xMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select X metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:u.xMetricKey||"",onCommit:O=>D({xMetricKey:O})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Axis"}),m?e.jsxs(t.Select,{value:u.yMetricKey||"",onValueChange:O=>D({yMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:u.yMetricKey||"",onCommit:O=>D({yMetricKey:O})})]}),c&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Radius"}),m?e.jsxs(t.Select,{value:u.radiusMetricKey||"",onValueChange:O=>D({radiusMetricKey:O}),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(t.SelectContent,{children:b.map(O=>e.jsx(t.SelectItem,{value:O.value,children:O.label},O.value))})]}):e.jsx(tt,{className:"h-8 text-xs",placeholder:"Column name for radius",value:u.radiusMetricKey||"",onCommit:O=>D({radiusMetricKey:O})})]})]}),c&&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:O=>D({radiusScale:O}),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(tt,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((A=u.minRadius)==null?void 0:A.toString())||"",onCommit:O=>D({minRadius:O?Number(O):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(tt,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((F=u.maxRadius)==null?void 0:F.toString())||"",onCommit:O=>D({maxRadius:O?Number(O):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(a.Slider,{value:[u.fixedRadius||10],onValueChange:([O])=>D({fixedRadius:O}),min:3,max:30,step:1,className:"py-2"})]})]}),l&&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(a.Slider,{value:[u.fixedRadius||5],onValueChange:([O])=>D({fixedRadius:O}),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:((C=(E=s==null?void 0:s.xAxisConfig)==null?void 0:E.name)==null?void 0:C.enabled)??!1,onCheckedChange:O=>{var Y,q,z,V;const P=u.xMetricKey||"X Axis",B=u.yMetricKey||"Y Axis";g({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{enabled:O,text:((q=(Y=s==null?void 0:s.xAxisConfig)==null?void 0:Y.name)==null?void 0:q.text)||P}},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{enabled:O,text:((V=(z=s==null?void 0:s.yAxisConfig)==null?void 0:z.name)==null?void 0:V.text)||B}}})}})]}),((L=(T=s==null?void 0:s.xAxisConfig)==null?void 0:T.name)==null?void 0:L.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(tt,{className:"h-8 text-xs",placeholder:u.xMetricKey||"X Axis",value:((R=(k=s==null?void 0:s.xAxisConfig)==null?void 0:k.name)==null?void 0:R.text)||"",onCommit:O=>{var P;g({...s??{},xAxisConfig:{...s==null?void 0:s.xAxisConfig,name:{...(P=s==null?void 0:s.xAxisConfig)==null?void 0:P.name,enabled:!0,text:O||u.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs",children:"Y Title"}),e.jsx(tt,{className:"h-8 text-xs",placeholder:u.yMetricKey||"Y Axis",value:((_=(y=s==null?void 0:s.yAxisConfig)==null?void 0:y.name)==null?void 0:_.text)||"",onCommit:O=>{var P;g({...s??{},yAxisConfig:{...s==null?void 0:s.yAxisConfig,name:{...(P=s==null?void 0:s.yAxisConfig)==null?void 0:P.name,enabled:!0,text:O||u.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const Gl=[{value:"percentOfTotal",label:"% of Total",description:"Each stage shows percentage of the sum of all values"},{value:"percentOfFirst",label:"% of Stage 1",description:"First stage = 100%, others relative to first stage"}];function Hl(){const s=t.useEditorStore(h=>h.card),n=t.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:r}=t.useEditorActions(),o=(s==null?void 0:s.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},d=i.percentMode??"percentOfTotal",c=i.shrinkFraction??1,l=i.labelThreshold??0,u=h=>{const p={...i,...h};r({...n||{},funnelConfig:p})},x=h=>{u({percentMode:h})},m=h=>{u({shrinkFraction:h[0]})},b=h=>{u({labelThreshold:h[0]})};return o?e.jsxs(a.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(a.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(a.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(a.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(a.RadioGroup,{value:d,onValueChange:h=>x(h),className:"space-y-2",children:Gl.map(h=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(a.RadioGroupItem,{id:`funnel-${h.value}`,value:h.value,className:"mt-0.5"}),e.jsxs(t.Label,{htmlFor:`funnel-${h.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.description})]})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{className:"text-xs font-medium",children:"SEGMENT SHRINK"}),e.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Same Width"}),e.jsx(a.Slider,{value:[c],onValueChange:m,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(c*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(a.Slider,{value:[l],onValueChange:b,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:l===0?"Showing all labels":`Hide labels below ${l}%`})]})]})]}):null}function os(){const s=t.useEditorStore(c=>c.card),{data:n,comparisonMetadata:r}=a.useEditorCardQuery(s),{keys:o}=a.getKeys((n==null?void 0:n.records)||[],r),i=o.slice(1).filter(c=>!je.METADATA_KEYS.includes(c));let d=i;if(["stackedBar","stackedLine"].includes(s.type)){const c=a.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:o[0],pivotKey:o[1],valueKey:o[2]}),{keys:l}=a.getKeys(c);d=l.slice(1)}return{transformedMetricKeys:d,dimensionKeys:o.slice(0,1),keys:o,defaultMetricKeys:i}}const Ql=[{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"}],Jl=[{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)"}],Wl=["center","start","end"],Xl=["center","start","end","top","bottom"];function ls({config:s,onChange:n,isHorizontal:r=!1,showAutoFormat:o=!0,positionOptions:i,showAppearance:d=!0}){var j,N,f,g,D,I;const c=i??(r?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),l=o?["auto","number","currency","percent","none"]:["number","currency","percent","none"],u=(w,S)=>{const M={...s,[w]:S};n(M)},x=(w,S)=>{const M={...s,font:{...(s==null?void 0:s.font)||{},[w]:S}};n(M)},m=(w,S)=>{const M={...s,formatOptions:{...(s==null?void 0:s.formatOptions)||{},[w]:S}};n(M)},b=()=>r?"Right":"Top",h=s||{},p=h.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:h.position||"auto",onValueChange:w=>u("position",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:c.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"?b():w==="custom"?"Custom (Advanced)":t.titleCase(w)},w))})]})]}),h.position==="custom"&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(t.Select,{value:h.anchor||"center",onValueChange:w=>u("anchor",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Wl.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Align"}),e.jsxs(t.Select,{value:String(h.align||"center"),onValueChange:w=>u("align",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Xl.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:t.titleCase(w)},w))})]})]})]}),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:p,onValueChange:w=>u("format",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:l.map(w=>e.jsx(t.SelectItem,{value:w,className:"text-xs",children:w==="auto"&&o?"Auto (Use Axis)":w==="none"?"None (Raw Value)":t.titleCase(w)},w))})]})]}),!["auto","none"].includes(p)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(p)&&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(lt,{type:"number",placeholder:"0",value:String(((j=h.formatOptions)==null?void 0:j.decimalPlaces)??(p==="currency"?2:p==="percent"?1:0)),onSave:w=>m("decimalPlaces",Number(w)),className:""})})]}),p==="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:((N=h.formatOptions)==null?void 0:N.currency)||"USD",onValueChange:w=>m("currency",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ql.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]}),["number","currency"].includes(p)&&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:((f=h.formatOptions)==null?void 0:f.useSuffix)??!1,onCheckedChange:w=>m("useSuffix",w)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Locale"}),e.jsxs(t.Select,{value:((g=h.formatOptions)==null?void 0:g.locale)||"en-US",onValueChange:w=>m("locale",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Jl.map(w=>e.jsx(t.SelectItem,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]}),d&&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(lt,{type:"number",placeholder:"12",value:String(((D=h.font)==null?void 0:D.size)||12),onSave:w=>x("size",Number(w)),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:((I=h.font)==null?void 0:I.weight)||"normal",onValueChange:w=>x("weight",w),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(t.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs",children:"Color"}),e.jsxs(t.Select,{value:h.color==="auto"||!h.color?"auto":"custom",onValueChange:w=>{w==="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(lt,{type:"number",placeholder:"0",value:String(h.rotation||0),onSave:w=>u("rotation",Number(w)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Zl=[{type:"bar",icon:a.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:a.ChartLine,label:"Line"}],ei=[0,1,2,3,4,5,6,8,10],ti=[{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 │"}],si=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ni(){return t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type})!=="combo"?null:e.jsxs(a.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(ai,{})})]})}function ai(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(ri,{metricKey:n,idx:r},n))})}function ri({metricKey:s,idx:n}){var g;const[r,o]=v.useState(!1),i=t.useEditorStore(D=>{var I;return(I=D.card)==null?void 0:I.preferences}),d=t.useEditorStore(D=>{var I,w;return(w=(I=D.card)==null?void 0:I.preferences)==null?void 0:w.datasetOptions}),c=d==null?void 0:d.find(D=>D.idx===n),{setCardPreferences:l}=t.useEditorStore(D=>D.actions),u=(c==null?void 0:c.type)||"bar",x=(c==null?void 0:c.yAxisId)||"y",m=((g=c==null?void 0:c.dataLabels)==null?void 0:g.enabled)??!1,b=u==="line"?a.ChartLine:a.ChartColumnIncreasing;function h(D){const I={idx:n,type:u,yAxisId:x,dataLabels:c==null?void 0:c.dataLabels,...D};if(!c)l({...i||{},datasetOptions:[...d||[],I]});else{const w=d==null?void 0:d.map(S=>S.idx===n?{...S,...I}:S);l({...i||{},datasetOptions:w})}}function p(D){h({type:D})}function j(D){h({yAxisId:D})}function N(D){h({dataLabels:{...c==null?void 0:c.dataLabels,enabled:D}})}function f(D){h({dataLabels:D})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(b,{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:x==="y2"?"Y2":"Y1"})]})]})}),e.jsx(a.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:Zl.map(({type:D,icon:I,label:w})=>{const S=u===D;return e.jsxs("button",{onClick:()=>p(D),className:t.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",S?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(I,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:w})]},D)})})]}),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:x,onValueChange:D=>j(D),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:(c==null?void 0:c.lineStyle)||"solid",onValueChange:D=>h({lineStyle:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:si.map(({value:D,label:I})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:I},D))})]})]}),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((c==null?void 0:c.pointRadius)??3),onValueChange:D=>h({pointRadius:Number(D)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ei.map(D=>e.jsx(t.SelectItem,{value:String(D),className:"text-xs",children:D===0?"None":D},D))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(t.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(t.Select,{value:(c==null?void 0:c.pointStyle)||"circle",onValueChange:D=>h({pointStyle:D}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ti.map(({value:D,label:I})=>e.jsx(t.SelectItem,{value:D,className:"text-xs",children:I},D))})]})]})]})]}),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:N})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ls,{config:c==null?void 0:c.dataLabels,onChange:f,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Cs=[{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"}],oi=[0,1,2,3,4,5,6,8,10],li=[{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 │"}],ii=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function ci(s){return s==null?"origin":s===!1?"false":s}function di(){const s=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return s!=="area"&&s!=="stackedArea"?null:e.jsxs(a.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(ui,{})})]})}function ui(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(mi,{metricKey:n,idx:r},n))})}function mi({metricKey:s,idx:n}){var N;const[r,o]=v.useState(!1),i=t.useEditorStore(f=>{var g;return(g=f.card)==null?void 0:g.preferences}),d=t.useEditorStore(f=>{var g,D;return(D=(g=f.card)==null?void 0:g.preferences)==null?void 0:D.datasetOptions}),c=d==null?void 0:d.find(f=>f.idx===n),{setCardPreferences:l}=t.useEditorStore(f=>f.actions),u=ci(c==null?void 0:c.fill),x=((N=c==null?void 0:c.dataLabels)==null?void 0:N.enabled)??!1,m=Cs.find(f=>f.value===u)||Cs[0];function b(f){const g={idx:n,fill:u,dataLabels:c==null?void 0:c.dataLabels,...f};if(!c)l({...i||{},datasetOptions:[...d||[],g]});else{const D=d==null?void 0:d.map(I=>I.idx===n?{...I,...g}:I);l({...i||{},datasetOptions:D})}}function h(f){b({fill:f==="false"?!1:f})}function p(f){b({dataLabels:{...c==null?void 0:c.dataLabels,enabled:f}})}function j(f){b({dataLabels:f})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(a.ChartArea,{className:"h-3 w-3"}),m.label.split(" ")[0]]})})]})}),e.jsx(a.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:f=>h(f),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Cs.map(f=>e.jsx(t.SelectItem,{value:f.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:f.label})})},f.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:(c==null?void 0:c.lineStyle)||"solid",onValueChange:f=>b({lineStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:ii.map(({value:f,label:g})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:g},f))})]})]}),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((c==null?void 0:c.pointRadius)??3),onValueChange:f=>b({pointRadius:Number(f)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:oi.map(f=>e.jsx(t.SelectItem,{value:String(f),className:"text-xs",children:f===0?"None":f},f))})]})]}),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:(c==null?void 0:c.pointStyle)||"circle",onValueChange:f=>b({pointStyle:f}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:li.map(({value:f,label:g})=>e.jsx(t.SelectItem,{value:f,className:"text-xs",children:g},f))})]})]})]})]}),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(ls,{config:c==null?void 0:c.dataLabels,onChange:j,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const xi=[0,1,2,3,4,5,6,8,10],hi=[{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 │"}],Ns=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function pi(){return t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type})!=="line"?null:e.jsxs(a.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(fi,{})})]})}function fi(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(gi,{metricKey:n,idx:r},n))})}function gi({metricKey:s,idx:n}){var f;const[r,o]=v.useState(!1),i=t.useEditorStore(g=>{var D;return(D=g.card)==null?void 0:D.preferences}),d=t.useEditorStore(g=>{var D,I;return(I=(D=g.card)==null?void 0:D.preferences)==null?void 0:I.datasetOptions}),c=d==null?void 0:d.find(g=>g.idx===n),{setCardPreferences:l}=t.useEditorStore(g=>g.actions),u=(c==null?void 0:c.lineStyle)||"solid",x=(c==null?void 0:c.pointRadius)??3,m=(c==null?void 0:c.pointStyle)||"circle",b=((f=c==null?void 0:c.dataLabels)==null?void 0:f.enabled)??!1,h=Ns.find(g=>g.value===u)||Ns[0];function p(g){const D={idx:n,lineStyle:u,pointRadius:x,pointStyle:m,dataLabels:c==null?void 0:c.dataLabels,...g};if(!c)l({...i||{},datasetOptions:[...d||[],D]});else{const I=d==null?void 0:d.map(w=>w.idx===n?{...w,...D}:w);l({...i||{},datasetOptions:I})}}function j(g){p({dataLabels:{...c==null?void 0:c.dataLabels,enabled:g}})}function N(g){p({dataLabels:g})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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(Pr,{className:"h-3 w-3"}),h.label.split(" ")[0]]})})]})}),e.jsx(a.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:g=>p({lineStyle:g}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ns.map(({value:g,label:D})=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:D},g))})]})]}),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(x),onValueChange:g=>p({pointRadius:Number(g)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:xi.map(g=>e.jsx(t.SelectItem,{value:String(g),className:"text-xs",children:g===0?"None":g},g))})]})]}),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:m,onValueChange:g=>p({pointStyle:g}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:hi.map(({value:g,label:D})=>e.jsx(t.SelectItem,{value:g,className:"text-xs",children:D},g))})]})]})]})]}),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:b,onCheckedChange:j})]}),b&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(ls,{config:c==null?void 0:c.dataLabels,onChange:N,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const bi=[0,2,4,6,8,10,12,16,20];function ji(){const s=t.useEditorStore(n=>{var r;return(r=n.card)==null?void 0:r.type});return!s||!["bar","horizontalBar","stackedBar"].includes(s)?null:e.jsxs(a.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(a.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(a.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(a.AccordionContent,{className:"pt-2",children:e.jsx(vi,{})})]})}function vi(){const{transformedMetricKeys:s}=os();return s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground",children:"Add metrics to configure series"}):e.jsx("div",{className:"space-y-3",children:s.map((n,r)=>e.jsx(yi,{metricKey:n,idx:r},n))})}function yi({metricKey:s,idx:n}){var j;const[r,o]=v.useState(!1),i=t.useEditorStore(N=>{var f;return(f=N.card)==null?void 0:f.type}),d=t.useEditorStore(N=>{var f;return(f=N.card)==null?void 0:f.preferences}),c=t.useEditorStore(N=>{var f,g;return(g=(f=N.card)==null?void 0:f.preferences)==null?void 0:g.datasetOptions}),l=c==null?void 0:c.find(N=>N.idx===n),{setCardPreferences:u}=t.useEditorStore(N=>N.actions),x=(l==null?void 0:l.borderRadius)??0,m=((j=l==null?void 0:l.dataLabels)==null?void 0:j.enabled)??!1;function b(N){const f={idx:n,borderRadius:x,dataLabels:l==null?void 0:l.dataLabels,...N};if(!l)u({...d||{},datasetOptions:[...c||[],f]});else{const g=c==null?void 0:c.map(D=>D.idx===n?{...D,...f}:D);u({...d||{},datasetOptions:g})}}function h(N){b({dataLabels:{...l==null?void 0:l.dataLabels,enabled:N}})}function p(N){b({dataLabels:N})}return e.jsx(a.Collapsible,{open:r,onOpenChange:o,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(a.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($e.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:x>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:",x]})})]})}),e.jsx(a.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(x),onValueChange:N=>b({borderRadius:Number(N)}),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:bi.map(N=>e.jsx(t.SelectItem,{value:String(N),className:"text-xs",children:N===0?"None":`${N}px`},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(ls,{config:l==null?void 0:l.dataLabels,onChange:p,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Ci=[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 │"}],Si=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function wi(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=a.useEffectiveEditorCardType(),o=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!["line","area","stackedArea"].includes(r))return null;const c=(l,u)=>{const x={...n||{},lineStyleConfig:{...o,[l]:u}};i(x),d({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(a.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(Ar,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(a.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:l=>c("lineStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Si.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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:l=>c("pointRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ci.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":l},l))})]})]}),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:l=>c("pointStyle",l),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ni.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}const Ti=[0,2,4,6,8,10,12,16,20],Ei=[{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%"}],Ii=[{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 Di(){const s=t.useEditorStore(l=>l.card),n=t.useEditorStore(l=>{var u;return(u=l.card)==null?void 0:u.preferences}),r=a.useEffectiveEditorCardType(),o=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:d}=t.useEditorActions();if(!s||!["bar","horizontalBar","stackedBar"].includes(r))return null;const c=(l,u)=>{const x={...n||{},barStyleConfig:{...o,[l]:u}};i(x),d({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(a.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(a.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:l=>c("borderRadius",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ti.map(l=>e.jsx(t.SelectItem,{value:String(l),className:"text-xs",children:l===0?"None":`${l}px`},l))})]})]}),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:l=>c("barPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ei.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]}),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:l=>c("categoryPercentage",Number(l)),children:[e.jsx(t.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:Ii.map(({value:l,label:u})=>e.jsx(t.SelectItem,{value:l,className:"text-xs",children:u},l))})]})]})]})})]})}function ki(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=t.useEditorActions();return e.jsxs(a.AccordionItem,{value:"stacked-sort",children:[e.jsx(a.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-3.5 w-3.5 text-foreground/60"}),"Sort"]})}),e.jsx(a.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(gt,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:s||"none",onValueChange:r=>{n(r)}})]})})]})}const Mi=["kpi"],Ss=2;function Tt(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 Ai(s){if(!(s!=null&&s.name)||!(s!=null&&s.dataType)||s.role==="metric")return!1;const n=t.getDataType(s.dataType);return["date","string","boolean"].includes(n)}function Li(s){return{...s,role:"groupby"}}function Fi(){var D,I;const s=t.useEditorStore(w=>w.card),n=t.useEditorStore(w=>w.actions.updateCardConfig),r=a.useEffectiveEditorCardType(),{scopedFields:o}=a.useScopedFields(),i=((D=s.config)==null?void 0:D.metricColumns)||[],d=((I=s.config)==null?void 0:I.summary)||{},c=d.breakdownDimensions||[],l=c.length>0,u=Mi.includes(r),x=i.length>0,m=d.enabled===!0,b=u&&x,h=Array.from(new Map(o.filter(Ai).map(w=>[Tt(w),Li(w)])).values()),p=new Set(h.map(w=>Tt(w))),j=new Set(c.map(w=>Tt(w)).filter(w=>w&&p.has(w)));if(!u)return null;const N=w=>{n(s.id,{summary:{...d,...w}})},f=(w,S)=>{const M=Tt(w),A=h.filter(E=>j.has(Tt(E))),F=S?j.has(M)?A:[...A,w].slice(0,Ss):A.filter(E=>Tt(E)!==M);N({breakdownDimensions:F,...F.length>0?{showOnCard:!0}:{}})},g=w=>{if(!w){N({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}N({enabled:!0,showOnCard:d.showOnCard??!0,includeInDashboardSummary:d.includeInDashboardSummary??!0})};return e.jsxs(a.AccordionItem,{value:"summary",className:"border-none",children:[e.jsxs(a.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(a.FileText,{className:"h-3.5 w-3.5 text-foreground/60"}),e.jsx("span",{children:"Summary"})]}),e.jsx(t.Switch,{size:"xs",checked:m,disabled:!b,onClick:w=>w.stopPropagation(),onPointerDown:w=>w.stopPropagation(),onCheckedChange:g,"aria-label":"Enable summary"})]}),e.jsx(a.AccordionContent,{className:"pb-4 pt-2",children:e.jsxs("div",{className:t.cn("space-y-3 transition-opacity",!m&&"opacity-60"),children:[!b&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:x?"Summary is not supported for this card type.":"Add at least one metric to enable summary."}),!l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Checkbox,{id:"summary-show-on-card",checked:d.showOnCard===!0,disabled:!m,onCheckedChange:w=>N({showOnCard:w===!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(a.Checkbox,{id:"summary-include-rollup",checked:d.includeInDashboardSummary===!0,disabled:!m,onCheckedChange:w=>N({includeInDashboardSummary:w===!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:[c.length,"/",Ss]})]}),h.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:h.map(w=>{const S=Tt(w),M=j.has(S),A=j.size>=Ss,F=!m||!M&&A;return e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(a.Checkbox,{id:`summary-breakdown-${S}`,checked:M,disabled:F,onCheckedChange:E=>f(w,E===!0)}),e.jsx(t.Label,{htmlFor:`summary-breakdown-${S}`,className:"cursor-pointer text-xs",children:w.label||w.name})]},S)})})]})]})})]})}const Ri=new Set(["area","bar","bubble","bullet","combo","doughnut","funnel","horizontalBar","line","pie","polarArea","radar","scatter","stackedArea","stackedBar","stackedLine","tornado"]);function Pi(){const s=t.useEditorStore(u=>u.card),n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=a.useEffectiveEditorCardType(),{setCardPreferences:o,updateCardInFrame:i}=t.useEditorActions();if(!s||!Ri.has(r||""))return null;const d=n==null?void 0:n.tooltipConfig,c=(d==null?void 0:d.formatMode)||(d==null?void 0:d.mode)||"inherit",l=u=>{const x={...n||{},tooltipConfig:{...d||{},...u}};o(x),i({...s,preferences:x})};return e.jsxs(a.AccordionItem,{value:"tooltip-format",className:"border-b-0",children:[e.jsx(a.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(a.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:c==="override",onCheckedChange:u=>l({formatMode:u?"override":"inherit",mode:u?"override":"inherit"})})]}),c==="override"&&e.jsx(Ut,{formatOptions:(d==null?void 0:d.formatOptions)||{},onFormatOptionsChange:u=>l({formatMode:"override",mode:"override",formatOptions:u}),showTitle:!1})]})]})}function La({mode:s}){const n=t.useEditorStore(r=>{var o;return(o=r.card)==null?void 0:o.type});return a.isTableChartType(n)?null:e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(ni,{}),(n==="area"||n==="stackedArea")&&e.jsx(di,{}),n==="line"&&e.jsx(pi,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(ji,{}),e.jsx(wi,{}),e.jsx(Di,{}),e.jsx(zl,{}),s==="config"&&e.jsx(Ml,{}),s==="config"&&e.jsx(Fi,{}),e.jsx($l,{}),n==="bullet"&&e.jsx(Kl,{}),n==="funnel"&&e.jsx(Hl,{}),(n==="bubble"||n==="scatter")&&e.jsx(Ul,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(ki,{}),e.jsx(Bl,{}),e.jsx(Vl,{}),e.jsx(_l,{}),e.jsx(Yl,{}),e.jsx(Pi,{})]})}function Oi(){const s=t.useEditorStore(r=>r.card),n=s==null?void 0:s.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx(Os,{chartType:n}),e.jsx(a.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(La,{mode:"dev"})})]}):null}function Bi({focusSection:s,focusRequestId:n}){const r=t.useEditorStore(c=>c.card),o=r.type;if(t.getVisualizationMode(r)==="dynamic")return e.jsx("div",{className:"p-6",children:e.jsxs(a.Alert,{children:[e.jsx(t.Info,{className:"h-4 w-4"}),e.jsx(a.AlertTitle,{children:"Dynamic mode manages presentation"}),e.jsx(a.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 d(){if(a.supportsRegularTableSettings(o))return e.jsx(Aa,{cardType:o,focusSection:s,focusRequestId:n});switch(o){case"kpi":return e.jsx(bl,{});case"map":return e.jsx(Nl,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(Ta,{})});case"text":return e.jsx(Ll,{});default:return e.jsx(Oi,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[d(),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}const Wn=32;function Vi(){const s=v.useRef(null),n=v.useRef(null),r=t.useEditorStore(g=>g.isShowingVisual),o=t.useEditorStore(g=>g.isDevMode),i=t.useEditorStore(g=>g.showAIDialog),[d,c]=v.useState(!1),[l,u]=v.useState({section:null,id:0}),x=r&&!i,m=x&&(!o||d),b=o&&x,h=()=>c(g=>!g),p=g=>{g&&u(D=>({section:g,id:D.id+1})),o&&c(!0)};v.useEffect(()=>{var g,D,I,w;i?((g=s.current)==null||g.resize(0),(D=n.current)==null||D.resize(0)):((I=s.current)==null||I.resize(Wn),(w=n.current)==null||w.resize(25))},[i]);const[j,N]=v.useState(!1),f=x?{show:b,isOpen:m,onToggle:h,onOpen:p}:void 0;return e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(a.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:g=>e.jsx(gs,{mode:"toolbar",inlineToolbar:!0,overflowActions:g,visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})})})})}),e.jsx(a.ResizableHandle,{}),e.jsx(a.ResizablePanel,{role:"visual-section",minSize:0,defaultSize:50,children:m?e.jsxs(a.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(a.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(gs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})}),!i&&e.jsx(a.ResizableHandle,{}),e.jsx(a.ResizablePanel,{ref:s,className:"flex",defaultSize:Wn,maxSize:45,children:e.jsx(Bi,{focusSection:l.section,focusRequestId:l.id})})]}):e.jsx(gs,{mode:"canvas",visualAsideControl:f,isDynamicInspectorOpen:j,onDynamicInspectorOpenChange:N})})]})}function _i(s){var ae;t.useAIInteractionStore(K=>K.currentAIContext);const[n,r]=v.useState(""),[o,i]=v.useState(null),{authToken:d,tokenProps:c}=a.useSemaphorContext(),l=t.useEditorStore(K=>K.card.id),u=t.useEditorStore(K=>{var ie;return(ie=K==null?void 0:K.card)==null?void 0:ie.sql}),x=t.useEditorStore(K=>K.isDevMode),m=t.useEditorStore(K=>{var ie;return(ie=K==null?void 0:K.card)==null?void 0:ie.python}),{setCardPython:b,setCardSql:h,setRunSql:p,switchCardType:j,setQueryConfig:N}=t.useEditorActions(),f=t.useEditorStore(K=>K.currentAssitantScope)||[],g=t.useEditorStore(K=>K.userInputForAI),D=t.useEditorStore(K=>K.triggerAIRun),I=t.useEditorStore(K=>K.card),w=t.useEditorStore(K=>K.selectedDatabaseName),S=t.useEditorStore(K=>K.selectedTableName),M=t.useEditorStore(K=>K.selectedConnectionId),A=t.useEditorStore(K=>K.selectedSchemaName),F=t.useDashboardStore(K=>K.dashboard.aiScopeTables),{errorMessage:E,refetch:C,data:T}=a.useEditorCardQuery(I),{setTriggerAIRun:L,setCurrentAssitantScope:k,setCardConfig:R}=t.useEditorActions(),{selectedDatamodelName:y,connectionType:_,selectedDatamodelId:O}=a.useEditorAside(),P=(ae=a.useDashboardQuery().data)==null?void 0:ae.assistantProfileId,B=v.useRef(a.createAssistantConversationId()),Y=v.useRef(null),q=v.useRef(l),z=v.useRef(!1),V=()=>{const K=Y.current;K&&(Y.current=null,B.current=a.createAssistantConversationId(),K==="clear"&&Q([]))},{messages:$,setMessages:Q,regenerate:U,error:J,sendMessage:W,status:ee,addToolResult:ue,stop:fe,clearError:be}=a.useChat({transport:new a.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${d==null?void 0:d.accessToken}`}),body:()=>{const K=t.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:P,conversationId:B.current,assistantRequestId:a.createAssistantRequestId(),isDevMode:x,aiContext:K.currentAIContext,reasoningEffort:K.reasoningEffort,showReasoning:K.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:K,body:ie})=>({body:{...ie,messages:t.cleanupIncompleteMessages(K)}})}),onError:K=>{var ie;if(z.current=!1,K.name==="AbortError"||(ie=K.message)!=null&&ie.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)"),V();return}console.error("[Editor Assistant] Stream error:",K),V()},onToolCall:ke,onFinish({isAbort:K,isDisconnect:ie,isError:Ce}){z.current=!1,r(""),console.log(K?"[Editor Assistant] Stream aborted by user":ie?"[Editor Assistant] Stream disconnected (network error)":Ce?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully"),V()}}),ge=v.useCallback(K=>{z.current=!0;try{const ie=W(K);return a.isPromiseLike(ie)?ie.catch(Ce=>{throw z.current=!1,Ce}):ie}catch(ie){throw z.current=!1,ie}},[W]),Pe=v.useCallback(()=>{z.current=!0;try{const K=U();return a.isPromiseLike(K)?K.catch(ie=>{throw z.current=!1,ie}):K}catch(K){throw z.current=!1,K}},[U]),Oe=K=>{let ie=!1;Q(Ce=>{const re=typeof K=="function"?K(Ce):K;if(re.length===0){if(z.current)return Y.current="clear",ie=!0,Ce;Y.current=null,B.current=a.createAssistantConversationId()}return re}),ie&&fe()};v.useEffect(()=>{if(q.current!==l){if(q.current=l,z.current){Y.current!=="clear"&&(Y.current="rotate"),fe();return}Y.current=null,B.current=a.createAssistantConversationId()}},[l,fe]),v.useEffect(()=>{D&&g&&(ge({role:"user",parts:[{type:"text",text:g}]}),L(!1))},[D,g,ge,L]);async function ke({toolCall:K}){var ie,Ce,re,he,Ye,Z,Fe,me,qe,Le,Ke,Se,oe,Ie,Re,De;if(["createChartFromSql","createForecast"].includes(K.toolName)){const te=((ie=K.input)==null?void 0:ie.sql)??((Ce=K.args)==null?void 0:Ce.sql),ve=((re=K.input)==null?void 0:re.python)??((he=K.args)==null?void 0:he.python),ye=((Ye=K.input)==null?void 0:Ye.chartType)??((Z=K.args)==null?void 0:Z.chartType);j(ye),h(te),b(ve),p(!0),ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(K.toolName==="getUserSql"){if(!u){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",message:"No SQL found"}});return}ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",sql:u,python:m||""}})}else if(K.toolName==="generateQueryConfig"){r("Generating query config...");const te=((Fe=K.input)==null?void 0:Fe.chartType)??((me=K.args)==null?void 0:me.chartType),ve=((qe=K.input)==null?void 0:qe.queryConfig)??((Le=K.args)==null?void 0:Le.queryConfig);((Ke=K.input)==null?void 0:Ke.cardConfig)??((Se=K.args)==null||Se.cardConfig),j(te),R(ve),h(void 0),b(void 0);const ye=await C();if((oe=ye==null?void 0:ye.data)!=null&&oe.error){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"error",queryConfig:ve,message:(Ie=ye==null?void 0:ye.data)==null?void 0:Ie.error.message}});return}if((Re=ye==null?void 0:ye.data)!=null&&Re.records){ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized"}});return}ue({tool:K.toolName,toolCallId:K.toolCallId,output:{status:"success",queryConfig:ve,message:"The data has been visualized",records:(De=ye==null?void 0:ye.data)==null?void 0:De.records}})}else r("Analyzing...")}function Te(K){const ie=a.removeFromScopeArray(f,K);_e(ie)}function _e(K){const ie=a.sanitizeAIScope(K);k(ie),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(ie)}`}]}])}function ze(){const K={databaseName:w||"",schemaName:A||"",tableName:S||"",datamodelId:O||"",datamodelName:t.resolveDatamodelName(y),connectionId:M||"",connectionType:_||""},ie=a.dedup([...f,K]);_e(ie)}function Be(){const K={databaseName:w||"",schemaName:A||"",tableName:S||"",datamodelName:t.resolveDatamodelName(y),connectionId:M||"",connectionType:_||"",datamodelId:O||""};if(!a.isInAiScopeArray([...F||[],...f],K)||f.length===0){const Ce=a.dedup([...F||[],...f,K]).filter(re=>re.connectionId===K.connectionId);_e(Ce)}}const Ae=!["ready","error"].includes(ee),Me=a.getErrorMessage(J);return{messages:$,setMessages:Oe,sendMessage:ge,regenerate:Pe,isLoading:Ae,handleSetAIScope:Be,handleAddCurrentTableToScope:ze,removeFromCurrentSelections:Te,currentAssitantScope:f,setCurrentAssitantScope:k,stop:fe,status:ee,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:Me,clearError:be}}const Yi=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Xn({isFullscreen:s,onFullscreenChange:n,fullscreenContainer:r}){const o=v.useRef(null),i=v.useRef(!1),[d,c]=v.useState(!1),[l,u]=v.useState(je.isDevEnv),[x,m]=v.useState(!1),[b,h]=v.useState(!1),[p,j]=v.useState(!1),[N,f]=v.useState(0),g=s??p,D=t.useCurrentAIContext(),{setCurrentAIContext:I,setHasEditorEntitySelectionOverride:w}=t.useAIActions(),{clearQueue:S}=t.useQueueActions(),{clearFileAttachments:M}=t.useFileActions(),A=t.useFileAttachments("editor"),{selectedEntities:F}=a.useAssistantContextEntities("editor"),E=t.useEditorStore(re=>re.card.id),C=t.useEditorStore(re=>re.card.dataSource),T=t.useEditorStore(re=>{var he;return(he=re.card.dataSource)==null?void 0:he.selectedEntities}),L=t.useEditorStore(re=>re.actions.setCardSql),k=t.useEditorStore(re=>re.actions.setRunSql),R=t.useEditorStore(re=>re.showAIDialog),y=t.useDashboardStore(re=>re.handleOpenAssistantProfile),{setShowAIDialog:_,setCardPython:O}=t.useEditorActions(),{assistantProfile:P}=a.useAssistantProfile(),{messages:B,setMessages:Y,sendMessage:q,isLoading:z,stop:V,status:$,llmUsage:Q,errorMessage:U,clearError:J}=_i(),[W,ee]=v.useState(""),ue=re=>{ee(re.target.value)},fe=re=>{re.preventDefault();const he=W.trim();if(!he&&A.length===0)return;const Ye=[];he&&Ye.push({type:"text",text:he}),A.forEach(Z=>{Z.data&&Ye.push({type:"file",mediaType:Z.type,filename:Z.name,url:`data:${Z.type};base64,${Z.data}`})}),q({role:"user",parts:Ye}),ee(""),M("editor"),be()},be=v.useCallback(()=>{f(re=>re+1)},[]);v.useEffect(()=>{var re;R&&!i.current&&((re=o.current)==null||re.focus()),i.current=R},[R]),v.useEffect(()=>{R&&(w(!1),I({selectedEntities:T||[]}))},[E,T,I,w,R]),a.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:z,sendMessage:q});const{hasActiveTools:ge,activeToolText:Pe}=a.useActiveToolStatus(B),Oe=v.useCallback(re=>{n==null||n(re),s===void 0&&j(re)},[s,n]);v.useEffect(()=>{if(!g)return;function re(he){he.key==="Escape"&&Oe(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[g,Oe]);const ke=v.useCallback(re=>{q({role:"user",parts:[{type:"text",text:re}]}),be()},[be,q]),Te=v.useCallback(async()=>{const re=JSON.stringify(B??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),t.ue.success("Conversation copied")}catch(he){console.error("Failed to copy conversation",he),t.ue.error("Unable to copy conversation")}},[B]),_e=v.useCallback(()=>{Oe(!g)},[g,Oe]);function ze(re,he){he==="sql"?(L(re),k(!0)):he==="python"&&(O(re),k(!0))}function Be(){D.selectedEntities.length===0&&I({selectedEntities:F})}function Ae(re){Be();const he={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};q(he),be()}function Me(re){Be(),q({role:"user",parts:[{type:"text",text:re}]}),be()}function ae(){return e.jsxs(a.DropdownMenu,{children:[e.jsx(a.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(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",children:[e.jsx(a.DropdownMenuLabel,{children:"Options"}),e.jsx(a.DropdownMenuSeparator,{}),e.jsx(a.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:c,children:"Token usage"}),e.jsx(a.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:u,children:"Tool invocations"}),e.jsx(a.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:m,children:"System message"})]})]})}function K(){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 ie=(W==null?void 0:W.length)===0&&(B==null?void 0:B.filter(re=>re.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",g&&"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:[K(),y&&e.jsx(t.Button,{variant:"outline",size:"xs",className:"min-w-0 shrink",onClick:y,children:e.jsx("span",{className:"truncate",children:(P==null?void 0:P.name)||"Default profile"})}),e.jsxs("div",{"data-role":"header-actions",className:"flex shrink-0 items-center gap-1.5",children:[ae(),l&&e.jsx(t.Button,{variant:"ghost",size:"xs",className:"text-muted-foreground hover:text-foreground",onClick:Te,children:"Copy conversation"}),e.jsx(a.IconButton,{tooltip:g?"Exit fullscreen":"Expand",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:_e,children:g?e.jsx($e.Minimize2,{className:"h-3.5 w-3.5"}):e.jsx($e.Maximize2,{className:"h-3.5 w-3.5"})}),e.jsx(a.IconButton,{className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",tooltip:"New chat",onClick:()=>{Y([]),S("editor"),J()},children:e.jsx(a.SquarePen,{className:"h-3.5 w-3.5"})}),e.jsx(a.IconButton,{tooltip:"Close",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>{_(!1)},children:e.jsx(le.X,{className:"h-3.5 w-3.5"})})]})]}),e.jsx(a.AssistantVirtualizedMessages,{messages:B,showTools:l,handleRun:ze,showSystemMessage:x,onQuickReply:ke,disableQuickReplies:z,status:$,errorMessage:U,activeToolText:z&&ge?Pe:void 0,className:"mt-2 w-full grow px-0 py-2 pr-3",latestButtonClassName:R?"bottom-24 right-8":"hidden",scrollToEndSignal:N}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ie&&!P&&e.jsx(a.Placeholders,{onClick:Ae,placeholders:Yi}),e.jsx("div",{children:ie&&P&&e.jsx(a.SeedQuestions,{seedQuestions:P.seedQuestions||[],handleSeedQuestionClick:Me})})]}),e.jsx(a.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(a.ChatInputWithContext,{ref:o,setInput:ee,stop:V,input:W,handleInputChange:ue,handleSubmit:re=>{Be(),fe(re)},isLoading:z,status:$,assistantType:"editor",onFocus:()=>{}})]}),Q&&d&&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(a.AddDataPicker,{incomingSelectedEntities:F,open:b,onOpenChange:h,dataSource:C||a.EMPTY_DATA_SOURCE,dialogMode:"aiContext",onSaveSelectedEntities:re=>{w(!0),I({...D,selectedEntities:re})}})]});return g&&r?dr.createPortal(e.jsx(a.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 Vs({children:s,className:n,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",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function Fa({id:s,label:n,dataType:r,calculated:o,open:i,onOpenChange:d,onRemove:c,sortDirection:l,onSortDirectionChange:u,badge:x,children:m}){const{attributes:b,listeners:h,setNodeRef:p,transform:j,transition:N,isDragging:f}=a.useSortable({id:s});return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:d,children:[e.jsxs("div",{ref:p,style:{transform:a.CSS.Transform.toString(j),transition:N},className:t.cn("group flex h-7 w-full items-center gap-1.5 rounded-control border bg-background px-1.5 transition-colors",i?"border-foreground/30 bg-muted/40":"border-border hover:bg-muted/40",f&&"z-50 scale-95 opacity-50"),children:[e.jsx("button",{type:"button",...b,...h,"aria-label":`Drag ${n}`,className:t.cn(a.GRIP_REVEAL_CLASS,"text-muted-foreground hover:text-foreground"),onClick:g=>g.stopPropagation(),children:e.jsx(a.GripVertical,{className:"h-3 w-3"})}),e.jsx(a.TypeGlyph,{dataType:r,calculated:o}),e.jsx(Vs,{className:"block w-0 min-w-0 flex-1 text-[12px] text-foreground",children:n}),x,u&&e.jsx("button",{type:"button","aria-label":l==="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 hover:bg-muted hover:text-foreground",onClick:g=>{g.stopPropagation(),u(l==="asc"?"desc":"asc")},children:l==="asc"?e.jsx(a.ArrowUp,{className:"h-3 w-3"}):e.jsx(a.ArrowDown,{className:"h-3 w-3"})}),m&&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 hover:bg-muted hover:text-foreground data-[state=open]:bg-muted",onClick:g=>g.stopPropagation(),children:e.jsx(a.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 hover:bg-muted hover:text-foreground group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:g=>{g.stopPropagation(),c()},children:e.jsx(le.X,{className:"h-3 w-3"})})]}),m&&e.jsx(t.PopoverContent,{align:"start",sideOffset:6,className:"w-[320px] p-0",children:e.jsx("div",{className:"max-h-[480px] space-y-3 overflow-y-auto p-3",children:m})})]})}function zi(s,n){var o;if(n.status==="blocked"||(o=s.sql)!=null&&o.trim())return!1;const r=new Set(n.mappingDispositions.flatMap(i=>i.status==="apply"?[i.filterValue.filterId]:[]));return n.cardFilterValues.some(i=>{const d=n.queryFilterDefinitions.find(u=>u.id===i.filterId);if(!t.hasFiniteDateComparisonRange(i))return!1;if(!(r.has(i.filterId)||(d==null?void 0:d.kind)==="global-date"))return!!(d&&qi([d],n.resolvedPrimaryDateField,[i]));const l=t.buildExecutedDateFilterDefinition(i);return!!(l&&t.resolveFieldDateComparisonCandidate({card:s,filter:l,filterValue:i,effectiveFilterValue:i,temporalBinding:n.resolvedPrimaryDateField}).status==="eligible")})}function qi(s,n,r){if(!n)return!1;const o=n.qualifiedFieldName,i=n.qualifiedEntityName,d=i&&n.name?`${i}.${n.name}`:o;return s.some(c=>{if(!(t.getDataType(c.dataType||"")==="date"))return!1;const u=a.getSelectedDateFilterColumn(c,r),x=u.split("."),m=x[x.length-1]||u,b=x.length>1?x.slice(0,-1).join("."):void 0,h=c.qualifiedTableName||b,p=h?`${h}.${m}`:void 0;return o?p?p===d||p.endsWith(`.${o}`):m===n.name:p?p===d:m===n.name})}function $i(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 Ki({aliasTemplate:s,onAliasTemplateChange:n}){var u;const[r,o]=v.useState(s),[i,d]=v.useState(!1),c=(u=t.useEditorStore(x=>{var m;return(m=x.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:u[0],l=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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:l,value:i?r:s,onChange:x=>{o(x.target.value),d(!0)},onFocus:()=>d(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&r!==s?(n(r),d(!1)):x.key==="Escape"&&(o(s),d(!1))},"aria-label":"Edit alias template"}),i&&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:()=>{n(r),d(!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),d(!1)},children:e.jsx(le.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function Ui({valueAliases:s,onValueAliasesChange:n}){const[r,o]=v.useState(null),[i,d]=v.useState(""),[c,l]=v.useState(""),u=()=>{n({...s,"":""})},x=b=>{const h={...s};delete h[b],n(h)},m=b=>{const h={...s};delete h[b],h[i]=c,n(h),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(([b,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:r===b?e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:i,onChange:j=>d(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(b):j.key==="Escape"&&o(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:c,onChange:j=>l(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(b):j.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:()=>m(b),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(le.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input,{placeholder:"Value key",value:b,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(b),d(b),l(h)},"aria-label":"Edit value alias key"}),e.jsx(t.Input,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{o(b),d(b),l(h)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(b),"aria-label":"Remove value alias",children:e.jsx(le.X,{className:"h-3 w-3"})})]})},b+p)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(a.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function Gi({idx:s}){var l;const n=t.useEditorStore(u=>{var x;return(x=u.card)==null?void 0:x.preferences}),r=t.useEditorStore(u=>{var x;return(x=u.card.preferences)==null?void 0:x.datasetOptions}),o=t.useEditorStore(u=>u.actions.setCardPreferences),i=(l=n==null?void 0:n.chartOptions)==null?void 0:l.indexAxis,d=r==null?void 0:r.find(u=>u.idx===s);function c(u,x){(u==="end"||u==="start")&&je.getContrastColor(je.getCanvasBackgroundColor());const m={display:u!=="none",align:u,anchor:u,clamp:!0};if(!d)o({...n,datasetOptions:[...r||[],{idx:x,datalabels:m}]});else{const b={...d};b.datalabels=m;const h=r==null?void 0:r.map(p=>p.idx===x?b:p);o({...n,datasetOptions:h})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(a.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:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(le.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Sr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Tr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(wr,{className:t.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function Hi(s,n=30){return s.length>n?s.slice(0,n)+"...":s}function Qi({col:s,idx:n,className:r,iconClassName:o,children:i}){const d=t.useEditorStore(m=>{var b;return(b=m.card)==null?void 0:b.preferences}),c=t.useEditorStore(m=>{var b,h;return(h=(b=m.card)==null?void 0:b.preferences)==null?void 0:h.datasetOptions}),l=c==null?void 0:c.find(m=>m.idx===n),{setCardPreferences:u}=t.useEditorStore(m=>m.actions);function x(m){if(!l)u({...d,datasetOptions:[...c||[],{idx:n,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const b={...l};b.type=m==="area"?"line":m,b.fill=m==="area"?"origin":"";const h=c==null?void 0:c.map(p=>p.idx===n?b:p);u({...d,datasetOptions:h})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",r),children:[i||e.jsx(Vs,{className:"max-w-[100px]",title:s,children:Hi(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(a.ChartColumnIncreasing,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(a.ChartLine,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(a.ChartArea,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",o)}),e.jsx(Gi,{idx:n})]})]})}function Ji(){const s=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>l.isDevMode),r=t.useEditorStore(l=>l.card.preferences),{setCardPreferences:o}=t.useEditorStore(l=>l.actions);function i(l){var m;const u={datalabels:{display:l!=="none",align:l,anchor:l,clamp:!0}},x={...r,chartOptions:{...r==null?void 0:r.chartOptions,plugins:{...(m=r==null?void 0:r.chartOptions)==null?void 0:m.plugins,...u}}};o(x)}function d(){var l,u,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,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 c(){var l,u,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(u=(l=r==null?void 0:r.chartOptions)==null?void 0:l.plugins)==null?void 0:u.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?d():c()})}function Wi({column:s}){const n=t.useEditorStore(u=>u.card.type),r=t.useEditorStore(u=>{var x,m;return(m=(x=u.card)==null?void 0:x.config)==null?void 0:m.metricColumns}),o=(r==null?void 0:r.map(u=>u.label))||[],i=o==null?void 0:o.find(u=>u===s.label||u===s.name),d=i?o.indexOf(i):-1;function c(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(Qi,{idx:d,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function l(){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(Ji,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&c(),["pie","doughnut"].includes(n)&&l()]})}function Xi({field:s,searchQuery:n="",limit:r=500}){const{authToken:o,tokenProps:i}=a.useSemaphorContext(),d=t.useDashboardStore(m=>{var b;return((b=m.reportContext)==null?void 0:b.calendar)??null}),c=t.useEditorStore(m=>m.card),l=c==null?void 0:c.dataSource,u=["attribute-values",s.entityName,s.name,n,r,d],x=a.useQuery({queryKey:u,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const m={groupByColumns:[{...s,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:s,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:r},b={connection_id:l.connectionId,cardConfig:m,cardDataSource:l,cache_config:t.getCacheConfig({card:c}),calendarContext:d};console.log("requestBody",b);const h=await t.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(o==null?void 0:o.accessToken)||"",b);if(h!=null&&h.error)return console.error("Error fetching attribute values:",h.error),[];const p=s.name;return((h==null?void 0:h.records)||[]).map(N=>{const f=N[p]||N[s.alias||p]||N[s.label];return{id:f||"",value:f||"",label:String(f||"(empty)")}})}catch(m){return console.error("Error fetching attribute values:",m),[]}},enabled:!!s&&!!(l!=null&&l.connectionId)&&!!d,staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:x.data||[],isLoading:x.isLoading,isFetching:x.isFetching,isError:x.isError,error:x.error,refetch:x.refetch}}const Zi=new Set;function Ra({open:s,onOpenChange:n,availableFields:r,existingFilters:o,editingCondition:i,onSave:d}){const c=!!i,[l,u]=v.useState(c?"values":"fields"),[x,m]=v.useState(""),[b,h]=v.useState({id:(i==null?void 0:i.id)||je.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),p=r.filter(I=>{var S;return c?!1:!((S=o==null?void 0:o.conditions)==null?void 0:S.some(M=>M.field.id===I.id))}),j=I=>{h({...b,field:I}),u("values")},N=()=>{if(b.field&&b.selectedValues.length>0){const I={id:b.id,field:b.field,operator:"in",value:b.selectedValues};let w;if(c){const S=((o==null?void 0:o.conditions)||[]).map(M=>M.id===i.id?I:M);w={...o,conditions:S}}else{const S=(o==null?void 0:o.conditions)||[];w={id:(o==null?void 0:o.id)||je.v4(),logicalOperator:"AND",negate:!1,conditions:[...S,I],groups:[]}}d(w),n(!1)}},f=()=>{if(!c||!i)return;const I=((o==null?void 0:o.conditions)||[]).filter(w=>w.id!==i.id);if(I.length>0){const w={...o,conditions:I};d(w)}else d(void 0);n(!1)},g=I=>{h({...b,selectedValues:I})},D=()=>{c&&i?(h({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),u("values")):(h({id:je.v4(),field:null,selectedValues:[]}),u("fields")),m("")};return v.useEffect(()=>{s&&D()},[s,c,i]),e.jsx(a.Dialog,{open:s,onOpenChange:n,children:e.jsxs(a.DialogContent,{className:"max-w-2xl",children:[e.jsx(a.DialogHeader,{children:e.jsx(a.DialogTitle,{children:c?`Edit Filter: ${b.field?a.getFieldDisplayLabel(b.field):""}`:l==="fields"?"Select Field to Filter":`Select Values for ${b.field?a.getFieldDisplayLabel(b.field):""}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(o==null?void 0:o.conditions)&&o.conditions.length>0&&l==="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(I=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[a.getFieldDisplayLabel(I.field),":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(I.value)?`${I.value.length} values`:String(I.value)})]},I.id))})]}),l==="fields"&&!c?e.jsx("div",{className:"flex flex-col",children:e.jsx(a.FieldOptionList,{fields:p,selectedIds:Zi,onSelect:j,query:x,onQueryChange:m,density:"compact",listLabel:"Filterable fields",listClassName:"max-h-[400px]",autoFocusSearch:!0,emptyMessage:x?`No fields found matching "${x}"`:r.length>0?"All available fields are already filtered":void 0})}):e.jsx(ec,{field:b.field,selectedValues:b.selectedValues,onValuesChange:g,onBack:c?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(t.Button,{variant:"destructive",onClick:f,children:"Delete Filter"}):e.jsx(t.Button,{variant:"outline",onClick:D,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(t.Button,{onClick:N,disabled:!b.field||b.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function ec({field:s,selectedValues:n,onValuesChange:r,onBack:o}){const[i,d]=v.useState(""),{values:c,isLoading:l,isFetching:u}=Xi({field:s,searchQuery:i,limit:500}),x=i?c.filter(h=>String(h.value).toLowerCase().includes(i.toLowerCase())):c,m=h=>{const p=n.includes(h);r(p?n.filter(j=>j!==h):[...n,h])},b=()=>{n.length===x.length&&x.length>0?r([]):r(x.map(h=>h.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 ",a.getFieldDisplayLabel(s)]})]}),e.jsxs("div",{className:"relative",children:[e.jsx($e.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:i,onChange:h=>d(h.target.value),className:"pl-10"})]}),l||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(a.Checkbox,{checked:n.length===x.length&&x.length>0,onCheckedChange:b}),e.jsxs(t.Label,{className:"text-sm",children:["Select All (",x.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:x.map(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(a.Checkbox,{checked:n.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(Vs,{className:"text-sm",children:h.label})]},h.id))})]})]})}function tc(s,n){return s==="pivotBy"&&(n==="table"||n==="pivotTable")}const sc=[];function nc({field:s,zone:n,index:r,sortDirection:o,onSortDirectionChange:i,hasPivotColumns:d=!1,cardType:c}){var Us,Gs,Hs,Qs,Js,Ws,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;const l=t.useEditorStore(G=>G.card),u=t.useEditorStore(G=>G.frame),x=t.useDashboardStore(G=>G.isVisualEditing),m=t.useDashboardStore(G=>G.selectedSheetId),b=t.useDashboardStore(G=>G.actions.updateSheetCalculatedFields),h=t.useDashboardStore(G=>G.actions.updateDashboardCalculatedFields),j=t.useDashboardStore(G=>{var Ee;return G.visualEditPendingDashboardCalculatedFields??((Ee=G.dashboard)==null?void 0:Ee.calculatedFields)})??sc,{scopedFields:N,valuePickFilterableFields:f,isLoading:g,hasError:D}=a.useFilterableFields(),{userContext:I}=a.useCurrentUserInfo(),{tokenProps:w}=a.useSemaphorContext(),S=a.canEditLocalCalculatedFields(I),M=a.useTimezone()??void 0,A=a.useResolvedTemporalStylePreferences()??Kt.DEFAULT_RESOLVED_VALUE_FORMAT_PREFERENCES,{updateLabel:F,handleAggregationChange:E,handleDetailDateFormatChange:C,handleDimensionFormatChange:T,handleTemporalBucketFormatChange:L,handleGranularityChange:k,handleAliasTemplateChange:R,handlePivotMemberOrderChange:y,handleValueAliasesChange:_,handleMetricFormatChange:O,removeField:P,handleMetricComparisonChange:B,handleMetricComparisonSpecChange:Y,handleMetricComparisonPolarityChange:q,handleMetricWindowTransformChange:z,handleMetricWindowOrderByChange:V,handleMetricWindowDirectionChange:$,handleMetricWindowPartitionToggle:Q,handleMetricMovingAverageWindowSizeChange:U,handleMetricMovingAverageMinPeriodsChange:J,handleMetricPreviousPeriodDeltaModeChange:W,handleMetricPercentOfTotalScopeChange:ee,handleMetricPercentOfTotalOutputChange:ue,handleMetricTargetValueChange:fe}=a.useFieldManagement(l),[be,ge]=v.useState(!1),[Pe,Oe]=v.useState(()=>{var G;return!!((G=s.parameters)!=null&&G.windowTransform)}),[ke,Te]=v.useState(!1),[_e,ze]=v.useState(!1),[Be,Ae]=v.useState(null),Me=v.useMemo(()=>{const G=de=>de!=null&&de.startsWith("card-source-")?de.replace("card-source-",""):de,Ee=G(s.id),X=N.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 Ne=G(de.id);return!!(Ee&&Ne&&Ee===Ne)});return{dataType:(X==null?void 0:X.dataType)||s.dataType,resolvedFromScopedField:!!X}},[s.dataType,s.id,s.name,s.qualifiedEntityName,s.qualifiedFieldName,N]),ae=a.getGranularityOptionsForFieldType(Me.dataType),K=v.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=n==="groupBy"?K.ok&&ae.includes(K.granularity)?K.granularity:void 0:ae.includes(s.granularity)?s.granularity:"day",Ce=K.ok?K.selection:{value:"auto",customPattern:"",format:et.AUTOMATIC_TEMPORAL_BUCKET_FORMAT},[re,he]=v.useState(n==="groupBy"?Ce.value:s.dateFormat||"YYYY-MM-DD"),[Ye,Z]=v.useState(n==="groupBy"?Ce.customPattern:s.customFormat||""),Fe=re==="custom",[me,qe]=v.useState(s.aliasTemplate||""),[Le,Ke]=v.useState(s.valueAliases||{}),[Se,oe]=v.useState((Us=s.parameters)==null?void 0:Us.filters),Ie=G=>{var X;if(n==="groupBy"&&!ie)return;const Ee=ie??"day";if(G==="custom"){const de=n==="groupBy"?et.getTemporalBucketAuthoringOptions(Ee,Ce.format,A).find(Ge=>Ge.value==="custom"):void 0,Ne=n==="groupBy"?Ye||(((X=de==null?void 0:de.format)==null?void 0:X.presentation.mode)==="pattern"?de.format.presentation.pattern:""):Ye;he(G),Z(Ne),n==="groupBy"&&L(r,et.resolveTemporalBucketAuthoringFormat(Ee,G,Ne))}else he(G),n==="groupBy"?L(r,et.resolveTemporalBucketAuthoringFormat(Ee,G)):n==="detailColumns"&&C(r,G,"")},Re=G=>{if(n==="groupBy"&&!ie)return;const Ee=ie??"day";Z(G),n==="groupBy"?L(r,et.resolveTemporalBucketAuthoringFormat(Ee,"custom",G)):n==="detailColumns"&&C(r,"custom",G)},De=G=>{if(n==="groupBy"){const Ee=et.reconcileTemporalBucketAuthoringFormat(Ce.format,G),X=t.readTemporalBucketAuthoringSelection({fieldId:s.id,dataType:s.dataType,granularity:G,format:Ee,semanticTemporalPresentation:s.semanticTemporalPresentation});he(X.value),Z(X.customPattern),k(r,G)}},te=G=>{qe(G),n==="metrics"&&R(r,G)},ve=G=>{n==="pivotBy"&&y(r,G)},ye=G=>{Ke(G),n==="metrics"&&_(r,G)},Qe=G=>{F(n,r,G)},st=a.getExpressionFieldKind(s);a.getFieldExpressionAnnotation(s);const ut=a.isManagedCalculatedExpressionField(s),it=s.role==="metric"&&ut,kt=ut&&(st==="user_calculated"||st==="inline_expression"&&s.fieldScope!=="domain"),nt=kt?t.resolveLocalCalculatedFieldScope({field:s,sheetFields:(u==null?void 0:u.calculatedFields)||[],dashboardFields:j}):void 0,vt=kt&&(nt==null?void 0:nt.scope)==="sheet",Gt=kt&&(nt==null?void 0:nt.scope)==="dashboard",mt=st==="domain_calculated"||s.fieldScope==="domain",Ht=mt?a.resolveDomainCalculatedFieldForEdit(s,N):void 0,ht=mt?"domain":vt?"sheet":Gt?"dashboard":"card",yt=mt?Ht||s:(vt||Gt)&&(nt!=null&&nt.matchedField)?nt.matchedField:s,Bt=mt?Ht?"effective":g?"loading":D?"unavailable":"unverified":void 0,Mt=G=>{var Ee;if(oe(G),n==="metrics"){const X={...s,parameters:{...s.parameters,filters:G}},de=[...((Ee=l.config)==null?void 0:Ee.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:de})}Te(!1)},Vt=()=>{P(n,r)},Ct=t.getDataType(Me.dataType||s.dataType),pt=Ct==="date",Qt=c==="kpi",At=n==="detailColumns",Jt=(Gs=l.config)==null?void 0:Gs.metricColumns,xt=(Hs=l.config)==null?void 0:Hs.groupByColumns,Nt=a.useCardQueryContext(l),Lt=t.useDashboardStore(G=>G.semanticExecutionPayload),_t=n==="groupBy"&&ie?et.getTemporalBucketAuthoringOptions(ie,Ce.format,A):n==="detailColumns"?$i(ie??"day"):[],is=Fe?"custom":!ie&&n==="groupBy"?void 0:_t.some(G=>G.value===re)?re:((Qs=_t[0])==null?void 0:Qs.value)??"YYYY-MM-DD",Wt=!!c&&a.COMPARISON_SUPPORTED_CHART_TYPES.includes(c),cs=!!c&&a.COMPARISON_TARGET_SUPPORTED_CHART_TYPES.includes(c),St=v.useMemo(()=>xt==null?void 0:xt.find(G=>t.getDataType(G.dataType||"")==="date"),[xt]),ct=v.useMemo(()=>t.resolveCardPrimaryDateField({card:l,cardConfig:l.config||{},semanticExecutionPayload:Lt}),[l,Lt]),Je=v.useMemo(()=>St||(ct?{...ct,id:`semantic-primary:${ct.entityId}:${ct.name}`,label:ct.name,role:"groupby",granularity:ct.defaultGranularity||"day"}:void 0),[St,ct]),H=je.getAuthoredCardFilters(l),ne=v.useMemo(()=>{if(!Je)return!1;const G=H;if(!G)return!1;const Ee=de=>{const Ne=de.field;return Ne?Je.id&&Ne.id===Je.id||Je.qualifiedFieldName&&Ne.qualifiedFieldName===Je.qualifiedFieldName?!0:Ne.name===Je.name:!1},X=de=>de.conditions.some(Ge=>t.getDataType(Ge.field.dataType||"")==="date"&&Ee(Ge))?!0:de.groups.some(Ge=>X(Ge));return X(G)},[H,Je]),se=v.useMemo(()=>zi(l,a.compileDashboardCardFilters({card:l,cardConfig:Nt.queryRelevantConfig,input:Nt.filterCompilationInput,resolvedFields:Nt.resolvedDateFields,semanticExecutionPayload:Lt,timezone:M})),[l,Nt,Lt,M]),we=ne||se,ce=s,pe=((Js=ce.comparison)==null?void 0:Js.mode)==="explicit"?ce.comparison.spec:void 0,Ue=((Xs=(Ws=ce.parameters)==null?void 0:Ws.windowTransform)==null?void 0:Xs.function)||"none",Ve=a.isMetricTransformEnabled(ce),He=Ve?Ue:null,ft=a.supportsMetricTransformForMetric({cardType:c||"table",cardConfig:l.config||{},metric:ce,transformMode:He||"running_total"}),dt=((Zs=ce.comparison)==null?void 0:Zs.mode)==="explicit",We=a.getRunningTotalOrderByCandidates(xt||[]),rt=((sn=(tn=(en=ce.parameters)==null?void 0:en.windowTransform)==null?void 0:tn.orderBy)==null?void 0:sn.fieldId)||"",ds=((rn=(an=(nn=ce.parameters)==null?void 0:nn.windowTransform)==null?void 0:an.orderBy)==null?void 0:rn.direction)||"asc",Xt=We.find(G=>G.id===rt),us=He==="running_total"||He==="moving_average"||He==="previous_period_delta",Ya=Ve&&us&&!!Xt&&t.getDataType(Xt.dataType||"")!=="date",za=a.getDefaultRunningTotalPartitionByFieldIds({cardType:c||"table",cardConfig:l.config||{},orderByFieldId:rt||void 0}),qa=new Set(((ln=(on=ce.parameters)==null?void 0:on.windowTransform)==null?void 0:ln.partitionByFieldIds)||za),$a=c==="pivotTable"||a.isSubtotalEnabledAggregateTable(c||"table",l.config||{}),zs=[...(xt||[]).filter(G=>G.id&&(!us||G.id!==rt)),...$a?(((cn=l.config)==null?void 0:cn.pivotByColumns)||[]).filter(G=>G.id):[]],qs=((mn=(un=(dn=ce.parameters)==null?void 0:dn.windowTransform)==null?void 0:un.movingAverage)==null?void 0:mn.windowSize)||7,Ka=((pn=(hn=(xn=ce.parameters)==null?void 0:xn.windowTransform)==null?void 0:hn.movingAverage)==null?void 0:pn.minPeriods)||1,Ua=((bn=(gn=(fn=ce.parameters)==null?void 0:fn.windowTransform)==null?void 0:gn.previousPeriodDelta)==null?void 0:bn.mode)||"absolute",$s=((yn=(vn=(jn=ce.parameters)==null?void 0:jn.windowTransform)==null?void 0:vn.percentOfTotal)==null?void 0:yn.scope)||"grand_total",Ga=((Sn=(Nn=(Cn=ce.parameters)==null?void 0:Cn.windowTransform)==null?void 0:Nn.percentOfTotal)==null?void 0:Sn.output)||"percent",Ha=v.useMemo(()=>(Jt||[]).some(()=>!1),[Jt]);v.useEffect(()=>{Ve&&Oe(!0)},[Ve]);const Qa=n!=="pivotBy"&&n!=="sortBy",Ja=tc(n,c),Wa=s.memberOrder??"auto",Xa=pt&&n==="groupBy"&&(!Qt||Ha),Za=!Qt&&pt&&(n==="groupBy"||At),er=n==="metrics",tr=!Qt&&Ct==="number"&&(n==="groupBy"||At)&&a.isTableNumericPresentationCardType(c),Zt=Wt&&!l.sql&&!l.python&&n==="metrics",sr=()=>{const G=s,Ee=n==="metrics"&&it;return e.jsxs("div",{className:"space-y-1",children:[!Ee&&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}`}),Ee&&G.calculatedFormula&&e.jsxs("div",{title:a.formatDisplayFormula(G.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:["= ",a.formatDisplayFormula(G.calculatedFormula)]})]})},nr=()=>Qa?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(lt,{value:s.label??"",onSave:Qe,placeholder:"Display label...",type:"text"})]}):null,ar=()=>n!=="sortBy"?null:e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Order"}),e.jsxs(t.Select,{value:o||"asc",onValueChange:G=>i(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"asc",children:"Ascending"}),e.jsx(t.SelectItem,{className:"text-xs",value:"desc",children:"Descending"})]})]})]}),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:Wa,onValueChange:G=>ve(G),children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"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,Ks=()=>Xa?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:De,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:ae.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G,children:t.toTitleCase(G)},G))})]})]}):null,or=()=>Za?e.jsxs(e.Fragment,{children:[Ks(),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:is,onValueChange:Ie,disabled:n==="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:_t.map(G=>e.jsx(t.SelectItem,{className:"text-xs",value:G.value,children:G.label},G.value))})]}),Fe&&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:Ye,onChange:G=>{G.stopPropagation(),Re(G.target.value)},onClick:G=>G.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,lr=()=>tr?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(Es,{value:s.format,onChange:G=>T(At?"detailColumns":"groupBy",r,G),cardType:c,showTitle:!1})]}):null,ir=()=>{var Ee;if(!er)return null;const G=it;return e.jsxs(e.Fragment,{children:[G&&S&&!mt&&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:()=>ze(!0),children:[e.jsx(a.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=>{E(r,X)},disabled:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsx(t.SelectContent,{children:et.getFieldAggregationOptions(s.dataType).map(X=>e.jsx(t.SelectItem,{className:"text-xs",value:X.value,children:X.label},X.value))})]})]}),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(Es,{value:ce.format,onChange:X=>O(r,X),cardType:c,showTitle:!1})]}),e.jsx(a.Collapsible,{open:Pe,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(a.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:[!Pe&&e.jsx("span",{className:"mr-2",children:Ve?t.toTitleCase(Ue.replace(/_/g," ")):"None"}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 transition-transform",Pe?"rotate-180":"")})]})]})}),e.jsxs(a.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:Ve?Ue:"none",onValueChange:X=>z(r,X),disabled:!ft.supported&&!Ve,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:dt,children:"Running Total"}),e.jsx(t.SelectItem,{value:"moving_average",disabled:dt,children:"Moving Average"}),e.jsx(t.SelectItem,{value:"previous_period_delta",disabled:dt,children:"Previous Period Delta"}),e.jsx(t.SelectItem,{value:"percent_of_total",disabled:dt,children:"Percent of Total"})]})]}),!ft.supported&&!Ve&&e.jsx("div",{className:"text-xs text-muted-foreground",children:ft.reason}),dt&&!Ve&&e.jsx("div",{className:"text-xs text-muted-foreground",children:"Disable comparison to enable metric transforms."})]}),Ve&&e.jsxs(e.Fragment,{children:[us&&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:rt,onValueChange:X=>V(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:We.filter(X=>!!X.id).map(X=>e.jsx(t.SelectItem,{value:X.id,className:"text-xs",children:X.label||X.name},X.id))})]}),!rt&&e.jsx("div",{className:"text-xs text-amber-700",children:"No date trend detected. Select an order field."}),Ya&&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:ds,onValueChange:X=>$(r,X),disabled:!rt,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"})]})]})]})]}),He==="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:qs,onChange:X=>U(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:qs,className:"h-8 text-xs",value:Ka,onChange:X=>J(r,Number(X.target.value))})]}),He==="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:Ua,onValueChange:X=>W(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"})]})]})]}),He==="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:$s,onValueChange:X=>ee(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=>ue(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"})]})]})]})]}),(He==="running_total"||He==="moving_average"||He==="previous_period_delta"||He==="percent_of_total"&&$s==="partition_total")&&zs.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:zs.map(X=>{const de=!!X.id&&qa.has(X.id);return e.jsxs("button",{type:"button",onClick:()=>X.id&&Q(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)})})]})]})]})]})}),Zt&&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:ce.comparison?ce.comparison.mode==="off"?"off":ce.comparison.spec.kind:"inherit",disabled:Ve,onValueChange:X=>B(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=!Je||!we,de=Je?we?void 0:"Add a date filter to enable":"Configure a semantic primary date or add a date axis",Ne=(Ge,Ze)=>e.jsx(t.TooltipProvider,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.SelectItem,{value:Ge,disabled:X,title:de,children:Ze})}),X&&de&&e.jsx(t.TooltipContent,{side:"right",children:de})]})});return e.jsxs(e.Fragment,{children:[Ne("previous_period","Previous Period"),Ne("previous_year","Previous Year")]})})(),cs&&e.jsx(t.SelectItem,{value:"target",children:"Target"})]})]}),!ce.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."})]}),Zt&&pe&&(pe.kind==="previous_period"||pe.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:pe.kind==="previous_year"?"Years back":"Periods back"}),e.jsx(t.Input,{type:"number",min:1,step:1,value:pe.kind==="previous_year"?pe.offsetYears||1:pe.offsetPeriods||1,onChange:X=>{const de=Number(X.target.value);!Number.isSafeInteger(de)||de<=0||(pe.kind==="previous_year"?Y(r,{...pe,offsetYears:de===1?void 0:de}):Y(r,{...pe,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:pe.alignment||"calendar",onValueChange:X=>Y(r,{...pe,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:pe.toDate===!0,onCheckedChange:X=>Y(r,{...pe,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:(Je==null?void 0:Je.label)||(Je==null?void 0:Je.name)}),". The resolved comparison dates appear after the card runs."]})]}),Zt&&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:a.getMetricComparisonPolarity(ce),disabled:!!ce.semanticComparisonPolarity,onValueChange:X=>q(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"})]})]}),ce.semanticComparisonPolarity&&e.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Governed by this metric's semantic definition."})]}),Zt&&((Ee=ce.comparison)==null?void 0:Ee.mode)==="explicit"&&ce.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:ce.comparison.spec.targetValue!==void 0&&ce.comparison.spec.targetValue!==null?String(ce.comparison.spec.targetValue):"",onChange:X=>{const de=X.target.value;if(de===""){fe(r,void 0);return}const Ne=Number(de);fe(r,Number.isFinite(Ne)?Ne:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Se==null?void 0:Se.conditions)&&Se.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Se.conditions.map(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:()=>{Ae(X),Te(!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,Ne)=>e.jsx("div",{children:String(de)},Ne))})]})})]})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:de=>{var Ge;de.stopPropagation();const Ne=Se.conditions.filter(Ze=>Ze.id!==X.id);if(Ne.length>0){const Ze={...Se,conditions:Ne};Mt(Ze)}else if(oe(void 0),n==="metrics"){const Ze={...s,parameters:{...s.parameters,filters:void 0}},ot=[...((Ge=l.config)==null?void 0:Ge.metricColumns)||[]];ot[r]=Ze,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:ot})}},children:e.jsx(le.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:()=>{Ae(null),Te(!0)},children:[e.jsx(a.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(Wi,{column:s}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ki,{aliasTemplate:me,onAliasTemplateChange:te}),e.jsx(Ui,{valueAliases:Le,onValueAliasesChange:ye})]})]})};Se!=null&&Se.conditions&&Se.conditions.length>0;const cr=n!=="sortBy";return e.jsxs(e.Fragment,{children:[e.jsx(Fa,{id:s.id,label:a.getMetricDisplayLabel(s),dataType:Ct,calculated:a.getCalculatedGlyphKind(s),open:be,onOpenChange:ge,onRemove:Vt,sortDirection:o,onSortDirectionChange:n==="sortBy"?i:void 0,badge:e.jsx(e.Fragment,{children:n==="metrics"&&((wn=Se==null?void 0:Se.conditions)==null?void 0:wn.length)&&!be&&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(a.Filter,{className:"h-2.5 w-2.5"}),e.jsx("span",{children:Se.conditions.length})]})}),e.jsx(t.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Se.conditions.map(G=>e.jsxs("div",{children:[G.field.label,":"," ",Array.isArray(G.value)?`${G.value.length} values`:String(G.value)]},G.id))})})]})})}),children:cr&&e.jsxs(e.Fragment,{children:[sr(),ar(),rr(),nr(),c==="kpi"&&Ks(),or(),lr(),ir()]})}),ke&&e.jsx(Ra,{open:ke,onOpenChange:G=>{Te(G),G||Ae(null)},availableFields:f,existingFilters:Se,editingCondition:Be,onSave:G=>{var Ee;if(G)Mt(G);else if(oe(void 0),n==="metrics"){const X={...s,parameters:{...s.parameters,filters:void 0}},de=[...((Ee=l.config)==null?void 0:Ee.metricColumns)||[]];de[r]=X,t.useEditorStore.getState().actions.updateCardConfig(l.id,{metricColumns:de})}Ae(null)}}),_e&&n==="metrics"&&it&&e.jsx(a.CalculatedFieldEditor,{open:_e,onOpenChange:ze,availableFields:N,existingField:yt,existingFieldScope:ht,domainDefinitionStatus:Bt,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=ht==="dashboard"?j:X.calculatedFields||[],{cardConfigPatch:Ge,nextStoredFields:Ze,nextSharedFields:ot}=a.saveCalculatedFieldToCardScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sharedFields:Ne,updatedField:G,editingField:yt,previousScope:ht});Object.keys(Ge).length&&de.updateCardConfig(l.id,Ge),de.updateCard(l.id,{calculatedFields:Ze}),ht==="dashboard"&&ot!==Ne?h(ot):ot!==Ne&&a.commitSharedCalculatedFields({nextSharedFields:ot,currentSharedFields:Ne,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b})},onSaveToSheet:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=s,Ge=X.calculatedFields||[],{cardConfigPatch:Ze,nextStoredFields:ot,nextSheetFields:ms,nextDashboardFields:wt}=a.saveCalculatedFieldToSheetScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sheetFields:Ge,dashboardFields:j,updatedField:{...G,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:yt,previousScope:ht});a.commitSharedCalculatedFields({nextSharedFields:ms,currentSharedFields:Ge,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),wt&&wt!==j&&h(wt),Object.keys(Ze).length&&de.updateCardConfig(l.id,Ze),de.updateCard(l.id,{calculatedFields:ot})},onSaveToDashboard:G=>{if(G.role!=="metric")return;const{card:Ee,frame:X,actions:de}=t.useEditorStore.getState(),Ne=s,Ge=X.calculatedFields||[],{cardConfigPatch:Ze,nextStoredFields:ot,nextSharedFields:ms,nextSheetFields:wt}=a.saveCalculatedFieldToSharedScope({cardConfig:Ee.config,storedFields:Ee.calculatedFields||[],sharedFields:j,sheetFields:Ge,updatedField:{...G,id:Ne.id,aliasTemplate:Ne.aliasTemplate,valueAliases:Ne.valueAliases,parameters:Ne.parameters,customFormat:Ne.customFormat},editingField:yt,previousScope:ht});h(ms),wt&&wt!==Ge&&a.commitSharedCalculatedFields({nextSharedFields:wt,currentSharedFields:Ge,isVisualEditing:x,selectedSheetId:m,updateFrame:de.updateFrame,updateSheetCalculatedFields:b}),Object.keys(Ze).length&&de.updateCardConfig(l.id,Ze),de.updateCard(l.id,{calculatedFields:ot})},cardId:l.id})]})}function ac({field:s,onRemove:n}){const[r,o]=v.useState(!1);return e.jsx(Fa,{id:s.id,label:a.getMetricDisplayLabel(s),dataType:s.dataType,calculated:a.getCalculatedGlyphKind(s),open:r,onOpenChange:o,onRemove:n,children:e.jsx(Is,{fieldId:s.id})})}function rc({concept:s}){const{title:n,description:r}=oc[s];return e.jsxs(a.HoverCard,{openDelay:150,closeDelay:50,children:[e.jsx(a.HoverCardTrigger,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`What does ${n} 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(a.CircleHelp,{className:"h-3 w-3"})})}),e.jsxs(a.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:n}),e.jsx("p",{className:"text-[11px] leading-[1.45] text-muted-foreground",children:r})]}),s!=="detailColumns"&&e.jsx(lc,{highlight:s})]})]})}const oc={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 lc({highlight:s}){const n=s==="pivotBy",r=s==="groupBy",o=s==="metrics",i="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(d=>e.jsx("th",{className:t.cn("px-1.5 py-1 text-center font-normal text-muted-foreground",n&&i),children:d},d))]})}),e.jsx("tbody",{children:Zn.map((d,c)=>e.jsxs("tr",{className:t.cn(c!==Zn.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&&i),children:d.label}),d.values.map((l,u)=>e.jsx("td",{className:t.cn("px-1.5 py-1 text-right font-mono tabular-nums text-muted-foreground",o&&i),children:l},u))]},d.label))})]})})}const Zn=[{label:"Electronics",values:["2,300","1,800","3,400"]},{label:"Clothing",values:["1,300","620","480"]}],ic={groupBy:a.Rows3,pivotBy:Ds,metrics:Mr,detailColumns:t.Table2,sortBy:sa};function zt({onRemoveField:s,zone:n,fields:r,label:o,placeholder:i,shouldShow:d,hasPivotColumns:c=!1,activeField:l=null}){const{isOver:u,setNodeRef:x}=a.useDroppable({id:n}),{updateSortByColumn:m}=t.useEditorActions(),b=t.useEditorStore(D=>D.card),h=t.useEditorStore(D=>D.card.type),p=r.length>0,j=v.useMemo(()=>!l||!u?!0:a.validateFieldForChartType(l,n,h).isValid,[l,u,n,h]),N=(D,I)=>{var S;!((S=b.config)!=null&&S.sortByColumns)||b.config.sortByColumns.findIndex(M=>M.id===D)===-1||m(b.id,D,{direction:I})};if(n==="sortBy"&&d===!1)return null;const f=n!=="sortBy"&&h!=="kpi",g=ic[n]||a.Plus;return e.jsxs("div",{className:"w-full",role:"group","aria-label":o,children:[e.jsx(t.Label,{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}),e.jsx("div",{ref:x,className:t.cn("rounded-control transition-colors",{"border border-foreground/40 bg-muted/50":u&&j,"border border-destructive/40 bg-destructive/5":u&&!j,"border border-dashed border-border/50 bg-background":!u&&!p}),children:r.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(g,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"}),e.jsx("span",{children:i}),f&&e.jsx(rc,{concept:n})]}):e.jsx(a.SortableContext,{id:n,items:r.map(D=>D.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-1",children:r.map((D,I)=>{const S=D.direction;return h==="matrixTable"?e.jsx(ac,{field:D,onRemove:()=>s(n,I)},D.id):e.jsx(nc,{field:D,zone:n,index:I,sortDirection:S,onSortDirectionChange:M=>N(D.id,M),hasPivotColumns:c,cardType:h},D.id)})})})})]})}const cc=[];function dc({onRemoveField:s,onResetFields:n,groupByFields:r,pivotByFields:o,metricsFields:i,sortByFields:d,detailFields:c,activeField:l}){var Q,U,J;const[u,x]=v.useState(!1);t.useEditorStore(W=>{var ee;return!!((ee=W.card.customCardPreferences)!=null&&ee.url)});const m=t.useEditorStore(W=>W.card),b=t.useEditorStore(W=>W.frame),h=xe.findCustomVisualConfigCard(b,m),{manifest:p}=a.useCustomVisual(((Q=h==null?void 0:h.customCardPreferences)==null?void 0:Q.url)||""),j=(U=p==null?void 0:p.visuals)==null?void 0:U.find(W=>{var ee;return W.name===((ee=h==null?void 0:h.customCardPreferences)==null?void 0:ee.componentName)}),N=xe.resolveMultiInputType(h,j)==="multiple";N&&((J=h==null?void 0:h.customCardPreferences)!=null&&J.url);const f=xe.getConfigSlotExpectedType(j==null?void 0:j.slots);t.useEditorStore(W=>W.actions.updateCardConfig);const g=t.useEditorStore(W=>W.actions.updateCard),D=t.useEditorStore(W=>W.actions.updateFrame),I=t.useDashboardStore(W=>W.isVisualEditing),w=t.useDashboardStore(W=>W.selectedSheetId),S=t.useDashboardStore(W=>W.actions.updateSheetCalculatedFields),M=t.useDashboardStore(W=>W.actions.updateDashboardCalculatedFields),F=t.useDashboardStore(W=>{var ee;return W.visualEditPendingDashboardCalculatedFields??((ee=W.dashboard)==null?void 0:ee.calculatedFields)})??cc,{scopedFields:E}=a.useScopedFields(),{userContext:C}=a.useCurrentUserInfo(),T=N&&(h==null?void 0:h.id)===m.id&&f?f:m==null?void 0:m.type,L=T==="detailTable",k=r.length>0||i.length>0||c.length>0,R=!L&&(T!=="kpi"||i.length<=2),y=!L,_=!L&&T!=="kpi",O=T!=="kpi"&&T!=="matrixTable"&&k,P=L,B="Drop sort fields here",Y=a.canEditLocalCalculatedFields(C),q=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(T),z=_&&!q,V=()=>T==="kpi"?{label:"Trend By",placeholder:"Drop trend field here"}:{label:"Rows",placeholder:"Drop dimensions here"},$=()=>T==="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"}),k&&e.jsx("button",{type:"button","aria-label":"Reset all field selections",onClick:n,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:[R&&e.jsx(zt,{zone:"groupBy",onRemoveField:s,fields:r,label:V().label,placeholder:V().placeholder,activeField:l}),z&&e.jsx(zt,{zone:"pivotBy",onRemoveField:s,fields:o,label:"Pivot Columns",placeholder:"Drop pivot fields here",activeField:l}),y&&e.jsx(zt,{zone:"metrics",onRemoveField:s,fields:i,label:$().label,placeholder:$().placeholder,hasPivotColumns:o.length>0,activeField:l}),P&&e.jsx(zt,{zone:"detailColumns",onRemoveField:s,fields:c,label:"Columns",placeholder:"Drop columns here"}),i.length>=1&&Y&&e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:()=>x(!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(a.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),O&&e.jsx(zt,{zone:"sortBy",onRemoveField:s,fields:d,label:"Sort By",placeholder:B,activeField:l})]}),e.jsx(a.CalculatedFieldEditor,{open:u,onOpenChange:x,availableFields:E,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:W=>{if(W.role!=="metric")return;const{nextStoredFields:ee}=a.saveCalculatedFieldToCardScope({storedFields:m.calculatedFields||[],sharedFields:b.calculatedFields||[],updatedField:W,previousScope:"card"});g(m.id,{calculatedFields:ee})},onSaveToSheet:W=>{if(W.role!=="metric")return;const ee=b.calculatedFields||[],{nextSheetFields:ue}=a.saveCalculatedFieldToSheetScope({storedFields:m.calculatedFields||[],sheetFields:ee,updatedField:W,previousScope:"sheet"});a.commitSharedCalculatedFields({nextSharedFields:ue,currentSharedFields:ee,isVisualEditing:I,selectedSheetId:w,updateFrame:D,updateSheetCalculatedFields:S})},onSaveToDashboard:W=>{if(W.role!=="metric")return;const{nextSharedFields:ee}=a.saveCalculatedFieldToSharedScope({storedFields:m.calculatedFields||[],sharedFields:F,updatedField:W,previousScope:"dashboard"});M(ee)},cardId:m.id})]})}function uc(){var D,I,w;const s=t.useEditorStore(S=>{var M;return(M=S.card)==null?void 0:M.type}),n=s==="kpi",[r,o]=v.useState(n),[i,d]=v.useState(!1),c=t.useEditorStore(S=>{var M;return!!((M=S.card.customCardPreferences)!=null&&M.url)}),l=t.useEditorStore(S=>S.card),u=t.useEditorStore(S=>S.frame),x=xe.findCustomVisualConfigCard(u,l),{manifest:m}=a.useCustomVisual(((D=x==null?void 0:x.customCardPreferences)==null?void 0:D.url)||""),b=(I=m==null?void 0:m.visuals)==null?void 0:I.find(S=>{var M;return S.name===((M=x==null?void 0:x.customCardPreferences)==null?void 0:M.componentName)}),p=xe.resolveMultiInputType(x,b)==="multiple"&&!!((w=x==null?void 0:x.customCardPreferences)!=null&&w.url),j=!c||p,N=c||p,f=n?"KPI Settings":"Chart Settings",g=j&&!a.isTableChartType(s);return v.useEffect(()=>{n&&o(!0)},[n]),!g&&!N?null:e.jsxs("div",{className:"shrink-0 border-t border-border bg-background",children:[g&&r&&e.jsx("div",{className:t.cn("overflow-y-auto border-b border-border px-4",n?"max-h-[72vh]":"max-h-[50vh]"),children:e.jsx(a.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(La,{mode:"config"})})}),g&&e.jsxs("button",{type:"button",onClick:()=>o(S=>!S),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(a.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:f})]}),e.jsx(le.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",r&&"rotate-180"),strokeWidth:1.75})]}),N&&i&&e.jsx("div",{className:"max-h-[40vh] overflow-y-auto border-b border-t border-border px-4",children:e.jsx(Ta,{})}),N&&e.jsxs("button",{type:"button",onClick:()=>d(S=>!S),className:t.cn("flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted/50",g&&"border-t border-border"),children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(na,{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(le.ChevronDown,{className:t.cn("h-3 w-3 text-muted-foreground transition-transform",i&&"rotate-180"),strokeWidth:1.75})]})]})}function mc({onEditJoins:s}){const n=t.useEditorStore(u=>u.card),{autoJoinMetadata:r}=a.useEditorCardQuery(n);if(!(r!=null&&r.autoResolved))return null;const{resolvedJoinPlan:o}=r,i=(o==null?void 0:o.joins)||[];if(i.length===0)return null;const d=u=>!u||u.length===0?"No conditions":u.map(x=>{var p,j,N,f;const m=`${(p=x.source)==null?void 0:p.entityName}.${(j=x.source)==null?void 0:j.name}`,b=`${(N=x.target)==null?void 0:N.entityName}.${(f=x.target)==null?void 0:f.name}`,h=x.operator||"=";return`${m} ${h} ${b}`}).join(" AND "),c=u=>!u.joinKeyGroups||u.joinKeyGroups.length===0?"No conditions defined":u.joinKeyGroups.length===1?d(u.joinKeyGroups[0].keys):u.joinKeyGroups.map((x,m)=>({id:m,operator:x.operator,condition:d(x.keys)})),l=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":`${i.length} resolved ${i.length===1?"join":"joins"}`,children:i.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:i.map((u,x)=>{const m=c(u),b=Array.isArray(m);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(a.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:b?m.map(h=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h.condition}),h.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",h.operator,")"]})]},h.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:m})})})]},u.id||x)})})})]})});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(a.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"}),l,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(a.SquarePen,{className:"h-3 w-3",strokeWidth:1.75})})]})}function xc({onRemoveField:s,onResetFields:n,selectedChart:r,onChartChange:o,isVisible:i=!0,onToggleVisibility:d,groupByFields:c,pivotByFields:l,metricsFields:u,sortByFields:x,detailFields:m,activeField:b}){var E;const[h,p]=v.useState(!1),j=t.useEditorStore(C=>C.card),N=t.useEditorStore(C=>C.editorContext),f=t.useEditorStore(C=>C.actions.updateCardConfig),g=(N==null?void 0:N.type)==="documentSection",{autoJoinMetadata:D}=a.useEditorCardQuery(j),I=je.getAuthoredCardJoinPlan(j)||(D!=null&&D.autoResolved?D.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),w=((E=j==null?void 0:j.dataSource)==null?void 0:E.selectedEntities)||[],S=C=>{f(j.id,je.withAuthoredCardJoinPlan(j,C)),p(!1)},M=()=>{f(j.id,je.withAuthoredCardJoinPlan(j,void 0)),p(!1)},A=()=>{p(!1)},F=()=>{p(!0)};return i?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:[!g&&e.jsxs("div",{className:"flex items-start",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Vo,{selectedChart:r,onChartChange:o})}),d&&e.jsx("div",{className:"px-2 pt-4",children:e.jsx(a.IconButton,{tooltip:"Hide chart configuration","aria-label":"Hide chart configuration",onClick:d,className:"h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx(a.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(mc,{onEditJoins:F})}),e.jsx(dc,{onRemoveField:s,onResetFields:n,groupByFields:c,pivotByFields:l,metricsFields:u,sortByFields:x,detailFields:m,activeField:b})]}),e.jsx(uc,{}),e.jsx(ra,{open:h,onOpenChange:p,joinPlan:I,availableDataSources:w,onSave:S,onCancel:A,onRemove:M,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:d&&e.jsx(a.IconButton,{tooltip:"Show chart configuration","aria-label":"Show chart configuration",onClick:d,className:"mt-3 h-7 w-7 rounded-[5px] p-0 text-muted-foreground hover:text-foreground",children:e.jsx($e.ChevronRight,{className:"h-4 w-4",strokeWidth:1.75})})})}function hc({initialFilters:s,availableFields:n}={}){const[r,o]=v.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(w=>w.card.dataSource);const{filterableFields:i,isLoading:d}=a.useFilterableFields(),c=n||i||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=w=>{const S=M=>{if(M.id===w){const A=c[0]||l,F=t.getDataType(A.dataType)==="date";return{...M,conditions:[...M.conditions,{id:`condition-${Date.now()}`,field:A,operator:F?"between":"=",value:F?[]:""}]}}return{...M,groups:M.groups.map(S)}};o(S(r))},x=w=>{const S=M=>{if(M.id===w){const A=c[0]||l,F=t.getDataType(A.dataType)==="date";return{...M,groups:[...M.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:A,operator:F?"between":"=",value:F?[]:""}],groups:[]}]}}return{...M,groups:M.groups.map(S)}};o(S(r))},m=(w,S)=>{const M=A=>A.id===w?{...A,conditions:A.conditions.filter(F=>F.id!==S)}:{...A,groups:A.groups.map(M)};o(M(r))},b=(w,S)=>{const M=A=>A.id===w?{...A,groups:A.groups.filter(F=>F.id!==S)}:{...A,groups:A.groups.map(M)};o(M(r))},h=(w,S,M,A)=>{if(M==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const F=E=>E.id===w?{...E,conditions:E.conditions.map(C=>C.id===S?{...C,[M]:A}:C)}:{...E,groups:E.groups.map(F)};o(F(r))},p=(w,S,M)=>{const A=F=>F.id===w?{...F,conditions:F.conditions.map(E=>E.id===S?{...E,...M}:E)}:{...F,groups:F.groups.map(A)};o(A(r))},j=(w,S)=>{const M=A=>A.id===w?{...A,logicalOperator:S}:{...A,groups:A.groups.map(M)};o(M(r))},N=(w,S)=>{const M=A=>A.id===w?{...A,negate:S}:{...A,groups:A.groups.map(M)};o(M(r))},f=(w,S,M)=>{const A=F=>F.id===w?{...F,conditions:a.arrayMove(F.conditions,S,M)}:{...F,groups:F.groups.map(A)};o(A(r))},g=(w,S,M)=>{const A=F=>F.id===w?{...F,groups:a.arrayMove(F.groups,S,M)}:{...F,groups:F.groups.map(A)};o(A(r))},D=w=>{if(!w||w.conditions.length===0&&w.groups.length===0)return"-- No filters defined";const S=A=>{let F="";typeof A.field=="object"?F=A.field.entityName?`${A.field.entityName}.${A.field.name}`:A.field.name:F=String(A.field);const E=A.operator;let C=A.value;if(A.field.dataType==="string"&&!["in","not in"].includes(A.operator))typeof C=="string"?C=`'${C}'`:Array.isArray(C)&&(C=`'${C.join(", ")}'`);else if(A.field.dataType==="date"||A.field.dataType==="datetime"||A.field.dataType==="timestamp")if(A.operator==="between"&&Array.isArray(C)&&C.length===2){const T=C[0]?`'${C[0]}'`:"NULL",L=C[1]?`'${C[1]}'`:"NULL";return`${F} BETWEEN ${T} AND ${L}`}else if((A.operator==="in"||A.operator==="not in")&&Array.isArray(C)){const T=C.map(L=>L?`'${L}'`:"NULL").join(", ");return`${F} ${E} (${T})`}else typeof C=="string"||C instanceof Date?C=`'${C}'`:Array.isArray(C)&&C.length>0&&(C=`'${C[0]}'`);else if(["in","not in"].includes(A.operator)){let T=[];Array.isArray(C)?T=C.map(L=>typeof L=="string"?`'${L}'`:String(L)):typeof C=="string"?T=C.split(",").map(L=>{const k=L.trim();return A.field.dataType==="string"?`'${k}'`:k}):typeof C=="number"&&(T=[String(C)]),C=`(${T.join(", ")})`}switch(E){case"contains":return typeof C=="string"?`${F} LIKE '%${C.replace(/'/g,"")}'`:`${F} LIKE '%${String(C)}'`;case"startsWith":return typeof C=="string"?`${F} LIKE '${C.replace(/'/g,"")}%'`:`${F} LIKE '${String(C)}%'`;case"endsWith":return typeof C=="string"?`${F} LIKE '%${C.replace(/'/g,"")}'`:`${F} LIKE '%${String(C)}'`;case"isNull":return`${F} IS NULL`;case"isNotNull":return`${F} IS NOT NULL`;default:return`${F} ${E} ${C}`}},M=A=>{const F=A.conditions.map(S),E=A.groups.map(k=>M(k)),C=[...F,...E].filter(Boolean);if(C.length===0)return"";const T=C.join(` ${A.logicalOperator} `),L=C.length>1?`(${T})`:T;return A.negate?`NOT ${L}`:L};return M(w)},I=r.conditions.length>0||r.groups.length>0;return{currentFilters:r,setCurrentFilters:o,availableFields:c,isLoading:d,addCondition:u,addGroup:x,removeCondition:m,removeGroup:b,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:N,reorderConditions:f,reorderGroups:g,generateSQLPreview:D,hasAnyFilters:I}}function pc({children:s,className:n,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",n),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function fc({value:s,onValueChange:n,availableFields:r,placeholder:o="Select field",className:i}){const[d,c]=v.useState(!1),l=v.useMemo(()=>new Set(s?[s.id]:[]),[s]),u=s?a.getFieldDisplayLabel(s):null;return e.jsxs(t.Popover,{modal:!0,open:d,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,title:s?`${s.entityName}.${s.name}`:void 0,className:t.cn("min-w-0 justify-between gap-1.5 font-normal",!s&&"text-muted-foreground",i),children:[u?e.jsx(pc,{className:"w-auto min-w-0 flex-1 text-left text-[12px]",children:u}):e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:o}),e.jsx(a.ChevronsUpDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"flex w-80 flex-col rounded-control p-1.5",align:"start",onOpenAutoFocus:x=>{var m,b;x.preventDefault(),(b=(m=x.currentTarget)==null?void 0:m.querySelector('input[type="text"]'))==null||b.focus()},children:e.jsx(a.FieldOptionList,{fields:r,selectedIds:l,onSelect:x=>{n(x),c(!1)},density:"compact",listLabel:"Fields",listClassName:"max-h-80"})})]})}function Pa(s){const n=t.useEditorStore(c=>c.card.dataSource),r=t.useEditorStore(c=>c.card.connectionId),o=t.useEditorStore(c=>c.selectedConnectionId),i=v.useMemo(()=>({id:`card-filter-option:${s.id}`,...ya(s,{dataSource:n,connectionId:o||(n==null?void 0:n.connectionId)||r})}),[r,n,s,o]),d=v.useMemo(()=>a.createExplicitDashboardInputTargetContext({filter:i}),[i]);return a.useFilterOptionBrowse(i,{inputContext:d,currentSelectionPolicy:"exclude"})}function gc({field:s,selected:n,onChange:r,placeholder:o="Select values…",className:i}){const[d,c]=ss.useState(!1),l=Pa(s),u=ss.useMemo(()=>new Set(n.map(h=>a.getFilterOptionValueIdentity(h))),[n]),x=h=>{var p,j;return((j=(p=l.allRecords.find(N=>a.getFilterOptionValueIdentity(N.value)===a.getFilterOptionValueIdentity(h)))==null?void 0:p.label)==null?void 0:j.toString())??h},m=h=>{r(n.filter(p=>p!==h))},b=h=>{c(h),!h&&l.query&&l.setQuery("")};return e.jsx("div",{className:t.cn("w-full",i),children:e.jsxs(t.Popover,{open:d,onOpenChange:b,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,className:"h-auto min-h-7 w-full justify-between gap-1.5 px-2 py-0.5 font-normal",children:[e.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap gap-1",children:n.length>0?n.map(h=>{const p=x(h);return e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-[4px] border border-border/70 bg-muted/40 px-1.5 py-0.5 text-[11px] leading-[14px] text-foreground",children:[e.jsx("span",{className:"truncate",children:p}),e.jsx("span",{role:"button",tabIndex:0,"aria-label":`Remove ${p}`,className:"shrink-0 rounded-[2px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring",onKeyDown:j=>{j.key==="Enter"&&m(h)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),m(h)},children:e.jsx(le.X,{className:"h-3 w-3"})})]},h)}):e.jsx("span",{className:"truncate text-muted-foreground",children:o})}),e.jsx(le.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:h=>{var p,j;h.preventDefault(),(j=(p=h.currentTarget)==null?void 0:p.querySelector('input[type="text"]'))==null||j.focus()},children:e.jsx(a.FilterOptionList,{records:l.displayRecords,selectedIdentities:u,onToggle:h=>{const p=String(h.value);n.includes(p)?m(p):r([...n,p])},browse:l,searchPlaceholder:`Search ${(s.label||s.name).toLowerCase()}`,listLabel:s.label||s.name,density:"compact"})})]})})}function bc({field:s,value:n,onChange:r,placeholder:o="Select value…",className:i}){var b,h;const[d,c]=ss.useState(!1),l=Pa(s),u=ss.useMemo(()=>new Set(n?[a.getFilterOptionValueIdentity(n)]:[]),[n]),x=n?((h=(b=l.allRecords.find(p=>a.getFilterOptionValueIdentity(p.value)===a.getFilterOptionValueIdentity(n)))==null?void 0:b.label)==null?void 0:h.toString())??n:"",m=p=>{c(p),!p&&l.query&&l.setQuery("")};return e.jsxs(t.Popover,{open:d,onOpenChange:m,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,className:t.cn("min-w-0 flex-1 justify-between gap-1.5 px-2 font-normal",i),children:[e.jsx("span",{className:t.cn("truncate",!n&&"text-muted-foreground"),children:n?x:o}),e.jsx(le.ChevronDown,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:p=>{var j,N;p.preventDefault(),(N=(j=p.currentTarget)==null?void 0:j.querySelector('input[type="text"]'))==null||N.focus()},children:e.jsx(a.FilterOptionList,{records:l.displayRecords,selectedIdentities:u,onToggle:p=>{r(String(p.value)),m(!1)},selectionMode:"single",browse:l,searchPlaceholder:`Search ${(s.label||s.name).toLowerCase()}`,listLabel:s.label||s.name,density:"compact"})})]})}function jc({value:s,operator:n,onChange:r,className:o}){const i=a.useTimezone(),d=n==="between"||n==="not between",c=v.useMemo(()=>{if(!(!s||!d)&&Array.isArray(s)&&s.length===2){const b=t.parseFilterDateValue(s[0],i,"start"),h=t.parseFilterDateValue(s[1],i,"end");if(b&&h)return{from:b,to:h}}},[s,d,i]),l=v.useMemo(()=>{if(!s||d)return;const b=Array.isArray(s)?s[0]:s;return t.parseFilterDateValue(b,i,"start")},[s,d,i]),u=b=>n==="<="||n===">"?t.endOfDayInTimezone(b,i):t.startOfDayInTimezone(b,i),x=b=>{if(!b){r([]);return}if(b.from&&b.to){r([b.from.toISOString(),b.to.toISOString()]);return}r([])},m=b=>{if(!b){r("");return}const h=u(b);r(h.toISOString())};return e.jsx(a.DateRangePicker,{value:d?c:void 0,selectionMode:d?"range":"single",singleValue:d?void 0:l,onChange:x,onSingleChange:m,timezone:i,showRelativeTab:d,className:t.cn("min-w-0",o),buttonClassName:"h-7 text-[12px] [&>span]:text-[12px]",placeholder:"Select date…"})}const _s=["contains","startsWith","endsWith","like","not like"],vc=["=","!=",">",">=","<","<=",..._s,"in","not in","isNull","isNotNull"],yc=["=","!=",..._s,"in","not in","isNull","isNotNull"],Cc=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Nc=["=","!=","isNull","isNotNull"],Sc=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],wc={"=":"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 ws(s){return wc[s]||t.titleCase(s)}function Tc(s){switch(s){case"string":return yc;case"number":return Cc;case"boolean":return Nc;case"date":return Sc;default:return vc}}const Oa="w-[68px] shrink-0",Ys="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Ba({value:s,onValueChange:n,"aria-label":r}){return e.jsxs(t.Select,{value:s,onValueChange:o=>n(o),children:[e.jsx(t.SelectTrigger,{size:"xs","aria-label":r,className:t.cn(Oa,"font-medium"),children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{className:"min-w-[var(--radix-select-trigger-width)]",children:[e.jsx(t.SelectItem,{value:"AND",className:"text-[12px] font-medium",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",className:"text-[12px] font-medium",children:"OR"})]})]})}function Va({condition:s,index:n,groupId:r,groupLogicalOperator:o,onUpdateCondition:i,onRemoveCondition:d,onUpdateGroupOperator:c,availableFields:l,updateConditionFields:u}){const{attributes:x,listeners:m,setNodeRef:b,transform:h,transition:p,isDragging:j}=a.useSortable({id:s.id}),N={transform:a.CSS.Transform.toString(h),transition:p},f=t.getDataType(s.field.dataType),g=s.operator==="isNull"||s.operator==="isNotNull",D=s.operator==="in"||s.operator==="not in";return e.jsxs("div",{ref:b,style:N,className:t.cn("flex items-center gap-2 rounded-control px-1.5 py-1 transition-colors hover:bg-muted/40",j&&"z-50 opacity-50"),children:[e.jsx("button",{type:"button",...x,...m,"aria-label":"Drag to reorder condition",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:e.jsx(a.GripVertical,{className:"h-3.5 w-3.5"})}),n>0?e.jsx(Ba,{value:o,onValueChange:I=>c(r,I),"aria-label":"Logical operator"}):e.jsx("span",{className:t.cn(Oa,"text-center",Ys),children:"Where"}),e.jsx(fc,{value:s.field,onValueChange:I=>{const w=I,S=t.getDataType(w.dataType)==="date";u(r,s.id,{field:w,value:"",operator:S?"between":"="})},availableFields:l,placeholder:"Select field",className:"w-60 shrink-0"}),e.jsxs(t.Select,{value:s.operator,onValueChange:I=>{I==="in"||I==="not in"?u(r,s.id,{operator:I,value:[]}):I==="isNull"||I==="isNotNull"?u(r,s.id,{operator:I,value:null}):I==="between"||I==="not between"?u(r,s.id,{operator:I,value:[]}):u(r,s.id,{operator:I,value:""})},children:[e.jsx(t.SelectTrigger,{size:"xs","aria-label":"Operator",className:"w-40 shrink-0",children:e.jsx(t.SelectValue,{children:s.operator?ws(s.operator):""})}),e.jsx(t.SelectContent,{children:Tc(f).map(I=>e.jsx(t.SelectItem,{value:I,children:ws(I)},I))})]}),g?e.jsx("div",{className:"min-w-0 flex-1"}):f==="string"?D?e.jsx(gc,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(I=>typeof I=="string")?s.value:[],onChange:I=>u(r,s.id,{value:I}),placeholder:"Select values…",className:"min-w-0 flex-1"}):_s.includes(s.operator)?e.jsx(t.Input,{size:"xs",value:typeof s.value=="string"?s.value:"",onChange:I=>u(r,s.id,{value:I.target.value}),className:"min-w-0 flex-1",placeholder:`${ws(s.operator)}…`}):e.jsx(bc,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:I=>u(r,s.id,{value:I}),placeholder:"Select value…",className:"min-w-0 flex-1"}):f==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:I=>u(r,s.id,{value:I==="true"}),children:[e.jsx(t.SelectTrigger,{size:"xs",className:"min-w-0 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"})]})]}):f==="date"?e.jsx(jc,{value:s.value,operator:s.operator,onChange:I=>u(r,s.id,{value:I}),className:"min-w-0 flex-1"}):e.jsx(t.Input,{size:"xs",value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:I=>i(r,s.id,"value",I.target.value),className:"min-w-0 flex-1",placeholder:D?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"xs","aria-label":"Remove condition",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(r,s.id),children:e.jsx(le.X,{className:"h-3.5 w-3.5"})})]})}function _a({onAddCondition:s,onAddGroup:n}){return e.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[e.jsxs(t.Button,{type:"button",size:"xs",variant:"outline",className:"gap-1.5",onClick:s,children:[e.jsx(a.Plus,{className:"h-3 w-3"}),"Add condition"]}),n&&e.jsxs(t.Button,{type:"button",size:"xs",variant:"ghost",className:"gap-1.5 text-muted-foreground hover:text-foreground",onClick:n,children:[e.jsx(a.Plus,{className:"h-3 w-3"}),"Add group"]})]})}function Ec({group:s,depth:n,parentGroupId:r,onUpdateGroupOperator:o,onUpdateGroupNegate:i,onRemoveGroup:d,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:u,onReorderConditions:x,onReorderGroups:m,onAddCondition:b,onAddGroup:h,availableFields:p,renderFilterGroup:j,updateConditionFields:N}){const{attributes:f,listeners:g,setNodeRef:D,transform:I,transition:w,isDragging:S}=a.useSortable({id:s.id}),M={transform:a.CSS.Transform.toString(I),transition:w},A=E=>{const{active:C,over:T}=E;if(T&&C.id!==T.id){const L=s.conditions.findIndex(R=>R.id===C.id),k=s.conditions.findIndex(R=>R.id===T.id);L!==-1&&k!==-1&&x(s.id,L,k)}},F=E=>{const{active:C,over:T}=E;if(T&&C.id!==T.id&&r){const L=s.groups.findIndex(R=>R.id===C.id),k=s.groups.findIndex(R=>R.id===T.id);L!==-1&&k!==-1&&m(r,L,k)}};return e.jsxs("div",{ref:D,style:M,className:t.cn(n>0&&"mt-2 overflow-hidden rounded-[6px] border border-border/60",S&&"z-50 opacity-50"),children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-2 py-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",...f,...g,"aria-label":"Drag to reorder group",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:e.jsx(a.GripVertical,{className:"h-3.5 w-3.5"})}),e.jsx(t.Button,{type:"button",variant:s.negate?"default":"outline",size:"xs","aria-pressed":s.negate,className:"px-2",onClick:()=>i(s.id,!s.negate),children:"NOT"}),e.jsx(Ba,{value:s.logicalOperator,onValueChange:E=>o(s.id,E),"aria-label":"Group logical operator"}),e.jsx("span",{className:Ys,children:"Group"})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"xs","aria-label":"Remove group",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>r&&d(r,s.id),children:e.jsx(a.Trash2,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:t.cn(n>0&&"p-2"),children:[e.jsx(a.DndContext,{sensors:a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),collisionDetection:a.closestCenter,onDragEnd:A,children:e.jsx(a.SortableContext,{items:s.conditions.map(E=>E.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-0.5",children:s.conditions.map((E,C)=>e.jsx(Va,{condition:E,index:C,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:l,onRemoveCondition:u,onUpdateGroupOperator:o,availableFields:p,updateConditionFields:N},E.id))})})}),e.jsx(a.DndContext,{sensors:a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),collisionDetection:a.closestCenter,onDragEnd:F,children:e.jsx(a.SortableContext,{items:s.groups.map(E=>E.id),strategy:a.verticalListSortingStrategy,children:s.groups.map(E=>j(E,n+1,s.id))})}),s.conditions.length===0&&s.groups.length===0&&e.jsx("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No conditions in this group."}),e.jsx(_a,{onAddCondition:()=>b(s.id),onAddGroup:()=>h(s.id)})]})]})}function Ic({filters:s,availableFields:n,onSave:r,onClearAll:o,onCancel:i}){const{currentFilters:d,availableFields:c,isLoading:l,addCondition:u,addGroup:x,removeCondition:m,removeGroup:b,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:N,reorderConditions:f,reorderGroups:g,generateSQLPreview:D,hasAnyFilters:I,setCurrentFilters:w}=hc({initialFilters:s,availableFields:n}),S=a.useSensors(a.useSensor(a.PointerSensor),a.useSensor(a.KeyboardSensor,{coordinateGetter:a.sortableKeyboardCoordinates})),[M,A]=v.useState(!1),F=(T,L,k)=>{const R=y=>y.id===T?{...y,conditions:y.conditions.map(_=>_.id===L?{..._,field:k,dataType:k.dataType}:_)}:{...y,groups:y.groups.map(R)};w(R(d))},E=(T,L=0,k)=>{if(L===0){const R=T.conditions.length===0&&T.groups.length===0;return e.jsxs("div",{children:[e.jsx(a.DndContext,{sensors:S,collisionDetection:a.closestCenter,onDragEnd:y=>{const{active:_,over:O}=y;if(O&&_.id!==O.id){const P=T.conditions.findIndex(Y=>Y.id===_.id),B=T.conditions.findIndex(Y=>Y.id===O.id);P!==-1&&B!==-1&&f(T.id,P,B)}},children:e.jsx(a.SortableContext,{items:T.conditions.map(y=>y.id),strategy:a.verticalListSortingStrategy,children:e.jsx("div",{className:"space-y-0.5",children:T.conditions.map((y,_)=>e.jsx(Va,{condition:y,index:_,groupId:T.id,groupLogicalOperator:T.logicalOperator,onUpdateCondition:h,onUpdateField:F,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:p},y.id))})})}),e.jsx(a.DndContext,{sensors:S,collisionDetection:a.closestCenter,onDragEnd:y=>{const{active:_,over:O}=y;if(O&&_.id!==O.id){const P=T.groups.findIndex(Y=>Y.id===_.id),B=T.groups.findIndex(Y=>Y.id===O.id);P!==-1&&B!==-1&&g(T.id,P,B)}},children:e.jsx(a.SortableContext,{items:T.groups.map(y=>y.id),strategy:a.verticalListSortingStrategy,children:T.groups.map(y=>E(y,L+1,T.id))})}),R&&e.jsx("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No filters yet. Add a condition to limit the rows this card shows."}),e.jsx(_a,{onAddCondition:()=>u(T.id),onAddGroup:M?()=>x(T.id):void 0})]},T.id)}return e.jsx(Ec,{group:T,depth:L,parentGroupId:k,onUpdateGroupOperator:j,onUpdateGroupNegate:N,onRemoveGroup:b,onUpdateCondition:h,onUpdateField:F,onRemoveCondition:m,onReorderConditions:f,onReorderGroups:g,onAddCondition:u,onAddGroup:x,availableFields:c,renderFilterGroup:E,updateConditionFields:p},T.id)},C=a.getFilterCount(s);return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:[l?e.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-[12px] text-muted-foreground",children:[e.jsx(t.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Loading columns…"]}):E(d),e.jsxs("div",{className:"mt-3 flex items-center gap-2 border-t border-border/60 pt-3",children:[e.jsx(t.Switch,{size:"xs",id:"advanced-mode",checked:M,onCheckedChange:T=>A(T)}),e.jsx(t.Label,{htmlFor:"advanced-mode",className:"text-[12px] font-normal leading-none text-foreground",children:"Advanced mode"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Nest conditions in groups"})]}),I&&e.jsxs("div",{className:"mt-3 border-t border-border/60 pt-3",children:[e.jsx("div",{className:t.cn("mb-1.5",Ys),children:"Where clause"}),e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words rounded-[6px] border border-border bg-muted/40 px-3 py-2 font-mono text-[12px] leading-[1.55] text-foreground",children:D(d)})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-3 py-2.5",children:[e.jsx("div",{children:C>0&&e.jsx(t.Button,{size:"xs",variant:"ghost",className:"text-muted-foreground hover:text-foreground",onClick:o,children:"Clear all"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(t.Button,{size:"xs",variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(t.Button,{size:"xs",onClick:()=>r(I?d:null),children:"Apply filters"})]})]})]})}function Dc({cardId:s,filters:n,onFiltersChange:r,onClearFilters:o,availableFields:i,isOpen:d,onOpenChange:c}){const l=x=>{r(s,x),c(!1)},u=()=>{o(s),c(!1)};return e.jsxs(a.Dialog,{modal:!1,open:d,onOpenChange:c,children:[d&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-zinc-950/40 backdrop-blur-sm"}),e.jsxs(a.DialogContent,{className:"flex max-h-[80vh] w-[min(880px,92vw)] max-w-none flex-col gap-0 overflow-hidden p-0 [&>button:last-child]:top-3",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border pl-3 pr-10",children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx(a.DialogTitle,{className:"truncate text-[13px] font-medium",children:"Card filters"}),e.jsx(a.DialogDescription,{className:"sr-only",children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Ic,{filters:n,availableFields:i,onSave:l,onCancel:()=>c(!1),onClearAll:u})]})]})}function kc({activeCardId:s,sourceFields:n,getFieldsForContainer:r,setFieldsForContainer:o,moveField:i}){const[d,c]=v.useState(null),l=t.useEditorStore(f=>f.card),u=t.useEditorStore(f=>f.actions.updateCardConfig),x=t.useEditorStore(f=>f.actions.setCardPreferences),m=a.useFieldAvailabilityContext(l),b=[...n,...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],h=v.useCallback(f=>f.startsWith("card-source-")?"source":f.startsWith("card-")?null:f.startsWith("source-")||n.find(g=>g.id===f)?"source":r("groupBy").find(g=>g.id===f)?"groupBy":r("metrics").find(g=>g.id===f)?"metrics":r("pivotBy").find(g=>g.id===f)?"pivotBy":r("sortBy").find(g=>g.id===f)?"sortBy":r("detailColumns").find(g=>g.id===f)?"detailColumns":null,[n,r]),p=v.useCallback(f=>{c(f.active.id)},[]),j=v.useCallback(f=>{const{active:g,over:D}=f;if(!D||!s){c(null);return}const I=g.id,w=D.id,S=h(I),M=h(w)||w;if(I===w){c(null);return}const A=S==="source"?n.find(F=>F.id===I):S?r(S).find(F=>F.id===I):void 0;if(A&&S&&(i!=null&&i({field:A,from:S,to:M,...w!==M?{beforeId:w}:{}}))){c(null);return}if(M==="sortBy"){if(S==="source"){const F=n.find(C=>C.id===I);if(!F){c(null);return}if(!(r("groupBy").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName)||r("metrics").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName)||r("detailColumns").some(C=>C.name===F.name&&C.qualifiedEntityName===F.qualifiedEntityName))){c(null);return}}else if(S==="pivotBy"){c(null);return}else if(S!=="groupBy"&&S!=="metrics"&&S!=="sortBy"&&S!=="detailColumns"){c(null);return}}if(S==="source"&&M==="sortBy"){const F=[...n].find(L=>L.id===I);if(!F){c(null);return}const E=r("sortBy");if(a.fieldAlreadyExists(F,E)){c(null);return}const C=a.validateFieldForChartType(F,"sortBy",l.type);if(!C.isValid){t.ue.error("Invalid Field Type",{description:C.reason,position:"top-center",duration:3e3}),c(null);return}const T=a.getNewField(F,"sortBy",E);c(null),o("sortBy",[...E,T]);return}if(S==="source"&&M!=="source"&&M!=="sortBy"){const F=[...n].find(y=>y.id===I);if(!F){c(null);return}const E=[...r("groupBy"),...r("pivotBy"),...r("metrics"),...r("sortBy"),...r("detailColumns")],C=a.validateEntityConsistency(F,E,m);if(!C.isValid){C.showError&&a.showJoinRequiredNotification(C.fieldState),c(null);return}const T=r(M);if(a.fieldAlreadyExists(F,T)){c(null);return}const L=a.validateFieldForChartType(F,M,l.type);if(!L.isValid){t.ue.error("Invalid Field Type",{description:L.reason,position:"top-center",duration:3e3}),c(null);return}const k=a.getNewField(F,M,T),R=[...T,k];if(c(null),o(M,R),M==="metrics"&&s){const y=a.seedSemanticMetricFormatDefaults(l,k,l.preferences);y&&x(y),a.cleanupKpiMetricComparisonMode(l.type,l.config,u,s,R)}return}if(S&&M&&S!=="source"&&M!=="source"&&S!==M){const F=r(S),E=r(M),C=F.find(y=>y.id===I);if(!C){c(null);return}const T=a.validateFieldForChartType(C,M,l.type);if(!T.isValid){t.ue.error("Invalid Field Type",{description:T.reason,position:"top-center",duration:3e3}),c(null);return}const L=a.getNewField(C,M,E);if(c(null),M==="sortBy"){a.fieldAlreadyExists(C,E)||o(M,[...E,L]);return}const k=F.filter(y=>y.id!==I),R=[...E,L];if(o(S,k),o(M,R),M==="metrics"&&s){const y=a.seedSemanticMetricFormatDefaults(l,L,l.preferences);y&&x(y),a.cleanupKpiMetricComparisonMode(l.type,l.config,u,s,R)}return}if(S&&M&&S===M&&S!=="source"){const F=r(S),E=F.findIndex(T=>T.id===I),C=F.findIndex(T=>T.id===w);if(E!==C){const T=a.arrayMove(F,E,C);o(S,T)}}c(null)},[s,n,r,o,i,h,m,l,u,x]),N=d?b.find(f=>f.id===d):null;return{activeId:d,activeField:N,handleDragStart:p,handleDragEnd:j}}function Mc({activeView:s,onViewChange:n,splitViewEnabled:r,hasQueryError:o=!1}){const i=t.useEditorStore(x=>x.card),{config:d}=v.useContext(a.SemaphorContext).tokenProps,c=(d==null?void 0:d.showInfoTab)!==!1,l=()=>r?!1:t.getVisualizationMode(i)==="dynamic"?!0:!["table","pivotTable","aggregateTable","detailTable"].includes(i.type),u=[{id:"chart",label:"Chart"}];return l()&&u.push({id:"table",label:"Results"}),c&&u.push({id:"info",label:o?"Error":"Info",isError:o}),e.jsx(t.Tabs,{value:s,onValueChange:x=>n(x),children:e.jsx(t.TabsList,{variant:"underline",className:"gap-5 border-b-0",children:u.map(x=>e.jsx(t.TabsTrigger,{value:x.id,className:t.cn("px-0 text-[13px]",x.isError&&"text-destructive hover:text-destructive focus-visible:text-destructive data-[state=active]:border-destructive data-[state=active]:text-destructive"),children:x.label},x.id))})})}const Ac=[{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 Lc(){var u,x;const s=t.useEditorStore(m=>m.card),{updateRowLimit:n}=t.useEditorActions(),[r,o]=v.useState(!1),[i,d]=v.useState(""),c=m=>{if(m==="custom"){o(!0);return}o(!1),n(s.id,parseInt(m))},l=m=>{const b=m.target.value;d(b),b&&!isNaN(parseInt(b))&&n(s.id,parseInt(b))};return e.jsx("div",{className:"flex items-center gap-2",children:r?e.jsx(t.Input,{type:"number",value:i,onChange:l,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(u=s.config)==null?void 0:u.rowLimit)==null?void 0:x.toString())||"100",onValueChange:c,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(a.Filter,{className:"h-3 w-3",strokeWidth:1.75}),e.jsx(t.SelectValue,{placeholder:"Select limit"})]}),e.jsx(t.SelectContent,{children:Ac.map(m=>e.jsx(t.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function Fc({card:s,queryData:n,isLoading:r,isFetching:o,pagination:i,onPaginationChange:d,onSortChange:c,sortState:l,splitViewEnabled:u,isDynamicInspectorOpen:x,onDynamicInspectorOpenChange:m}){var j,N;const b=v.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]),h=t.getVisualizationMode(s)==="dynamic",p=e.jsx(It,{alwaysRenderOverride:!0,renderCardOverride:()=>e.jsx(Na,{fallbackPreview:e.jsx(It,{}),records:b,title:s.title,isInspectorOpen:x,onInspectorOpenChange:m})});return h?u?e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(a.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:p}),e.jsx(a.ResizableHandle,{withHandle:!0}),e.jsx(a.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)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(a.TableVisual,{card:s,data:b,resultColumns:n==null?void 0:n.columns,columnKeyMap:n==null?void 0:n.columnKeyMap,totalsByColumnId:n==null?void 0:n.tableTotalsByColumnId,comparisonMetadata:(j=n==null?void 0:n.metadata)==null?void 0:j.comparisonMetadata,paginationMetadata:i,onPaginationChange:d,isLoading:r||o,onSortChange:c,sortState:l})]})})]}):p:!u||["table","pivotTable","aggregateTable","detailTable"].includes(s.type)?e.jsx(It,{}):e.jsxs(a.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(a.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(It,{})}),e.jsx(a.ResizableHandle,{withHandle:!0}),e.jsx(a.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)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(a.TableVisual,{card:s,data:b,resultColumns:n==null?void 0:n.columns,columnKeyMap:n==null?void 0:n.columnKeyMap,totalsByColumnId:n==null?void 0:n.tableTotalsByColumnId,comparisonMetadata:(N=n==null?void 0:n.metadata)==null?void 0:N.comparisonMetadata,paginationMetadata:i,onPaginationChange:d,isLoading:r||o,onSortChange:c,sortState:l})]})})]})}function Rc(s,n){const[r,o]=v.useState(()=>{const i=localStorage.getItem(s);return i?JSON.parse(i):n});return v.useEffect(()=>{localStorage.setItem(s,JSON.stringify(r))},[r,s]),[r,o]}const Pc="semaphor-split-view-enabled";function Oc(){return Rc(Pc,!0)}function Bc({showInfoTab:s}){return e.jsx(a.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 Vc({card:s,effectiveCardType:n=s.type,queryResultColumns:r}){return a.supportsRegularTableSettings(n)?e.jsxs(a.Sheet,{modal:!1,children:[e.jsx(a.SheetTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"Table settings",className:"h-7 w-7 rounded-[5px] p-0",buttonProps:{type:"button","aria-label":"Table settings"},children:e.jsx(a.Settings2,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),e.jsxs(a.SheetContent,{side:"right",hideOverlay:!0,className:"flex w-[420px] flex-col gap-0 p-0 sm:max-w-[420px]",children:[e.jsx(a.SheetTitle,{className:"sr-only",children:"Table settings"}),e.jsx(a.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(Aa,{cardType:n,queryResultColumns:r,focusSection:"style"})})]})]}):null}function _c({className:s,visible:n}){const r=t.useDashboardStore(l=>l.selectedFrameId),o=a.useManagementStore(l=>l.selectedVisual),i=t.useEditorStore(l=>l.frame),c=!!!(i!=null&&i.visualId||o!=null&&o.id)&&!!r;return!n||c?null:e.jsx("div",{className:t.cn("flex",s),children:e.jsx(jt.VisualBadge,{showLabel:!0,className:"h-6 w-fit px-2 py-0.5 text-[11px]"})})}function Yc({activeView:s,onViewChange:n,onFiltersClick:r,activeCard:o,columns:i}){var Me;const d=t.useEditorStore(ae=>ae.card),c=t.useEditorStore(ae=>ae.editorContext),l=t.useEditorStore(ae=>ae.inlineFilterValuesMap[(o==null?void 0:o.id)||""]),u=t.useEditorStore(ae=>ae.actions.removeCardInlineFilterValue),x=t.useDashboardStore(ae=>ae.filterValues),m=t.useDashboardStore(ae=>ae.selectedSheetId),{updateCardConfig:b,setCard:h,updateCardInFrame:p,setShowAIDialog:j}=t.useEditorActions(),N=t.useEditorStore(ae=>ae.showAIDialog),f=t.useEditorStore(ae=>ae.isDevMode),g=t.useDashboardStore(ae=>ae.isVisualEditing),[D,I]=v.useState(!1),[w,S]=v.useState(!1),[M,A]=v.useState(!1),[F,E]=v.useState(null),{config:C}=v.useContext(a.SemaphorContext).tokenProps,T=(C==null?void 0:C.showInfoTab)!==!1,L=(C==null?void 0:C.showQueryDebugTools)!==!1,[k,R]=Oc();t.useEditorStore(ae=>{var K;return!!((K=ae.card.customCardPreferences)!=null&&K.url)});const _=t.getVisualizationMode(d)==="dynamic",O=(c==null?void 0:c.type)==="documentSection",P=a.useEffectiveEditorCardType(),{data:B,errorMessage:Y,isLoading:q,isFetching:z,errorSql:V,pagination:$,refetch:Q,comparisonMetadata:U,queryRequestPayload:J,resolvedPrimaryDateField:W}=a.useEditorCardQuery(o),ee=v.useMemo(()=>(B==null?void 0:B.records)||[],[B==null?void 0:B.records]),ue=v.useMemo(()=>!z&&ee.length>0?Object.keys(ee[0]):[],[z,ee]),[fe,be]=v.useState(!1),ge=a.useMatrixEditorRefresh(o),Pe=t.useEditorStore(ae=>ae.frame),[Oe,ke]=v.useState();v.useEffect(()=>{z||be(!1)},[z]);const Te=()=>{const ae=!k;ae&&s==="table"&&n("chart"),R(ae)},_e=(ae,K)=>{const ie={...o,paginationConfig:{page:ae+1,pageSize:K}};h(ie),p(ie)},ze=ae=>{if(!d.config)return;const K=a.sortStateToSortByColumns(ae,d.config.metricColumns,d.config.groupByColumns,d.config.detailColumns);b(d.id,{...d.config,sortByColumns:K})},Be=v.useMemo(()=>{var ae;return a.sortByColumnsToSortState((ae=d.config)==null?void 0:ae.sortByColumns)},[(Me=d.config)==null?void 0:Me.sortByColumns]),Ae=a.getFilterCount(je.getAuthoredCardFilters(o)||null);return e.jsx("div",{className:t.cn("relative flex w-0 grow flex-col",{"border-l":N&&g}),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"&&N&&!O&&!_&&e.jsx("div",{className:"w-[200px]",children:e.jsx(Bo,{variant:f?"secondary":"ghost"})}),e.jsxs("div",{className:"flex h-11 items-end gap-5 self-stretch",children:[e.jsx(Mc,{activeView:s,onViewChange:n,splitViewEnabled:k,hasQueryError:!!Y}),!a.isTableType(P)&&e.jsx(Lc,{})]}),P==="kpi"&&e.jsx(_c,{visible:!0,className:"self-center"}),U&&d.type!=="table"&&e.jsx(a.ComparisonMetadataBadge,{metadata:U,variant:"compact"}),N&&e.jsx(jt.EditorClearButton,{})]}),e.jsxs("div",{className:"flex grow items-center justify-end gap-1",children:[e.jsx(a.FilterInfo,{cardId:o.id,cardFilters:je.getAuthoredCardFilters(o),cardFilterCount:Ae,onFiltersClick:r,inlineFilters:o.inlineFilters,inlineFilterValues:l,sheetId:m||"",removeInlineFilterValue:ae=>u(o.id,ae),resolvedPrimaryDateField:W}),s==="chart"&&e.jsx(Vc,{card:o,effectiveCardType:P,queryResultColumns:ue}),s==="chart"&&!_&&e.jsx(Ca,{showInlineFilters:!1,showControls:!1,showDisplayOptions:!1}),e.jsx(a.IconButton,{tooltip:"Refresh",className:"h-7 w-7 rounded-[5px] p-0",disabled:q||z,onClick:()=>{var ae;if(ge){(ae=ge.refresh)==null||ae.call(ge);return}be(!0),Q()},children:e.jsx(Ts,{className:t.cn("h-3.5 w-3.5",{"animate-spin":(ge==null?void 0:ge.isFetching)??fe})})}),s==="chart"&&e.jsxs(a.DropdownMenu,{modal:!1,children:[e.jsx(a.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.IconButton,{tooltip:"More Options",className:"h-7 w-7 rounded-[5px] p-0","aria-label":"More options",children:e.jsx(a.EllipsisVertical,{className:"h-3.5 w-3.5"})})}),e.jsxs(a.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsxs(a.DropdownMenuItem,{onSelect:r,children:[e.jsx(a.Filter,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Card filters",Ae>0&&e.jsx("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:Ae})]}),e.jsx(Rs,{triggerVariant:"menu",className:"w-full"}),e.jsx(Ps,{triggerVariant:"menu",className:"w-full"}),e.jsx(Fs,{triggerVariant:"menu",className:"w-full"}),e.jsxs(a.DropdownMenuItem,{onClick:Te,children:[k?e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Fr,{className:"h-3.5 w-3.5 text-muted-foreground"}),k?"Hide results table":"Show results table"]}),ge&&e.jsxs(a.DropdownMenuItem,{disabled:ge.isFetching||!ge.hasDelivery,title:ge.hasDelivery?void 0:"Available once the preview has loaded.",onClick:()=>ke(ge.readDelivery()),children:[e.jsx(a.Download,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Download"]}),e.jsx(Sa,{onCustomize:()=>A(!0)})]})]})]})]}),e.jsxs("div",{className:"flex min-h-0 grow flex-col",children:[s==="chart"?Y?e.jsx(Bc,{showInfoTab:T}):e.jsx("div",{className:"flex grow flex-col",children:e.jsx(Fc,{card:o,queryData:B,isLoading:q,isFetching:z,pagination:$,onPaginationChange:_e,onSortChange:ze,sortState:Be,splitViewEnabled:k,isDynamicInspectorOpen:M,onDynamicInspectorOpenChange:A})}):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:[(q||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(a.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(a.TableVisual,{card:o,data:ee,resultColumns:B.columns,columnKeyMap:B.columnKeyMap,totalsByColumnId:B==null?void 0:B.tableTotalsByColumnId,comparisonMetadata:U,paginationMetadata:$,onPaginationChange:_e,isLoading:q||z,onSortChange:ze,sortState:Be})]}),s==="info"&&T&&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:V,showCardDetails:!0,defaultSqlExpanded:!0,debugPayloads:L?{queryRequest:J,queryResponse:B,columns:i,dashboardFilters:x}:void 0,onSendFeedback:()=>{const ae=a.prepareFeedbackData(a.FeedbackCategory.QUERY_GENERATION,{cardConfig:d.config,dataSource:o.dataSource,dashboardFilters:x,errorMessage:Y,errorSql:V,generatedSql:B==null?void 0:B.sql});E(ae),S(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const ae=t.useEditorStore.getState().actions;ae.setIsDevMode(!0),ae.setCardSql(V||""),setTimeout(()=>{ae.setRunSql(!0)},100)},100)}}):(B==null?void 0:B.sql)&&e.jsx(wa,{sql:B.sql,showCardDetails:!0,debugPayloads:L?{queryRequest:J,queryResponse:B,columns:i,dashboardFilters:x}:void 0})})})]}),Oe&&o&&Pe&&e.jsx(a.ExportDialog,{isOpen:!0,onClose:()=>ke(void 0),card:o,frame:Pe,matrix:Oe}),F&&e.jsx(a.FeedbackDialog,{open:w,onOpenChange:S,feedbackData:F})]})})}function zc({activeField:s}){const[n,r]=v.useState(!0);if(v.useEffect(()=>{s&&r(!0)},[s]),!s)return null;const o=a.getCalculatedGlyphKind(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 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(a.TypeGlyph,{dataType:s.dataType,calculated:o}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap",children:s.label||s.name})]})}const qc=()=>{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 n=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 i;if((i=o.reason)!=null&&i.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",n,!0),window.addEventListener("unhandledrejection",r,!0),()=>{console.error=s,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",r,!0)}};function $c({column:s,isSelected:n,onSelect:r,availableFields:o,width:i,onWidthChange:d}){var B,Y;const c=t.useEditorStore(q=>q.card),{updateCardConfig:l,removeGroupByColumn:u,removeMetricColumn:x,updateFilters:m}=t.useEditorActions(),[b,h]=v.useState(!1),[p,j]=v.useState(!1),N=v.useRef(null),f=v.useCallback(q=>{q.preventDefault(),q.stopPropagation(),j(!0),N.current={startX:q.clientX,startWidth:i||150};const z=$=>{if(!N.current)return;const Q=$.clientX-N.current.startX,U=Math.max(80,N.current.startWidth+Q);d==null||d(s.id,U)},V=()=>{j(!1),N.current=null,document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",V)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",V)},[i,s.id,d]),g=je.getAuthoredCardFilters(c),D=(B=g==null?void 0:g.conditions)==null?void 0:B.some(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName),I=q=>{q?m(c.id,q):l(c.id,{filters:void 0})},{attributes:w,listeners:S,setNodeRef:M,transform:A,transition:F,isDragging:E}=a.useSortable({id:s.id}),C={transform:a.CSS.Transform.toString(A),transition:F},T=t.getDataType(s.dataType),L=Kc(T),k=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.sortByColumns)||[],z=q.findIndex($=>$.name===s.name);if(z!==-1){const $=[...q];$[z]={...$[z],direction:"asc"},l(c.id,{sortByColumns:$})}else l(c.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"asc"}]})},R=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.sortByColumns)||[],z=q.findIndex($=>$.name===s.name);if(z!==-1){const $=[...q];$[z]={...$[z],direction:"desc"},l(c.id,{sortByColumns:$})}else l(c.id,{sortByColumns:[...q,{...s,id:`sort-${s.id}`,role:"sortby",direction:"desc"}]})},y=()=>{var V;const q=((V=c==null?void 0:c.config)==null?void 0:V.groupByColumns)||[];if(!q.some($=>$.name===s.name)){const $={...s,id:`groupby-${s.id}-${Date.now()}`,role:"groupby"};l(c.id,{groupByColumns:[...q,$]})}},_=q=>{var $;const z=(($=c==null?void 0:c.config)==null?void 0:$.metricColumns)||[];if(!z.some(Q=>Q.name===s.name&&Q.aggregate===q)){const Q={...s,id:`metric-${s.id}-${q}-${Date.now()}`,label:`${q} of ${s.label||s.name}`,role:"metric",aggregate:q,aggregateOrigin:"explicit"};l(c.id,{metricColumns:[...z,Q]})}},O=()=>{s.role==="groupby"?u(c.id,s.id):s.role==="metric"&&x(c.id,s.id)},P={...C,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:M,style:P,className:t.cn("group relative border-r border-border bg-background px-1 py-0",E&&"opacity-50",n&&"bg-primary/10",p&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...w,...S,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(a.GripVertical,{className:"h-3 w-3"})}),e.jsxs(a.DropdownMenu,{children:[e.jsx(a.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",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(L,{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,")"]}),D&&e.jsx(a.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(le.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(a.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(a.DropdownMenuItem,{onClick:()=>h(!0),children:[e.jsx(a.Filter,{className:t.cn("mr-2 h-4 w-4",D&&"text-primary")}),D?"Edit Filter":"Filter"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{onClick:k,children:[e.jsx(gr,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(a.DropdownMenuItem,{onClick:R,children:[e.jsx(fr,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuSub,{children:[e.jsxs(a.DropdownMenuSubTrigger,{children:[e.jsx(a.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(a.DropdownMenuSubContent,{children:[e.jsx(a.DropdownMenuItem,{onClick:()=>_("SUM"),children:"Sum"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("AVG"),children:"Average"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("COUNT"),children:"Count"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("DISTINCT"),children:"Count Distinct"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("MIN"),children:"Min"}),e.jsx(a.DropdownMenuItem,{onClick:()=>_("MAX"),children:"Max"})]})]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{onClick:y,children:[e.jsx(a.Rows3,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(a.DropdownMenuItem,{disabled:!0,children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(a.DropdownMenuSeparator,{}),e.jsxs(a.DropdownMenuItem,{disabled:!0,children:[e.jsx(a.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(a.DropdownMenuItem,{onClick:O,className:"text-destructive focus:text-destructive",children:[e.jsx(a.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:f,className:t.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",p&&"bg-primary")}),e.jsx(Ra,{open:b,onOpenChange:h,availableFields:o.length>0?o:[s],existingFilters:g,editingCondition:D?(Y=g==null?void 0:g.conditions)==null?void 0:Y.find(q=>q.field.name===s.name&&q.field.qualifiedEntityName===s.qualifiedEntityName):void 0,onSave:I})]})}function Kc(s){switch(s){case"number":return a.Hash;case"date":return a.Calendar;case"string":default:return t.Type}}function Uc({selectedColumn:s,onColumnSelect:n,isLoading:r=!1,sourceFields:o=[],filterableFields:i=o}){var E,C,T,L;const d=t.useEditorStore(k=>k.card),{updateCardConfig:c}=t.useEditorActions(),[l,u]=v.useState(null),[x,m]=v.useState({}),[b,h]=v.useState(!1),p=v.useMemo(()=>{var y,_;const k=((y=d==null?void 0:d.config)==null?void 0:y.groupByColumns)||[],R=((_=d==null?void 0:d.config)==null?void 0:_.metricColumns)||[];return[...k,...R]},[(E=d==null?void 0:d.config)==null?void 0:E.groupByColumns,(C=d==null?void 0:d.config)==null?void 0:C.metricColumns]),j=v.useMemo(()=>{const k=new Set(p.map(R=>`${R.qualifiedEntityName}.${R.name}`));return o.filter(R=>!k.has(`${R.qualifiedEntityName}.${R.name}`))},[o,p]),{data:N,isLoading:f}=a.useEditorCardQuery(d),g=(N==null?void 0:N.records)||[],D=v.useCallback((k,R)=>{m(y=>({...y,[k]:R}))},[]),I=v.useCallback(k=>{var O,P;const R=t.getDataType(k.dataType),y=((O=d==null?void 0:d.config)==null?void 0:O.groupByColumns)||[],_=((P=d==null?void 0:d.config)==null?void 0:P.metricColumns)||[];if(R==="number"){const B=a.getNewField(k,"metrics",[...y,..._]);c(d.id,{metricColumns:[..._,B]})}else{const B=a.getNewField(k,"groupBy",[...y,..._]);c(d.id,{groupByColumns:[...y,B]})}h(!1)},[(T=d==null?void 0:d.config)==null?void 0:T.groupByColumns,(L=d==null?void 0:d.config)==null?void 0:L.metricColumns,d.id,c]),w=a.useSensors(a.useSensor(a.PointerSensor,{activationConstraint:{distance:8}})),S=k=>{u(k.active.id)},M=k=>{const{active:R,over:y}=k;if(u(null),!y||R.id===y.id)return;const _=p.findIndex(P=>P.id===R.id),O=p.findIndex(P=>P.id===y.id);if(_!==-1&&O!==-1){const P=a.arrayMove(p,_,O),B=P.filter(q=>q.role==="groupby"),Y=P.filter(q=>q.role==="metric");c(d.id,{groupByColumns:B,metricColumns:Y})}},A=l?p.find(k=>k.id===l):null,F=k=>{let R="";for(;k>=0;)R=String.fromCharCode(k%26+65)+R,k=Math.floor(k/26)-1;return R};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"})}):p.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(a.DndContext,{sensors:w,collisionDetection:a.closestCenter,onDragStart:S,onDragEnd:M,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(a.SortableContext,{items:p.map(k=>k.id),strategy:a.horizontalListSortingStrategy,children:p.map((k,R)=>e.jsx("th",{style:{width:x[k.id]?`${x[k.id]}px`:void 0,minWidth:x[k.id]?`${x[k.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:F(R)},`letter-${k.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(a.SortableContext,{items:p.map(k=>k.id),strategy:a.horizontalListSortingStrategy,children:p.map(k=>e.jsx($c,{column:k,isSelected:(s==null?void 0:s.id)===k.id,onSelect:()=>n(k),availableFields:i,width:x[k.id],onWidthChange:D},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(t.Popover,{open:b,onOpenChange:h,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(a.Plus,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search columns..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No columns available."}),e.jsx(a.CommandGroup,{heading:"Available Columns",children:j.map(k=>{const R=t.getDataType(k.dataType),y=R==="number"?a.Hash:R==="date"?a.Calendar:t.Type;return e.jsxs(a.CommandItem,{value:k.label||k.name,onSelect:()=>I(k),children:[e.jsx(y,{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:k.label||k.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.entityName})]})]},k.id)})})]})]})})]})})]})]}),e.jsx("tbody",{children:f?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center",children:e.jsx(t.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):g.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:p.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):g.slice(0,100).map((k,R)=>e.jsxs("tr",{className:t.cn("border-b border-border transition-colors hover:bg-muted/50",R%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:R+1}),p.map(y=>{const _=k[y.name]??k[y.label??""];return e.jsx("td",{style:{width:x[y.id]?`${x[y.id]}px`:void 0,minWidth:x[y.id]?`${x[y.id]}px`:"120px"},className:t.cn("border-r border-border px-3 py-2 text-sm",(s==null?void 0:s.id)===y.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Gc(_,y)})},`${R}-${y.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},R))})]}),e.jsx(a.DragOverlay,{children:A&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:A.label||A.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(g.length,100)," of ",g.length," rows"]}),e.jsxs("span",{children:[p.length," columns"]})]})]})}function Gc(s,n){if(s==null)return"—";if(typeof s=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(s):s.toString();if(s instanceof Date||typeof s=="string"&&!isNaN(Date.parse(s))){const r=new Date(s);if(!isNaN(r.getTime()))return r.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(s)}function Hc({entityGroups:s,isLoading:n=!1}){var I,w;const r=t.useEditorStore(S=>S.card),{updateCardConfig:o,removeGroupByColumn:i,removeMetricColumn:d}=t.useEditorActions(),[c,l]=v.useState(!0),[u,x]=v.useState(""),[m,b]=v.useState(new Set),h=((I=r==null?void 0:r.config)==null?void 0:I.groupByColumns)||[],p=((w=r==null?void 0:r.config)==null?void 0:w.metricColumns)||[],j=S=>{const M=new Set(m);M.has(S)?M.delete(S):M.add(S),b(M)},N=S=>h.some(M=>M.name===S.name&&M.qualifiedEntityName===S.qualifiedEntityName)||p.some(M=>M.name===S.name&&M.qualifiedEntityName===S.qualifiedEntityName),f=(S,M)=>{if(M)if(t.getDataType(S.dataType)==="number"){const F=a.getNewField(S,"metrics",[...h,...p]);o(r.id,{metricColumns:[...p,F]})}else{const F=a.getNewField(S,"groupBy",[...h,...p]);o(r.id,{groupByColumns:[...h,F]})}else{const A=h.findIndex(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName),F=p.findIndex(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName);A!==-1&&i(r.id,h[A].id),F!==-1&&d(r.id,p[F].id)}},g=S=>{if(!u)return S;const M=u.toLowerCase();return S.filter(A=>A.name.toLowerCase().includes(M)||A.label&&A.label.toLowerCase().includes(M))},D=S=>{switch(t.getDataType(S)){case"number":return a.Hash;case"date":return a.Calendar;default:return t.Type}};return c?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:()=>l(!1),title:"Close panel",children:e.jsx(Ir,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx($e.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:S=>x(S.target.value),className:"h-8 pl-8 text-sm"})]})}),(h.length>0||p.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[h.length>0&&e.jsxs(a.Collapsible,{defaultOpen:!0,children:[e.jsxs(a.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx($e.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(a.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:h.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:h.map(S=>{const M=D(S.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(a.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.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:()=>i(r.id,S.id),children:e.jsx(le.X,{className:"h-3 w-3"})})]},S.id)})})})]}),p.length>0&&e.jsxs(a.Collapsible,{defaultOpen:!0,children:[e.jsxs(a.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx($e.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(a.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:p.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:p.map(S=>{const M=D(S.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(a.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(M,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:S.label||S.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:S.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:()=>d(r.id,S.id),children:e.jsx(le.X,{className:"h-3 w-3"})})]},S.id)})})})]})]}),e.jsx(t.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):s.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):s.map(S=>{const M=g(S.columns);if(M.length===0)return null;const A=m.has(S.entityId)||u.length>0;return e.jsxs(a.Collapsible,{open:A,onOpenChange:()=>j(S.entityId),children:[e.jsxs(a.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($e.ChevronRight,{className:t.cn("h-3.5 w-3.5 transition-transform duration-200",A&&"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:S.label||S.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M.length})]}),e.jsx(a.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:M.map(F=>{const E=D(F.dataType),C=N(F);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",C&&"bg-primary/5"),children:[e.jsx(a.Checkbox,{checked:C,onCheckedChange:T=>f(F,T),className:"h-3.5 w-3.5"}),e.jsx(E,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:F.label||F.name})]},F.id)})})})]},S.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:()=>l(!0),title:"Open panel",children:e.jsx(Dr,{className:"h-4 w-4"})})})}const Qc=[{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 Jc({value:s,onChange:n,onSubmit:r,onCancel:o,selectedColumn:i,availableColumns:d}){const[c,l]=v.useState(!1),[u,x]=v.useState("column"),m=v.useRef(null);v.useEffect(()=>{const j=N=>{N.key==="Escape"&&s?o():N.key==="Enter"&&s&&!c&&r(s)};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[s,o,r,c]);const b=j=>{const N=`[${j.label||j.name}]`,f=m.current;if(f){const g=f.selectionStart||0,D=f.selectionEnd||0,I=s.slice(0,g)+N+s.slice(D);n(I),setTimeout(()=>{f.setSelectionRange(g+N.length,g+N.length),f.focus()},0)}else n(s+N);l(!1)},h=j=>{const N=m.current;if(N){const f=N.selectionStart||0,g=N.selectionEnd||0,D=s.slice(0,f)+j.syntax+s.slice(g);n(D),setTimeout(()=>{N.setSelectionRange(f+j.name.length+1,f+j.syntax.length-1),N.focus()},0)}else n(s+j.syntax);l(!1)},p=j=>{switch(t.getDataType(j)){case"number":return a.Hash;case"date":return a.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:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(t.Popover,{open:c&&u==="function",onOpenChange:j=>{l(j),j&&x("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(Lr,{className:"h-4 w-4"})})}),e.jsx(t.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search functions..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No functions found."}),e.jsx(a.CommandGroup,{heading:"Functions",children:Qc.map(j=>e.jsx(a.CommandItem,{value:j.name,onSelect:()=>h(j),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:j.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:j.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:j.syntax})]})},j.name))})]})]})})]}),e.jsxs(t.Popover,{open:c&&u==="column",onOpenChange:j=>{l(j),j&&x("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(le.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(t.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(a.Command,{children:[e.jsx(a.CommandInput,{placeholder:"Search columns..."}),e.jsxs(a.CommandList,{children:[e.jsx(a.CommandEmpty,{children:"No columns found."}),e.jsx(a.CommandGroup,{heading:"Available Columns",children:d.map(j=>{const N=p(j.dataType);return e.jsxs(a.CommandItem,{value:j.label||j.name,onSelect:()=>b(j),children:[e.jsx(N,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:j.label||j.name})]},j.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(t.Input,{ref:m,value:s,onChange:j=>n(j.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(le.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 Wc({className:s}){var p,j,N,f;const n=t.useEditorStore(g=>g.card),[r,o]=v.useState(null),[i,d]=v.useState(""),{columns:c=[],columnGroups:l=[],isLoading:u}=a.useColumns(),{valuePickFilterableFields:x=[]}=a.useFilterableFields();(p=n==null?void 0:n.config)!=null&&p.groupByColumns,(j=n==null?void 0:n.config)!=null&&j.metricColumns,(N=n==null?void 0:n.config)!=null&&N.groupByColumns,(f=n==null?void 0:n.config)!=null&&f.pivotByColumns;const m=g=>{o(g),d(g?`[${g.label||g.name}]`:"")},b=g=>{console.log("Formula submitted:",g),d(""),o(null)},h=()=>{d(""),o(null)};return e.jsxs("div",{className:t.cn("flex h-full w-full flex-col",s),children:[e.jsx(Jc,{value:i,onChange:d,onSubmit:b,onCancel:h,selectedColumn:r,availableColumns:c}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Uc,{selectedColumn:r,onColumnSelect:m,isLoading:u,sourceFields:c,filterableFields:x})}),e.jsx(Hc,{entityGroups:l,isLoading:u})]})]})}function Xc(){const[s,n]=v.useState("chart"),[r,o]=v.useState(!1),[i,d]=v.useState(!0),[c,l]=v.useState(!0),u=t.useEditorStore(V=>V.showAIDialog),x=t.useDashboardStore(V=>V.isVisualEditing),{setCardType:m}=t.useEditorActions(),b=t.useEditorStore(V=>V.card.type);v.useEffect(()=>qc(),[]);const h=V=>{m(V)},p=t.useEditorStore(V=>V.frame),j=t.useEditorStore(V=>V.card);t.useEditorStore(V=>V.activeTabCardId),t.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:N,removeCard:f,updateCard:g,setActiveCard:D,updateFilters:I,clearFilters:w}=t.useEditorActions(),{columnFields:S=[],scopedFields:M=[],filterableFields:A=[]}=a.useFilterableFields(),F=a.useSensors(a.useSensor(a.PointerSensor,{activationConstraint:{distance:8}})),E=j,{getFieldsForContainer:C,setFieldsForContainer:T,moveField:L,removeField:k,resetFields:R}=a.useFieldManagement(E,M),{activeField:y,handleDragStart:_,handleDragEnd:O}=kc({activeCardId:p.activeCardId,sourceFields:M,getFieldsForContainer:C,setFieldsForContainer:T,moveField:L}),P=(V,$)=>{$&&I(V,$)},B=V=>{w(V)},Y=A,q=V=>{if(!V)return 0;let $=V.conditions.length;return V.groups.forEach(Q=>{$+=q(Q)}),$},z=q(je.getAuthoredCardFilters(E)||null);return e.jsxs(a.DndContext,{sensors:F,collisionDetection:a.closestCenter,onDragStart:_,onDragEnd:O,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(oa,{isVisible:i,onToggleVisibility:()=>d(!i)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:b==="tableBuilder"?e.jsx(Wc,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!u&&e.jsx(xc,{onRemoveField:k,onResetFields:R,selectedChart:b,onChartChange:h,groupByFields:C("groupBy"),pivotByFields:C("pivotBy"),metricsFields:C("metrics"),sortByFields:C("sortBy"),detailFields:C("detailColumns"),activeField:y,isVisible:c,onToggleVisibility:()=>l(!c)}),e.jsx(Yc,{selectedChart:b,activeView:s,onViewChange:n,onFiltersClick:()=>o(!0),filterCount:z,activeCard:E,columns:S,getFieldsForContainer:C,cards:p.cards,activeCardId:p.activeCardId,addCard:N,setActiveCard:D})]})}),!i&&x&&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:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(a.Database,{className:"h-4 w-4"})})})]}),E&&e.jsx(Dc,{cardId:E.id,filters:je.getAuthoredCardFilters(E)||null,onFiltersChange:P,onClearFilters:B,availableFields:Y,isOpen:r,onOpenChange:o}),e.jsx(a.DragOverlay,{dropAnimation:null,children:e.jsx(zc,{activeField:y||null})})]})}function Zc({authToken:s,onSave:n,onClose:r}){const o=v.useRef(null),i=t.useEditorStore(A=>A.showAIDialog),d=t.useEditorStore(A=>A.isDevMode),c=a.useAssistantLayoutStore(A=>A.setFullscreen),l=a.useAssistantLayoutStore(A=>A.setPanelOpen),u=a.useAssistantLayoutStore(A=>A.setContainer),x=a.useAssistantPanel("editor"),m=a.useFullscreenAssistant(),b=a.useAssistantContainer("editor"),h=m==="editor",p=a.useDashboardAppearance(),j=v.useCallback(A=>{u("editor",A)},[u]),{setAuthToken:N}=t.useDashboardActions(),{setShowAIDialog:f,setOnSave:g,setOnClose:D}=t.useEditorActions(),{setActiveAssistantType:I}=t.useAIActions();v.useEffect(()=>{n&&g(n),r&&D(r)},[n,g,r,D]),v.useEffect(()=>{s&&s.accessToken&&N(s)},[s,N]),v.useEffect(()=>{var A,F;i?((A=o.current)==null||A.resize(40),l("editor",!0),I("editor")):((F=o.current)==null||F.resize(0),l("editor",!1),m==="editor"&&c(null),I(null))},[i,l,I,c,m]);function w(A){var F;A<1?(f(!1),l("editor",!1),m==="editor"&&c(null),I(null),(F=o.current)==null||F.resize(0)):(i||(f(!0),I("editor")),x.isOpen||l("editor",!0))}function S(){return e.jsxs(e.Fragment,{children:[e.jsx(oa,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow",children:[e.jsxs(a.ResizablePanelGroup,{"data-content":"editor-main",className:t.cn("grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(a.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Vi,{})}),e.jsx(a.ResizableHandle,{disabled:!i}),e.jsx(a.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xn,{isFullscreen:h,onFullscreenChange:A=>c(A?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:j,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function M(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(a.ResizablePanelGroup,{"data-content":"explorer",className:t.cn("flex grow transition-opacity",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(a.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Xc,{})}),e.jsx(a.ResizableHandle,{disabled:!i}),e.jsx(a.ResizablePanel,{"data-role":"editor-assistant-panel",ref:o,onResize:w,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Xn,{isFullscreen:h,onFullscreenChange:A=>c(A?"editor":null),fullscreenContainer:b})})})]}),e.jsx("div",{ref:j,className:t.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(a.ErrorBoundary,{FallbackComponent:a.Fallback,children:d?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:p.dashboardContainerStyle,children:S()}):e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",style:p.dashboardContainerStyle,children:M()})})}function ed(){t.useDashboardStore(p=>p.selectedCardId);const s=t.useDashboardStore(p=>p.selectedSheetId),n=t.useDashboardStore(p=>p.dashboard),{setIsVisualEditing:r,setSelectedSheetId:o}=t.useDashboardStore(p=>p.actions),i=t.useEditorStore(p=>p.editorContext),{clearEditorContext:d}=t.useEditorStore(p=>p.actions),c=a.useDashboardAppearance(),l=t.useDashboardStore(p=>p.isVisualEditing),u=t.useDashboardStore(p=>p.actions.updateFrame),x=t.useDashboardStore(p=>p.actions.updateDocumentSectionCard),m=a.useResolveExistingFrameSemanticExecutionPayload();async function b(p){var D,I,w;if((i==null?void 0:i.type)==="documentSection"){const S=a.getDocumentSectionEditorCard(p,i.cardId);if(!S){t.ue.error("No document section card found");return}if(!a.isSupportedDocumentTableCardType(S)){t.ue.error("Document table sections support Table and Pivot Table");return}x(i.sheetId,i.sectionId,S,{calculatedFields:p.calculatedFields}),d(),r(!1);return}const j=s?(D=n==null?void 0:n.sheets)==null?void 0:D.some(S=>{var M;return S.id===s&&((M=S.frames)==null?void 0:M.some(A=>A.id===p.id))}):!1,N=(w=(I=n==null?void 0:n.sheets)==null?void 0:I.find(S=>{var M;return(M=S.frames)==null?void 0:M.some(A=>A.id===p.id)}))==null?void 0:w.id,f=j?s:N||null;if(!f)return;const g=t.findDashboardFrameById(n,p.id);try{const S=await m(p,{previousFrame:g});u(f,p,{semanticExecutionPayload:S}),s!==f&&o(f),r(!1)}catch(S){console.error("Failed to resolve semantic metadata on save:",S),t.ue.error(S instanceof Error?S.message:"Failed to resolve semantic metadata for this visual")}}function h(){d(),r(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!l}),style:c.dashboardContainerStyle,children:e.jsx(Zc,{onSave:b,onClose:h})})}exports.default=ed;