react-semaphor 0.1.207 → 0.1.209

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 (37) hide show
  1. package/dist/chunks/{dashboard-controls-HlEsqiRq.js → dashboard-controls-BNTI4r0_.js} +581 -553
  2. package/dist/chunks/{dashboard-controls-CwMm9_ki.js → dashboard-controls-Dcpx9_an.js} +8 -8
  3. package/dist/chunks/{dashboard-json-DoYcT7tI.js → dashboard-json-BjOqpGbW.js} +1 -1
  4. package/dist/chunks/{dashboard-json-CI8wIOzY.js → dashboard-json-kIoBtmBF.js} +1 -1
  5. package/dist/chunks/{dashboard-summary-settings-dialog-ioe7ZyFE.js → dashboard-summary-settings-dialog-BoX18wiA.js} +1 -1
  6. package/dist/chunks/{dashboard-summary-settings-dialog-eQcHYcAI.js → dashboard-summary-settings-dialog-CO1SwHHD.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-Cl_qfIV_.js → edit-dashboard-visual-B9HuGExj.js} +2 -2
  8. package/dist/chunks/{edit-dashboard-visual-BotbTTiL.js → edit-dashboard-visual-DG4VLoJF.js} +1108 -1122
  9. package/dist/chunks/editor-action-buttons-CDTIx_Jc.js +11 -0
  10. package/dist/chunks/editor-action-buttons-CszdZ4Fw.js +345 -0
  11. package/dist/chunks/{index-CqOQuBxB.js → index-D0TdW88i.js} +24716 -24254
  12. package/dist/chunks/index-DSA80lEg.js +1104 -0
  13. package/dist/chunks/{notification-bell-BSBRPw38.js → notification-bell-D2V1-ARa.js} +1 -1
  14. package/dist/chunks/{notification-bell-BI-XywDI.js → notification-bell-DFiRaeJQ.js} +52 -52
  15. package/dist/chunks/resource-management-panel-BhiWNPcw.js +6 -0
  16. package/dist/chunks/resource-management-panel-DS_WEv1x.js +902 -0
  17. package/dist/chunks/{use-role-aware-display-preferences-BWghO18e.js → use-role-aware-display-preferences-D8j5_cnK.js} +1 -1
  18. package/dist/chunks/{use-role-aware-display-preferences-C-m9KEuJ.js → use-role-aware-display-preferences-DfihB5pN.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-BbVM0bck.js → use-visual-utils-BfLXO_vi.js} +34 -34
  20. package/dist/chunks/{use-visual-utils-DHmGIepC.js → use-visual-utils-CzcVz3zB.js} +1 -1
  21. package/dist/dashboard/index.cjs +1 -1
  22. package/dist/dashboard/index.js +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +5 -5
  25. package/dist/style.css +1 -1
  26. package/dist/surfboard/index.cjs +1 -1
  27. package/dist/surfboard/index.js +2 -2
  28. package/dist/types/dashboard.d.ts +12 -1
  29. package/dist/types/main.d.ts +13 -1
  30. package/dist/types/surfboard.d.ts +12 -1
  31. package/dist/types/types.d.ts +12 -1
  32. package/package.json +1 -1
  33. package/dist/chunks/editor-action-buttons-B0-mScSZ.js +0 -340
  34. package/dist/chunks/editor-action-buttons-CcXUQDy4.js +0 -11
  35. package/dist/chunks/index-plgMsXq1.js +0 -1104
  36. package/dist/chunks/resource-management-panel-D0q51oXw.js +0 -6
  37. package/dist/chunks/resource-management-panel-Z8x52dx2.js +0 -914
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-plgMsXq1.js"),I=require("react"),ye=require("./editor-action-buttons-CcXUQDy4.js"),Lt=require("react-dom");function Mt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const as=Mt(I);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-DSA80lEg.js"),I=require("react"),ye=require("./editor-action-buttons-CDTIx_Jc.js"),Lt=require("react-dom");function Mt(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const as=Mt(I);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -174,6 +174,6 @@ ${w.joinType} JOIN ${E.name}
174
174
 
175
175
  ${n||a.sql||a.python}
176
176
 
177
- `;l(x)}:void 0}}function nt({className:t,...n}){var ne,_,W,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((W=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:W.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),l=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[o,x]=I.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:m}=I.useContext(s.SemaphorContext),u=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:v}=s.useDashboardActions(),y=l==null?void 0:l.find($=>$.id===c.filterId),h=I.useMemo(()=>s.findCustomVisualConfigCard(c,a),[c,a]),{manifest:b}=s.useCustomVisual(((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.url)||""),T=I.useMemo(()=>{var $;return($=b==null?void 0:b.visuals)==null?void 0:$.find(H=>{var ae;return H.name===((ae=h==null?void 0:h.customCardPreferences)==null?void 0:ae.componentName)})},[b,(he=h==null?void 0:h.customCardPreferences)==null?void 0:he.componentName]),C=s.resolveMultiInputType(h,T),B=I.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:C==="multiple"}),[c,h,C]),O=I.useMemo(()=>{const $=B.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[B,a]),L=I.useMemo(()=>!h||C!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,T==null?void 0:T.slots)??a.type,[h,C,O,a,T==null?void 0:T.slots]),g=L??a.type,w=I.useMemo(()=>g===a.type?a:{...a,type:g},[a,g]),E=I.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:f,isLoading:M,isFetching:j,errorMessage:k,errorSql:D,pagination:P}=s.useDashboardCardQuery(E),{handleOpenInEditor:N,handleDebugWithAssistant:A}=at(k,D||a.sql||a.python),S=I.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=I.useMemo(()=>{var $;return g!=="pivotTable"||!(($=f==null?void 0:f.records)!=null&&$.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[g,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},Q=I.useMemo(()=>{const $=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:m,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:l,errorMessage:k||void 0,errorSql:D||a.sql||a.python,generatedSql:D||a.sql},metadata:{url:$,userAgent:H,timestamp:new Date().toISOString(),viewport:ae}}},[p,m,a,l,k,D]),J=($,H)=>{var ie,ge;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((ge=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&ge.enableDevModePagination)&&u(!0)},Z=$=>{var ie,ge,je,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(ge=a.config)==null?void 0:ge.groupByColumns,(je=a.config)==null?void 0:je.detailColumns),ae={...a,config:{...a.config||{},sortByColumns:H}};R(ae),F(ae),a.sql&&((Ne=(ve=a.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&u(!0)},q=I.useMemo(()=>!w.id||!(f!=null&&f.records)?null:s.createChartConfig({card:w,data:f==null?void 0:f.records,cardType:g,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w.id,f==null?void 0:f.records,g,w.customCfg,w.preferences,z]);function Y($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!M&&!j)return k?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:k,errorSql:D||a.sql||a.python,onOpenInEditor:N,onDebugWithAssistant:A,onSendFeedback:U,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((M||j)&&(!(f!=null&&f.records)||f.records.length===0))return g==="table"||g==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!w.id)return null;if(g==="custom")return Y(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(g)&&q)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:M||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:q})});if(g==="table"||g==="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(s.TableVisual,{card:w,data:S,comparisonMetadata:($=f==null?void 0:f.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:P,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(g==="pivotTable"&&V)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:w,data:V.data,options:V.options,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},onAggregationLabelChange:H=>{const ae=s.handleAggregationLabelChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)}})});if(g==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:w,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:J,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},isLoading:M||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(M||j)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:$=>R({...a,title:$}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(pa,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ha,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:$=>R({...a,description:$.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),y&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:y.title||y.column,onSave:$=>v({...y,title:$}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:y})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:d||""})}),e.jsxs(s.CardContent,{className:"flex min-h-0 grow flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:se()}),s.isCardSummaryVisibleOnCard(w)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:w,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:x,feedbackData:Q,showDebugInfo:!0})]})}const Qe=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),fa=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ga=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{language:"javascript",value:t,onChange:i})})]}),ja=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:i,variant:"outline",children:"Close"})]});function ba(){const[t,n]=I.useState(!1),[a,r]=I.useState(""),[i,c]=I.useState(""),[l,d]=I.useState(""),[o,x]=I.useState(""),p=s.useEditorStore(w=>w.card),m=ye.useEffectiveEditorCardType(),u=s.useEditorStore(w=>w.card.customCfg),v=u?JSON.stringify(u,null,2):"",y=I.useMemo(()=>m!==p.type?{...p,type:m}:p,[p,m]),{data:h}=s.useDashboardCardQuery(y),{data:b}=s.useTopoJson(p),{setCardCustomCfg:T,setCustomVisualCode:C}=s.useEditorActions(),B=w=>{var E,f;return JSON.stringify({...w,data:{...w.data,datasets:(f=(E=w.data)==null?void 0:E.datasets)==null?void 0:f.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,f;if(!((E=h==null?void 0:h.records)!=null&&E.length))return;const w=s.createChartConfig({card:p,data:h.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:b});if(w){r(B(w)),d(((f=p.preferences)==null?void 0:f.customVisualCode)||"");const M=s.merge(w,u);c(B(M))}},L=()=>{try{if(l&&C(l),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);T(E),x("")}}catch{x("Invalid JSON configuration")}},g=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:O,className:g?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(fa,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ga,{customCode:l,cardCustomCfgString:v,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ja,{error:o,hasCardCustomConfig:!!u,onReset:()=>{c(a),T(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ya({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function Ds({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:l,onToggleStar:d}){return e.jsxs("button",{onClick:l,className:s.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[c&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(ya,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const Ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function va({onChartSelect:t,onClose:n}){const[a,r]=I.useState(""),{starredCharts:i,isStarred:c,toggleStar:l}=s.useStarredChartsStore(),{data:d=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:m}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:v,setCustomCardPreferences:y,setQueryConfig:h,replaceFrameCards:b,clearModeDrafts:T,initializeModeDrafts:C}=s.useEditorActions(),B=I.useMemo(()=>{if(!a)return Ls;const f=a.toLowerCase();return Ls.filter(M=>M.name.toLowerCase().includes(f))},[a]),O=I.useMemo(()=>{const f=d.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return f;const M=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=f=>{v(null),p({}),x(f),["custom","text","map"].includes(f)&&(m(!0),h(void 0)),t==null||t(f),n==null||n()},g=f=>{v(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(f);if(M==="multiple"&&f.slots&&f.slots.length>0){T();const k=s.createCardsFromSlots(f.slots,f,u);b(k),k[0]&&C(k[0]),n==null||n();return}else x("custom"),y({type:"component",visualType:M,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},w=f=>{const M={type:"default",id:f.id,name:f.name};l(M)},E=f=>{const M={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};l(M)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[B.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:B.map(f=>e.jsx(Ds,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:c("default",f.id),onSelect:()=>L(f.id),onToggleStar:()=>w(f)},f.id))})}),O.length>0&&e.jsxs(e.Fragment,{children:[B.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:O.map((f,M)=>e.jsx(Ds,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:c("custom",f.name),onSelect:()=>g(f),onToggleStar:()=>E(f)},`${f.url}-${f.name}-${M}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),B.length===0&&O.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Na({selectedChart:t,onChartChange:n}){var g,w,E,f;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=s.useEditorActions(),x=I.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((g=x==null?void 0:x.customCardPreferences)==null?void 0:g.url)||""),m=I.useMemo(()=>{var M;return(M=p==null?void 0:p.visuals)==null?void 0:M.find(j=>{var k;return j.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[p,(w=x==null?void 0:x.customCardPreferences)==null?void 0:w.componentName]),u=s.resolveMultiInputType(x,m)==="multiple",v=ye.useEffectiveEditorCardType(),y=u?v:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,b=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,T=u&&!!b,C=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===y);return M?M.label:y==="custom"?h||"Custom Visual":"Select chart type"},[y,h]),B=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===y);if(M){const j=M.icon;return e.jsx(j,{className:"h-4 w-4"})}if(y==="custom"&&h){const j=s.getAutoDetectedChartIcon(h);return j||e.jsx(s.ChartIcon,{chartName:h,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Wt,{className:"h-4 w-4"})},[y,h]);return{displayChartType:y,displayLabel:C,displayIcon:B,showBadge:T,badgeLabel:b,isMultiInputContext:u,handleChartSelect:M=>{n==null||n(M)},handleClearCustomVisual:M=>{if(M.stopPropagation(),u){const k={...a,sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{}},P=s.useEditorStore.getState().frame.cards.map(N=>N.id===k.id?k:N);c(P),l(),d(k),i&&o(!0);return}const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([j]),l(),d(j),i&&o(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=I.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:m}=Na({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:"w-full justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(va,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),o&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:m,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function Ca(){const t=s.useEditorStore(o=>{var x,p;return(p=(x=o.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(o=>o.actions),i=o=>{if(a(o),n!=="bullet")return;const x=o==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,m={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(m)};function c(){const o=t??"x",x=()=>{i(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function l(){const o=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const o=t??"y",x=()=>{i(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?d():c()})}function Sa({className:t}){var v,y,h,b,T,C,B,O,L,g;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,l]=I.useState(!1),d=((y=(v=n.preferences)==null?void 0:v.displayOptions)==null?void 0:y.showFilterInfo)??!0,o=((b=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:b.showCardToolbar)??!0,x=((C=(T=n.preferences)==null?void 0:T.displayOptions)==null?void 0:C.showChrome)??!0,p=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,m=((g=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:g.showInlineFilterBar)??!0,u=(w,E)=>{var j;const f={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(f);const M={...n,preferences:f};i(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Qs,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:w=>{u("showFilterInfo",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:w=>{u("showCardToolbar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:w=>{u("showChrome",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:w=>{u("allowScroll",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:w=>{u("showInlineFilterBar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function wa(){const[t,n]=I.useState(!1),a=s.useEditorStore(m=>m.card),r=s.useEditorStore(m=>m.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),l=(a==null?void 0:a.inlineFilters)||[];function d(m){var g,w,E,f,M;const u=((E=(w=(g=a==null?void 0:a.dataSource)==null?void 0:g.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",v=m.qualifiedFieldName||m.name;if(l.find(j=>j.column===v))return;const h=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),C=s.buildFilterFieldMeta(m),B=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((f=a==null?void 0:a.dataSource)==null?void 0:f.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(C),L={id:s.v4(),column:v,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:u,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(m.dataType,h,T),fieldMeta:C,semanticContext:B,width:250};i({...a,inlineFilters:[...l,L]})}function o(m){const u=l.filter(v=>v.id!==m);i({...a,inlineFilters:u}),c(a.id,m)}function x(m,u){const v=l.map(y=>y.id===m?{...y,...u}:y);i({...a,inlineFilters:v})}return["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":l.length>0}),children:[e.jsx(Ut,{className:"h-4 w-4"}),l.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:l.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:d,inlineFilters:l})})})}),l.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:l.map(m=>e.jsx(Ta,{filter:m,onUpdate:u=>x(m.id,u),onRemove:()=>o(m.id)},m.id))})]})]})})]})}):null}function Ta({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function rt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(a)+1)%c.length;r(c[d])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Ca,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:i,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Hs,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(wa,{}),e.jsx(Sa,{})]})}function Ea({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,N,A,S,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:m}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(N=m==null?void 0:m.visuals)==null?void 0:N.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),y=s.resolveMultiInputType(a,u)==="multiple",h=(u==null?void 0:u.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,b=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),T=I.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:y}),[r,a,y]),C=y?T.filter(Boolean).length:r.cards.length,B=b?C<b:!0,O=C>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),g=(F,z)=>{F.dataTransfer.setData("tabIndex",z.toString())},w=F=>{F.preventDefault()},E=(F,z)=>{const G=F.dataTransfer.getData("tabIndex");if(G===z.toString())return;const V=Array.from(r.cards),[U]=V.splice(parseInt(G),1);V.splice(z,0,U),c({...r,cards:V})};function f(F){const z=(a==null?void 0:a.id)===F;if(!(L&&z?r.cards.length>1:O))return;let V=r.cards.filter(Z=>Z.id!==F);y&&!L&&(V=s.reindexSlotCards(V));const U=V[0],Q={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(Q),l(U.id),d(U),J&&p(U)}function M(F,z){if(!B)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),l(z.id)}function j(){if(y&&(a==null?void 0:a.id)===i.id){k(i);return}const F={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:y?Math.max(-1,...T.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function k(F){var J;if(!B)return;let z=y?"table":"bar",G="Title",V="";const U=y?Math.max(-1,...T.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:C;if(y&&((J=u==null?void 0:u.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(u.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const Q={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:s.v4(),title:G,tabTitle:G,description:V,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:z,sql:"",data:[],mode:"explorer",...y&&{customCardPreferences:{slotIndex:U}}};M(F,Q)}function D(F,z){return F.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||F.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=z.displayTab===void 0?!1:!z.displayTab;d({...z,displayTab:G}),o({...z,displayTab:G})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((F,z)=>{var J,Z;const G=y?s.getSlotIndexForCard(F,z):-1,V=y&&((J=u==null?void 0:u.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(u.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,Q=y&&((Z=u==null?void 0:u.slots)==null?void 0:Z.length)&&u.slots.every(q=>typeof q.position=="number"||typeof q.position=="string"&&!q.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!y,onDragStart:y?void 0:q=>g(q,z),onDragOver:y?void 0:w,onDrop:y?void 0:q=>E(q,z),className:"",value:F.id,children:[y&&V?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:V.label||`Tab ${G+1}`})]})}),e.jsx(s.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:V.label}),V.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:V.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[V.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(V.expectedType)?V.expectedType.join(" / "):V.expectedType}),V.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:[D(r,F),e.jsx(s.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:q=>{d({...i,tabTitle:q}),o({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!Q&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:q=>{q.stopPropagation(),j()}}),r.activeCardId===F.id&&(L&&(a==null?void 0:a.id)===F.id?r.cards.length>1:O)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(F.id)})]},F.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>k(i),disabled:!B,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),y&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ns(){var ge,je,ve,Ne,Ie;const t=s.useEditorStore(X=>X.frame),n=s.useEditorStore(X=>X.card),[a,r]=I.useState(!1),i=I.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),c=s.useEditorStore(X=>X.isSqlRunning);s.useEditorStore(X=>X.isDevMode);const{setFrame:l,setActiveTabCardId:d,setCard:o,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:u}=s.useEditorActions(),[v,y]=I.useState({}),[h,b]=I.useState(()=>new Set),{theme:T}=s.useTheme(),C=s.useDashboardStore(X=>X.themeStyle),{authToken:B}=s.useSemaphorContext(),O=s.getTokenParams(B==null?void 0:B.accessToken),L={mode:T||"system",colors:((je=(ge=C==null?void 0:C.chart)==null?void 0:ge.dataset)==null?void 0:je.backgroundColor)||[]},{getCard:g,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),f=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=f?g(f):null,j=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(X=>X.name===f),k=s.resolveMultiInputType(i,j),D=a&&k==="multiple"&&!!i,P=I.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(oe=>(oe==null?void 0:oe.id)===n.id?n:oe),[t,i,n]),N=I.useMemo(()=>s.buildSlotOrderedCards(P),[P]),A=I.useMemo(()=>{const X=P.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[P,n]),S=I.useMemo(()=>!i||k!=="multiple"||A<0?n.type:s.getEffectiveCardTypeForSlot(n,A,j==null?void 0:j.slots)??n.type,[i,k,A,n,j==null?void 0:j.slots]),R=I.useMemo(()=>D?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,D]),{data:F,isLoading:z,isFetching:G,isError:V}=s.useDashboardCardQuery(R),U=I.useCallback((X,oe)=>{const ue=s.normalizeMultiInputPayload(oe);y(xe=>({...xe,[X]:ue}))},[]),Q=I.useCallback((X,oe)=>{b(ue=>{const xe=new Set(ue);return oe?xe.add(X):xe.delete(X),xe})},[]),J=h.size>0,Z=s.useInteractionStore(X=>X.interactionStates),q=s.useDashboardStore(X=>{var oe;return(oe=X.dashboard)==null?void 0:oe.id}),Y=s.useDashboardStore(X=>X.dashboard.filters),se=s.useDashboardStore(X=>X.filterValues),ne=s.useDashboardStore(X=>X.selectedSheetId),_=s.useDashboardStore(X=>X.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),W=I.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:ne||"",inlineFilterValues:_}):[],[i,ne,_]),{cardFilters:le,cardFilterValues:he}=I.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:Z,currentDashboardId:q,filters:Y,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Y,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),m(),u(oe))}function H(X){const oe=s.useEditorStore.getState().card,ue=s.useEditorStore.getState().frame,xe={...ue,cards:ue.cards.map(Ce=>Ce.id===oe.id?oe:Ce),activeCardId:X};l(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),o(we)}function ae(){if(E)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!M)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const oe=N.map((ue,xe)=>s.getEffectiveCardTypeForSlot(ue,xe,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col px-6",children:[P.map((ue,xe)=>{if(!ue)return null;const we=s.getSlotIndexForCard(ue,xe),Ce=s.getEffectiveCardTypeForSlot(ue,we,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:Q,onDataChange:U,card:ue,effectiveCardType:Ce},`${ue.id}-${we}`)}),J&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",J&&"opacity-50"),children:e.jsx(I.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(M,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:N,slotTypes:oe,multiInputData:v,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:W})})})})]})}function ie(){var X;return D?ae():n.type==="kpi"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:F==null?void 0:F.records,isPending:z||G,isError:V,comparisonMetadata:(X=F==null?void 0:F.metadata)==null?void 0:X.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:c,card:n,data:F==null?void 0:F.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:$,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[D?e.jsx("div",{className:"mt-0 grow",children:ie()}):t.cards.map(X=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:X.id,children:ie()},X.id)),e.jsx(Ea,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ms({children:t}){var R;const n=s.useEditorStore(F=>F.frame),a=s.useEditorStore(F=>F.card),r=s.useEditorStore(F=>F.isDevMode),i=s.useEditorStore(F=>F.isShowingVisual),c=s.useDashboardStore(F=>F.isVisualEditing),l=s.useEditorStore(F=>F.pythonStdOut),d=s.useEditorStore(F=>F.actions.setRunSql),o=ye.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:m,runAssistant:u,setCardPreferences:v,mergeDraftsIntoCard:y,clearModeDrafts:h,initializeModeDrafts:b}=s.useEditorActions(),T=I.useMemo(()=>o!==a.type?{...a,type:o}:a,[a,o]),{data:C,isLoading:B,isFetching:O,errorMessage:L,errorSql:g,refetch:w,pagination:E}=s.useDashboardCardQuery(T),{handleDebugWithAssistant:f}=at(L,g),M=I.useMemo(()=>(C==null?void 0:C.records)||[],[C==null?void 0:C.records]),[j,k]=I.useState(!1);I.useEffect(()=>{O||k(!1)},[O]);function D(F,z){var U,Q;const G={...a,paginationConfig:{page:F+1,pageSize:z}};p(G);const V={...n,cards:n.cards.map(J=>J.id===a.id?G:J)};x(V),a.sql&&((Q=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&Q.enableDevModePagination)&&d(!0)}function P(F){var U,Q,J,Z,q;const z=s.sortStateToSortByColumns(F,(U=a.config)==null?void 0:U.metricColumns,(Q=a.config)==null?void 0:Q.groupByColumns,(J=a.config)==null?void 0:J.detailColumns),G={...a,config:{...a.config||{},sortByColumns:z}};p(G);const V={...n,cards:n.cards.map(Y=>Y.id===a.id?G:Y)};x(V),a.sql&&((q=(Z=a.preferences)==null?void 0:Z.tablePrefs)!=null&&q.enableDevModePagination)&&d(!0)}function N(){const F=JSON.stringify(C==null?void 0:C.records,null,2),z=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(z),V=document.createElement("a");V.href=G,V.download=`${a.title}.json`,V.click()}function A(){const z=[Object.keys(C==null?void 0:C.records.reduce((Q,J)=>({...Q,...J}),{})).join(","),...((C==null?void 0:C.records)||[]).map(Q=>Object.values(Q).join(","))].join(`
177
+ `;l(x)}:void 0}}function nt({className:t,...n}){var ne,_,W,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((W=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:W.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),l=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[o,x]=I.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:m}=I.useContext(s.SemaphorContext),u=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:v}=s.useDashboardActions(),y=l==null?void 0:l.find($=>$.id===c.filterId),h=I.useMemo(()=>s.findCustomVisualConfigCard(c,a),[c,a]),{manifest:b}=s.useCustomVisual(((le=h==null?void 0:h.customCardPreferences)==null?void 0:le.url)||""),T=I.useMemo(()=>{var $;return($=b==null?void 0:b.visuals)==null?void 0:$.find(H=>{var ae;return H.name===((ae=h==null?void 0:h.customCardPreferences)==null?void 0:ae.componentName)})},[b,(he=h==null?void 0:h.customCardPreferences)==null?void 0:he.componentName]),C=s.resolveMultiInputType(h,T),B=I.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:C==="multiple"}),[c,h,C]),O=I.useMemo(()=>{const $=B.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[B,a]),L=I.useMemo(()=>!h||C!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,T==null?void 0:T.slots)??a.type,[h,C,O,a,T==null?void 0:T.slots]),g=L??a.type,w=I.useMemo(()=>g===a.type?a:{...a,type:g},[a,g]),E=I.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:f,isLoading:M,isFetching:j,errorMessage:k,errorSql:D,pagination:P}=s.useDashboardCardQuery(E),{handleOpenInEditor:N,handleDebugWithAssistant:A}=at(k,D||a.sql||a.python),S=I.useMemo(()=>(f==null?void 0:f.records)||[],[f==null?void 0:f.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=I.useMemo(()=>{var $;return g!=="pivotTable"||!(($=f==null?void 0:f.records)!=null&&$.length)?null:{records:f.records,columnSubtotalMeta:f.columnSubtotalMeta,subtotalColumns:f.subtotalColumns||[],pivotSchema:f.pivotSchema||[],groupByColumns:f.groupByColumns}},[g,f==null?void 0:f.records,f==null?void 0:f.columnSubtotalMeta,f==null?void 0:f.subtotalColumns,f==null?void 0:f.pivotSchema,f==null?void 0:f.groupByColumns]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},Q=I.useMemo(()=>{const $=typeof window<"u"?window.location.href:"",H=typeof navigator<"u"?navigator.userAgent:"",ae=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:p,tokenContext:m,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:l,errorMessage:k||void 0,errorSql:D||a.sql||a.python,generatedSql:D||a.sql},metadata:{url:$,userAgent:H,timestamp:new Date().toISOString(),viewport:ae}}},[p,m,a,l,k,D]),J=($,H)=>{var ie,ge;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((ge=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&ge.enableDevModePagination)&&u(!0)},Z=$=>{var ie,ge,je,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(ge=a.config)==null?void 0:ge.groupByColumns,(je=a.config)==null?void 0:je.detailColumns),ae={...a,config:{...a.config||{},sortByColumns:H}};R(ae),F(ae),a.sql&&((Ne=(ve=a.preferences)==null?void 0:ve.tablePrefs)!=null&&Ne.enableDevModePagination)&&u(!0)},q=I.useMemo(()=>!w.id||!(f!=null&&f.records)?null:s.createChartConfig({card:w,data:f==null?void 0:f.records,cardType:g,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w.id,f==null?void 0:f.records,g,w.customCfg,w.preferences,z]);function Y($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(f!=null&&f.records&&(f==null?void 0:f.records.length)===0&&!M&&!j)return k?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:k,errorSql:D||a.sql||a.python,onOpenInEditor:N,onDebugWithAssistant:A,onSendFeedback:U,showFeedbackButton:!0})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(s.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if((M||j)&&(!(f!=null&&f.records)||f.records.length===0))return g==="table"||g==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableSkeleton,{})}):e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})});if(!w.id)return null;if(g==="custom")return Y(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(g)&&q)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:M||j?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:q})});if(g==="table"||g==="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(s.TableVisual,{card:w,data:S,comparisonMetadata:($=f==null?void 0:f.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:P,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(g==="pivotTable"&&V)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.PivotTableTanstack,{card:w,data:V.data,options:V.options,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},onAggregationLabelChange:H=>{const ae=s.handleAggregationLabelChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)}})});if(g==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:w,data:(f==null?void 0:f.records)||[],groupByColumns:f==null?void 0:f.groupByColumns,pivotSchema:f==null?void 0:f.pivotSchema,paginationMetadata:P,onPaginationChange:J,onAggregationChange:H=>{const ae=s.handleAggregationChange(H,a.config),ie={...a,config:ae};R(ie),F(ie)},isLoading:M||j})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...n,children:[(M||j)&&(f==null?void 0:f.records)&&f.records.length>0&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),r&&e.jsxs(s.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.CardTitle,{className:"text-base",children:e.jsx(s.EditableText,{value:a.title,onSave:$=>R({...a,title:$}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(pa,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ha,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:(a.description||"").trim(),onSave:$=>R({...a,description:$.trim()}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),y&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:y.title||y.column,onSave:$=>v({...y,title:$}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:y})]})]}),i&&a.inlineFilters&&a.inlineFilters.length>0&&e.jsx("div",{className:"px-6 pb-3",children:e.jsx(s.InlineFilterBar,{card:a,sheetId:d||""})}),e.jsxs(s.CardContent,{className:"flex min-h-0 grow flex-col",children:[e.jsx("div",{className:"min-h-0 flex-1 grow basis-0",children:se()}),s.isCardSummaryVisibleOnCard(w)&&e.jsx("div",{className:"pt-3",children:e.jsx(s.CardSummary,{card:w,mode:"editor"})})]}),e.jsx(s.FeedbackDialog,{open:o,onOpenChange:x,feedbackData:Q,showDebugInfo:!0})]})}const Qe=({language:t,value:n,onChange:a,readonly:r})=>e.jsx(s.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:t,value:n,onChange:a}),fa=()=>e.jsxs(s.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(s.DialogTitle,{children:"Customize Card"})}),e.jsxs(s.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),ga=({customCode:t,cardCustomCfgString:n,mergedConfig:a,onConfigChange:r,onCodeChange:i})=>e.jsxs(s.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(s.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(s.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(s.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(s.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(s.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{language:"json",value:a,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{readonly:!0,language:"json",value:n,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Qe,{language:"javascript",value:t,onChange:i})})]}),ja=({error:t,hasCardCustomConfig:n,onReset:a,onApply:r,onClose:i})=>e.jsxs(s.DialogFooter,{className:"flex items-center",children:[e.jsx(s.Label,{className:"mr-2 text-red-500",children:t}),e.jsx(s.Button,{disabled:!n,onClick:a,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:i,variant:"outline",children:"Close"})]});function ba(){const[t,n]=I.useState(!1),[a,r]=I.useState(""),[i,c]=I.useState(""),[l,d]=I.useState(""),[o,x]=I.useState(""),p=s.useEditorStore(w=>w.card),m=ye.useEffectiveEditorCardType(),u=s.useEditorStore(w=>w.card.customCfg),v=u?JSON.stringify(u,null,2):"",y=I.useMemo(()=>m!==p.type?{...p,type:m}:p,[p,m]),{data:h}=s.useDashboardCardQuery(y),{data:b}=s.useTopoJson(p),{setCardCustomCfg:T,setCustomVisualCode:C}=s.useEditorActions(),B=w=>{var E,f;return JSON.stringify({...w,data:{...w.data,datasets:(f=(E=w.data)==null?void 0:E.datasets)==null?void 0:f.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,f;if(!((E=h==null?void 0:h.records)!=null&&E.length))return;const w=s.createChartConfig({card:p,data:h.records,cardType:p.type,queryConfig:p.queryConfig,preferences:p.preferences,topoJson:b});if(w){r(B(w)),d(((f=p.preferences)==null?void 0:f.customVisualCode)||"");const M=s.merge(w,u);c(B(M))}},L=()=>{try{if(l&&C(l),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);T(E),x("")}}catch{x("Invalid JSON configuration")}},g=Object.keys(u||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:n,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:O,className:g?"":"text-green-600 hover:text-green-700",children:e.jsx(s.Settings,{className:"h-4 w-4"})})}),e.jsxs(s.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(fa,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(ga,{customCode:l,cardCustomCfgString:v,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ja,{error:o,hasCardCustomConfig:!!u,onReset:()=>{c(a),T(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ya({isStarred:t,onClick:n,className:a}){const r=i=>{i.stopPropagation(),i.preventDefault(),n(i)};return e.jsx("button",{type:"button",onClick:r,className:s.cn("flex items-center justify-center rounded-sm p-0.5 transition-all","hover:bg-muted/80",a),"aria-label":t?"Remove from favorites":"Add to favorites",children:e.jsx(s.Star,{className:s.cn("h-3.5 w-3.5 transition-colors",t?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-foreground")})})}function Ds({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:l,onToggleStar:d}){return e.jsxs("button",{onClick:l,className:s.cn("group relative flex flex-col items-center gap-2 rounded-lg border border-border","bg-background p-3 transition-all","hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm"),children:[c&&e.jsx("div",{className:s.cn("absolute left-1 top-1 transition-opacity",i?"opacity-100":"opacity-0 group-hover:opacity-100"),children:e.jsx(ya,{isStarred:i,onClick:()=>d()})}),a&&r&&e.jsx("div",{className:"absolute right-1 top-1",children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center justify-center",children:e.jsx(s.Info,{className:"h-3 w-3 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"top",className:"text-xs",children:r})]})}),e.jsx(s.ChartIcon,{chartType:t,chartName:n,isCustom:a,className:"h-6 w-6"}),e.jsx("span",{title:n,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:n})]})}const Ls=[{id:"table",name:"Table"},{id:"bar",name:"Bar Chart"},{id:"line",name:"Line Chart"},{id:"area",name:"Area Chart"},{id:"combo",name:"Combo Chart"},{id:"stackedBar",name:"Stacked Bar"},{id:"stackedArea",name:"Stacked Area"},{id:"stackedLine",name:"Stacked Line"},{id:"scatter",name:"Scatter"},{id:"bubble",name:"Bubble"},{id:"pie",name:"Pie Chart"},{id:"doughnut",name:"Doughnut"},{id:"funnel",name:"Funnel"},{id:"radar",name:"Radar"},{id:"polarArea",name:"Polar Area"},{id:"tornado",name:"Tornado"},{id:"range",name:"Range"},{id:"bullet",name:"Bullet Chart"},{id:"treemap",name:"Treemap"},{id:"heatmap",name:"Heatmap"},{id:"kpi",name:"KPI"},{id:"text",name:"Text"},{id:"map",name:"Map"}];function va({onChartSelect:t,onClose:n}){const[a,r]=I.useState(""),{starredCharts:i,isStarred:c,toggleStar:l}=s.useStarredChartsStore(),{data:d=[],isLoading:o}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:m}=s.useEditorStore(f=>f.actions),u=s.useEditorStore(f=>f.card),{setCardCustomCfg:v,setCustomCardPreferences:y,setQueryConfig:h,replaceFrameCards:b,clearModeDrafts:T,initializeModeDrafts:C}=s.useEditorActions(),B=I.useMemo(()=>{if(!a)return Ls;const f=a.toLowerCase();return Ls.filter(M=>M.name.toLowerCase().includes(f))},[a]),O=I.useMemo(()=>{const f=d.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return f;const M=a.toLowerCase();return f.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=f=>{v(null),p({}),x(f),["custom","text","map"].includes(f)&&(m(!0),h(void 0)),t==null||t(f),n==null||n()},g=f=>{v(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(f);if(M==="multiple"&&f.slots&&f.slots.length>0){T();const k=s.createCardsFromSlots(f.slots,f,u);b(k),k[0]&&C(k[0]),n==null||n();return}else x("custom"),y({type:"component",visualType:M,url:f.url,componentName:f.name,icon:f.icon,pluginChartType:f.chartType,minInputs:f.minInputs,maxInputs:f.maxInputs});t==null||t("custom",f),n==null||n()},w=f=>{const M={type:"default",id:f.id,name:f.name};l(M)},E=f=>{const M={type:"custom",id:f.name,url:f.url,icon:f.icon,name:f.name};l(M)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:a,onChange:f=>r(f.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[B.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:B.map(f=>e.jsx(Ds,{chartType:f.id,chartName:f.name,isCustom:!1,isStarred:c("default",f.id),onSelect:()=>L(f.id),onToggleStar:()=>w(f)},f.id))})}),O.length>0&&e.jsxs(e.Fragment,{children:[B.length>0?e.jsx(s.Separator,{className:"my-3"}):null,e.jsxs("div",{children:[e.jsx("span",{className:"mb-2 block text-xs font-medium text-muted-foreground",children:"Custom Charts"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:O.map((f,M)=>e.jsx(Ds,{chartName:f.name,isCustom:!0,pluginName:f.pluginName,isStarred:c("custom",f.name),onSelect:()=>g(f),onToggleStar:()=>E(f)},`${f.url}-${f.name}-${M}`))})]})]}),o&&e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom charts..."})]}),B.length===0&&O.length===0&&!o&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function Na({selectedChart:t,onChartChange:n}){var g,w,E,f;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:l,initializeModeDrafts:d,setIsDevMode:o}=s.useEditorActions(),x=I.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((g=x==null?void 0:x.customCardPreferences)==null?void 0:g.url)||""),m=I.useMemo(()=>{var M;return(M=p==null?void 0:p.visuals)==null?void 0:M.find(j=>{var k;return j.name===((k=x==null?void 0:x.customCardPreferences)==null?void 0:k.componentName)})},[p,(w=x==null?void 0:x.customCardPreferences)==null?void 0:w.componentName]),u=s.resolveMultiInputType(x,m)==="multiple",v=ye.useEffectiveEditorCardType(),y=u?v:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,b=(f=x==null?void 0:x.customCardPreferences)==null?void 0:f.componentName,T=u&&!!b,C=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===y);return M?M.label:y==="custom"?h||"Custom Visual":"Select chart type"},[y,h]),B=I.useMemo(()=>{const M=s.chartTypes.find(j=>j.id===y);if(M){const j=M.icon;return e.jsx(j,{className:"h-4 w-4"})}if(y==="custom"&&h){const j=s.getAutoDetectedChartIcon(h);return j||e.jsx(s.ChartIcon,{chartName:h,isCustom:!0,className:"h-4 w-4"})}return e.jsx(Wt,{className:"h-4 w-4"})},[y,h]);return{displayChartType:y,displayLabel:C,displayIcon:B,showBadge:T,badgeLabel:b,isMultiInputContext:u,handleChartSelect:M=>{n==null||n(M)},handleClearCustomVisual:M=>{M.stopPropagation();const j={...a,type:"bar",sql:"",python:"",config:void 0,queryConfig:void 0,customCfg:void 0,preferences:{},customCardPreferences:void 0,title:"Chart",tabTitle:"Chart",description:void 0,info:void 0};c([j]),l(),d(j),i&&o(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=I.useState(!1),{displayLabel:l,displayIcon:d,showBadge:o,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:m}=Na({selectedChart:t,onChartChange:n});return e.jsxs("div",{className:s.cn("relative w-full",r),children:[e.jsxs(s.Popover,{open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:a,role:"combobox","aria-expanded":i,className:"w-full justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[d,e.jsx("span",{className:"truncate",children:l})]}),e.jsx(s.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[360px] p-3",align:"start",onOpenAutoFocus:u=>u.preventDefault(),children:e.jsx(va,{onChartSelect:u=>p(u),onClose:()=>c(!1)})})]}),o&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title:x,children:[e.jsx(s.Layers,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:x}),e.jsx("button",{onClick:m,className:"rounded-full p-0.5 hover:bg-muted",title:"Clear custom visual",children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]})]})}function Ca(){const t=s.useEditorStore(o=>{var x,p;return(p=(x=o.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(o=>o.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(o=>o.actions),i=o=>{if(a(o),n!=="bullet")return;const x=o==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,m={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(m)};function c(){const o=t??"x",x=()=>{i(o==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function l(){const o=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:o,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const o=t??"y",x=()=>{i(o==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:o==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?l():n==="bullet"?d():c()})}function Sa({className:t}){var v,y,h,b,T,C,B,O,L,g;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,l]=I.useState(!1),d=((y=(v=n.preferences)==null?void 0:v.displayOptions)==null?void 0:y.showFilterInfo)??!0,o=((b=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:b.showCardToolbar)??!0,x=((C=(T=n.preferences)==null?void 0:T.displayOptions)==null?void 0:C.showChrome)??!0,p=((O=(B=n.preferences)==null?void 0:B.displayOptions)==null?void 0:O.allowScroll)??!0,m=((g=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:g.showInlineFilterBar)??!0,u=(w,E)=>{var j;const f={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(f);const M={...n,preferences:f};i(M),r(M)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:l,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(Qs,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:w=>{u("showFilterInfo",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:w=>{u("showCardToolbar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:x,onCheckedChange:w=>{u("showChrome",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:p,onCheckedChange:w=>{u("allowScroll",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:w=>{u("showInlineFilterBar",w)},onSelect:w=>w.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Inline Filter Bar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card filters"})]})]})]})})}function wa(){const[t,n]=I.useState(!1),a=s.useEditorStore(m=>m.card),r=s.useEditorStore(m=>m.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(m=>m.actions.removeCardInlineFilterValue),l=(a==null?void 0:a.inlineFilters)||[];function d(m){var g,w,E,f,M;const u=((E=(w=(g=a==null?void 0:a.dataSource)==null?void 0:g.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",v=m.qualifiedFieldName||m.name;if(l.find(j=>j.column===v))return;const h=m.qualifiedFieldName?m.qualifiedFieldName.split(".").slice(0,-1).join("."):m.qualifiedEntityName||m.entityName,T=s.fmt(m.name),C=s.buildFilterFieldMeta(m),B=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((f=a==null?void 0:a.dataSource)==null?void 0:f.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(C),L={id:s.v4(),column:v,title:m.label||m.name,dataType:m.dataType,table:m.entityName||"",database:u,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(m.dataType,h,T),fieldMeta:C,semanticContext:B,width:250};i({...a,inlineFilters:[...l,L]})}function o(m){const u=l.filter(v=>v.id!==m);i({...a,inlineFilters:u}),c(a.id,m)}function x(m,u){const v=l.map(y=>y.id===m?{...y,...u}:y);i({...a,inlineFilters:v})}return["bar","line","pie","doughnut","table","detailTable","stackedBar","stackedLine","horizontalBar","radar","polarArea","scatter","bubble","funnel","aggregateTable","custom"].includes(a==null?void 0:a.type)?e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs(s.Popover,{open:t,onOpenChange:n,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.IconButton,{tooltip:"Add Inline Filter",className:s.cn("relative",{"text-primary":l.length>0}),children:[e.jsx(Ut,{className:"h-4 w-4"}),l.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:l.length})]})}),e.jsx(s.PopoverContent,{align:"end",className:"w-80 p-0",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"border-b px-4 py-3",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Inline Filters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On-card filters for fast, focused exploration."})]}),e.jsx("div",{className:"flex max-h-[300px] flex-col overflow-hidden",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx(s.FieldsList,{context:"inline-filter",onFieldSelect:d,inlineFilters:l})})})}),l.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:l.map(m=>e.jsx(Ta,{filter:m,onUpdate:u=>x(m.id,u),onRemove:()=>o(m.id)},m.id))})]})]})})]})}):null}function Ta({filter:t,onUpdate:n,onRemove:a}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted px-2 py-1.5 text-sm",children:[e.jsx("span",{className:"truncate",title:t.column,children:t.title}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(s.CustomFilterPopover,{filter:t,variant:"inline",onAccept:r=>n(r),trigger:e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0",title:"Configure filter",children:e.jsx(s.Settings2,{className:"h-3 w-3"})})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 shrink-0 hover:bg-destructive/10 hover:text-destructive",onClick:a,children:e.jsx(s.X,{className:"h-3 w-3"})})]})]})}function rt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var l,d;return(d=(l=c.card)==null?void 0:l.preferences)==null?void 0:d.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function i(){const c=["xy","none","x","y"],d=(c.indexOf(a)+1)%c.length;r(c[d])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel","bullet"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(Ca,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:i,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(Hs,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(wa,{}),e.jsx(Sa,{})]})}function Ea({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var P,N,A,S,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:l,setCard:d,updateCardInFrame:o,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:m}=s.useCustomVisual(((P=a==null?void 0:a.customCardPreferences)==null?void 0:P.url)||""),u=(N=m==null?void 0:m.visuals)==null?void 0:N.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),y=s.resolveMultiInputType(a,u)==="multiple",h=(u==null?void 0:u.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,b=(u==null?void 0:u.maxInputs)??((S=a==null?void 0:a.customCardPreferences)==null?void 0:S.maxInputs),T=I.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:y}),[r,a,y]),C=y?T.filter(Boolean).length:r.cards.length,B=b?C<b:!0,O=C>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),g=(F,z)=>{F.dataTransfer.setData("tabIndex",z.toString())},w=F=>{F.preventDefault()},E=(F,z)=>{const G=F.dataTransfer.getData("tabIndex");if(G===z.toString())return;const V=Array.from(r.cards),[U]=V.splice(parseInt(G),1);V.splice(z,0,U),c({...r,cards:V})};function f(F){const z=(a==null?void 0:a.id)===F;if(!(L&&z?r.cards.length>1:O))return;let V=r.cards.filter(Z=>Z.id!==F);y&&!L&&(V=s.reindexSlotCards(V));const U=V[0],Q={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(Q),l(U.id),d(U),J&&p(U)}function M(F,z){if(!B)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),l(z.id)}function j(){if(y&&(a==null?void 0:a.id)===i.id){k(i);return}const F={...i,id:s.v4(),title:`${i.title} Copy`,tabTitle:`${i.tabTitle||i.title} Copy`,customCardPreferences:i.customCardPreferences?{...i.customCardPreferences,slotIndex:y?Math.max(-1,...T.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function k(F){var J;if(!B)return;let z=y?"table":"bar",G="Title",V="";const U=y?Math.max(-1,...T.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:C;if(y&&((J=u==null?void 0:u.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(u.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const Q={dataSource:F.dataSource,connectionId:F.connectionId,lastSelectedDatabase:F.lastSelectedDatabase,lastSelectedSchema:F.lastSelectedSchema,lastSelectedTable:F.lastSelectedTable,lastSelectedDatamodelId:F.lastSelectedDatamodelId,id:s.v4(),title:G,tabTitle:G,description:V,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:z,sql:"",data:[],mode:"explorer",...y&&{customCardPreferences:{slotIndex:U}}};M(F,Q)}function D(F,z){return F.cards.length===1&&(z.displayTab===!0||z.displayTab===void 0)||F.activeCardId!==z.id&&(z.displayTab===!0||z.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const G=z.displayTab===void 0?!1:!z.displayTab;d({...z,displayTab:G}),o({...z,displayTab:G})},children:z.displayTab===!0||z.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(s.EyeOff,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[r.cards.map((F,z)=>{var J,Z;const G=y?s.getSlotIndexForCard(F,z):-1,V=y&&((J=u==null?void 0:u.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(u.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,Q=y&&((Z=u==null?void 0:u.slots)==null?void 0:Z.length)&&u.slots.every(q=>typeof q.position=="number"||typeof q.position=="string"&&!q.position.includes("+"));return e.jsxs(s.TabsTrigger,{draggable:!y,onDragStart:y?void 0:q=>g(q,z),onDragOver:y?void 0:w,onDrop:y?void 0:q=>E(q,z),className:"",value:F.id,children:[y&&V?e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-muted-foreground",children:s.getChartIconByType(U,"size-3.5")}),e.jsx("span",{children:V.label||`Tab ${G+1}`})]})}),e.jsx(s.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:V.label}),V.description&&e.jsx("p",{className:"whitespace-normal break-words text-xs text-muted-foreground",children:V.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[V.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(V.expectedType)?V.expectedType.join(" / "):V.expectedType}),V.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:[D(r,F),e.jsx(s.Editable,{enabled:r.activeCardId===F.id,text:F.tabTitle||F.title,onSave:q=>{d({...i,tabTitle:q}),o({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!Q&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:q=>{q.stopPropagation(),j()}}),r.activeCardId===F.id&&(L&&(a==null?void 0:a.id)===F.id?r.cards.length>1:O)&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>f(F.id)})]},F.id)}),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>k(i),disabled:!B,children:e.jsx(s.Plus,{className:"h-4 w-4"})}),y&&e.jsxs(s.Toggle,{pressed:t,onPressedChange:n,size:"sm",className:"ml-2 h-8 gap-1 px-2 data-[state=on]:bg-background data-[state=on]:text-foreground","aria-label":"Toggle preview",children:[t?e.jsx(s.EyeOff,{className:"h-4 w-4"}):e.jsx(s.Eye,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Preview"})]})]})})}function ns(){var ge,je,ve,Ne,Ie;const t=s.useEditorStore(X=>X.frame),n=s.useEditorStore(X=>X.card),[a,r]=I.useState(!1),i=I.useMemo(()=>s.findCustomVisualConfigCard(t,n),[t,n]),c=s.useEditorStore(X=>X.isSqlRunning);s.useEditorStore(X=>X.isDevMode);const{setFrame:l,setActiveTabCardId:d,setCard:o,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:m,initializeModeDrafts:u}=s.useEditorActions(),[v,y]=I.useState({}),[h,b]=I.useState(()=>new Set),{theme:T}=s.useTheme(),C=s.useDashboardStore(X=>X.themeStyle),{authToken:B}=s.useSemaphorContext(),O=s.getTokenParams(B==null?void 0:B.accessToken),L={mode:T||"system",colors:((je=(ge=C==null?void 0:C.chart)==null?void 0:ge.dataset)==null?void 0:je.backgroundColor)||[]},{getCard:g,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),f=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=f?g(f):null,j=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(X=>X.name===f),k=s.resolveMultiInputType(i,j),D=a&&k==="multiple"&&!!i,P=I.useMemo(()=>s.getCustomVisualInputCards({frame:t,configCard:i,isMultiInputVisual:!0}).map(oe=>(oe==null?void 0:oe.id)===n.id?n:oe),[t,i,n]),N=I.useMemo(()=>s.buildSlotOrderedCards(P),[P]),A=I.useMemo(()=>{const X=P.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[P,n]),S=I.useMemo(()=>!i||k!=="multiple"||A<0?n.type:s.getEffectiveCardTypeForSlot(n,A,j==null?void 0:j.slots)??n.type,[i,k,A,n,j==null?void 0:j.slots]),R=I.useMemo(()=>D?{...n,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==n.type?{...n,type:S}:n,[n,S,D]),{data:F,isLoading:z,isFetching:G,isError:V}=s.useDashboardCardQuery(R),U=I.useCallback((X,oe)=>{const ue=s.normalizeMultiInputPayload(oe);y(xe=>({...xe,[X]:ue}))},[]),Q=I.useCallback((X,oe)=>{b(ue=>{const xe=new Set(ue);return oe?xe.add(X):xe.delete(X),xe})},[]),J=h.size>0,Z=s.useInteractionStore(X=>X.interactionStates),q=s.useDashboardStore(X=>{var oe;return(oe=X.dashboard)==null?void 0:oe.id}),Y=s.useDashboardStore(X=>X.dashboard.filters),se=s.useDashboardStore(X=>X.filterValues),ne=s.useDashboardStore(X=>X.selectedSheetId),_=s.useDashboardStore(X=>X.inlineFilterValuesMap[(i==null?void 0:i.id)||""]),W=I.useMemo(()=>i?s.buildInlineFilterNodes({card:i,sheetId:ne||"",inlineFilterValues:_}):[],[i,ne,_]),{cardFilters:le,cardFilterValues:he}=I.useMemo(()=>i?s.calculateContextAwareFilters({card:i,interactionStates:Z,currentDashboardId:q,filters:Y,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Y,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),m(),u(oe))}function H(X){const oe=s.useEditorStore.getState().card,ue=s.useEditorStore.getState().frame,xe={...ue,cards:ue.cards.map(Ce=>Ce.id===oe.id?oe:Ce),activeCardId:X};l(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),o(we)}function ae(){if(E)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading manifest"})});if(!M)return e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select a component to preview the multi-input visual."});const oe=N.map((ue,xe)=>s.getEffectiveCardTypeForSlot(ue,xe,j==null?void 0:j.slots));return e.jsxs("div",{className:"relative flex h-full flex-col px-6",children:[P.map((ue,xe)=>{if(!ue)return null;const we=s.getSlotIndexForCard(ue,xe),Ce=s.getEffectiveCardTypeForSlot(ue,we,j==null?void 0:j.slots);return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:Q,onDataChange:U,card:ue,effectiveCardType:Ce},`${ue.id}-${we}`)}),J&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading preview"})}),e.jsx("div",{className:s.cn("flex h-full min-h-0 flex-1 flex-col gap-2",J&&"opacity-50"),children:e.jsx(I.Suspense,{fallback:e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted"})}),children:e.jsx(M,{editing:!0,...s.buildMultiInputCustomVisualProps({configCard:i,slotOrderedCards:N,slotTypes:oe,multiInputData:v,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:W})})})})]})}function ie(){var X;return D?ae():n.type==="kpi"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"w-1/2 space-y-3",children:[e.jsx("div",{className:"rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:F==null?void 0:F.records,isPending:z||G,isError:V,comparisonMetadata:(X=F==null?void 0:F.metadata)==null?void 0:X.comparisonMetadata})}),s.isCardSummaryVisibleOnCard(n)&&e.jsx(s.CardSummary,{card:n,mode:"editor"})]})}):n.type==="text"?z||G?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:c,card:n,data:F==null?void 0:F.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(nt,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:$,value:t.activeCardId,className:"flex grow flex-col gap-2",children:[D?e.jsx("div",{className:"mt-0 grow",children:ie()}):t.cards.map(X=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:X.id,children:ie()},X.id)),e.jsx(Ea,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ms({children:t}){var R;const n=s.useEditorStore(F=>F.frame),a=s.useEditorStore(F=>F.card),r=s.useEditorStore(F=>F.isDevMode),i=s.useEditorStore(F=>F.isShowingVisual),c=s.useDashboardStore(F=>F.isVisualEditing),l=s.useEditorStore(F=>F.pythonStdOut),d=s.useEditorStore(F=>F.actions.setRunSql),o=ye.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:m,runAssistant:u,setCardPreferences:v,mergeDraftsIntoCard:y,clearModeDrafts:h,initializeModeDrafts:b}=s.useEditorActions(),T=I.useMemo(()=>o!==a.type?{...a,type:o}:a,[a,o]),{data:C,isLoading:B,isFetching:O,errorMessage:L,errorSql:g,refetch:w,pagination:E}=s.useDashboardCardQuery(T),{handleDebugWithAssistant:f}=at(L,g),M=I.useMemo(()=>(C==null?void 0:C.records)||[],[C==null?void 0:C.records]),[j,k]=I.useState(!1);I.useEffect(()=>{O||k(!1)},[O]);function D(F,z){var U,Q;const G={...a,paginationConfig:{page:F+1,pageSize:z}};p(G);const V={...n,cards:n.cards.map(J=>J.id===a.id?G:J)};x(V),a.sql&&((Q=(U=a.preferences)==null?void 0:U.tablePrefs)!=null&&Q.enableDevModePagination)&&d(!0)}function P(F){var U,Q,J,Z,q;const z=s.sortStateToSortByColumns(F,(U=a.config)==null?void 0:U.metricColumns,(Q=a.config)==null?void 0:Q.groupByColumns,(J=a.config)==null?void 0:J.detailColumns),G={...a,config:{...a.config||{},sortByColumns:z}};p(G);const V={...n,cards:n.cards.map(Y=>Y.id===a.id?G:Y)};x(V),a.sql&&((q=(Z=a.preferences)==null?void 0:Z.tablePrefs)!=null&&q.enableDevModePagination)&&d(!0)}function N(){const F=JSON.stringify(C==null?void 0:C.records,null,2),z=new Blob([F],{type:"application/json"}),G=URL.createObjectURL(z),V=document.createElement("a");V.href=G,V.download=`${a.title}.json`,V.click()}function A(){const z=[Object.keys(C==null?void 0:C.records.reduce((Q,J)=>({...Q,...J}),{})).join(","),...((C==null?void 0:C.records)||[]).map(Q=>Object.values(Q).join(","))].join(`
178
178
  `),G=new Blob([z],{type:"text/csv"}),V=URL.createObjectURL(G),U=document.createElement("a");U.href=V,U.download=`${a.title}.csv`,U.click()}function S(){const F=`Can you get the documentation for ${a.type} chart?`;u(F)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[i&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),c&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:S,children:e.jsx(Rt,{className:"size-4"})}),!["table","detailTable","custom"].includes(a.type)&&c&&e.jsx(ba,{})]}),!i&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:A,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:N,children:e.jsx(Pt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(C==null?void 0:C.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:B||O,onClick:()=>{k(!0),w()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":j})})}),e.jsx(rt,{})]}),r&&e.jsx(ka,{})]}),i?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[l&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:l&&e.jsx(Ia,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":l}),children:[(C==null?void 0:C.records)&&(C==null?void 0:C.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:M,comparisonMetadata:(R=C==null?void 0:C.metadata)==null?void 0:R.comparisonMetadata,paginationMetadata:E,onPaginationChange:D,onSortChange:P,isLoading:B||O}),L&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:L,errorSql:g||a.sql||a.python,onDebugWithAssistant:f,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Ia(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function ka(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs(s.Toggle,{pressed:!t,onPressedChange:()=>n(!t),variant:"outline",size:"sm",className:"h-8 gap-2",children:[e.jsx(s.Table2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:"Results"})]})}function Se({value:t,onCommit:n,type:a="text",placeholder:r,className:i}){const[c,l]=I.useState(t),d=I.useRef(!1);I.useEffect(()=>{l(t)},[t]);const o=()=>{if(d.current){d.current=!1;return}c!==t&&n(c)},x=p=>{if(p.key==="Enter"){p.currentTarget.blur();return}p.key==="Escape"&&(d.current=!0,l(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:c,onChange:p=>l(p.target.value),onBlur:o,onKeyDown:x,className:i})}function De({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:c,icon:l,showPlaceholderLabel:d=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:i,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",c),children:e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("span",{children:l}),d&&e.jsx(s.SelectValue,{placeholder:n})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:n}),a.map(o=>e.jsx(s.SelectItem,{value:o.value,children:o.label},o.value))]})})]})}function Aa(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function Be(t){if(typeof t=="number")return`Tab ${t+1}`;const n=t.match(/^(\d+)-(\d+)$/);if(n){const[,r,i]=n;return`Tabs ${Number(r)+1}-${Number(i)+1}`}const a=t.match(/^(\d+)\+$/);return a?`Tabs ${Number(a[1])+1}+`:`Tab ${t}`}function Da(t){return t?Array.isArray(t)?t:[t]:[]}function We(t){var r,i;if(!t)return!1;if(t.type==="text")return!!((r=t.description)!=null&&r.trim());const n=!!((i=t.sql)!=null&&i.trim()),a=s.hasValidCardConfig(t.config);return n||a}function La({slots:t,cards:n,minInputs:a}){const r=[],i=n.filter(Boolean).length;return a&&i<a&&r.push({type:"too-few-inputs",message:`This visual requires at least ${a} tab${a===1?"":"s"}.`}),!t||t.length===0||(t.forEach(c=>{if(!c.required)return;if(typeof c.position=="number"){const o=n[c.position];We(o)||r.push({type:"missing-required",message:`${Be(c.position)} ("${c.label}") is required but has no data configured.`});return}const l=c.position.match(/^(\d+)-(\d+)$/);if(l){const[,o,x]=l.map(Number);for(let p=o;p<=x;p+=1){const m=n[p];if(!We(m)){r.push({type:"missing-required",message:`${Be(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const o=Number(d[1]);if(n.length<=o){r.push({type:"missing-required",message:`${Be(o)} ("${c.label}") is required but has no data configured.`});return}for(let x=o;x<n.length;x+=1){const p=n[x];if(!We(p)){r.push({type:"missing-required",message:`${Be(x)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,l)=>{if(!c)return;const d=Aa(t,l);if(!d||!d.expectedType)return;const o=Da(d.expectedType);o.length!==0&&(o.includes(c.type)||r.push({type:"wrong-type",message:`${Be(l)} ("${d.label}") expects ${o.join(", ")}, but is configured as ${c.type}.`}))})),r}const Ma={table:({children:t})=>e.jsx("table",{className:"my-3 w-full border-collapse overflow-hidden rounded-md border border-border text-sm",children:t}),thead:({children:t})=>e.jsx("thead",{className:"bg-muted",children:t}),th:({children:t})=>e.jsx("th",{className:"border border-border px-3 py-2 text-left font-medium",children:t}),td:({children:t})=>e.jsx("td",{className:"border border-border px-3 py-2",children:t}),code:({children:t,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:t})}):e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:t}),pre:({children:t})=>e.jsx(e.Fragment,{children:t})};function lt(){var k,D,P;const t=s.useEditorStore(N=>N.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(N=>N.card),i=s.useEditorStore(N=>N.frame),{setCustomCardPreferences:c}=s.useEditorActions(),l=I.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),d=l==null?void 0:l.customCardPreferences,{components:o,manifest:x}=s.useCustomVisual((d==null?void 0:d.url)||(t==null?void 0:t.url)||""),p=(k=x==null?void 0:x.visuals)==null?void 0:k.find(N=>N.name===((d==null?void 0:d.componentName)||(t==null?void 0:t.componentName))),u=s.resolveMultiInputType(l||r,p)==="multiple",v=!!l&&l.id===r.id,y=(p==null?void 0:p.minInputs)??((D=l==null?void 0:l.customCardPreferences)==null?void 0:D.minInputs),h=(p==null?void 0:p.maxInputs)??((P=l==null?void 0:l.customCardPreferences)==null?void 0:P.maxInputs),b=I.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:l||r,isMultiInputVisual:u}),[i,l,r,u]),T=I.useMemo(()=>s.buildSlotOrderedCards(b),[b]),C=I.useMemo(()=>T.map((N,A)=>{if(!N)return null;const S=s.getSlotIndexForCard(N,A),R=s.getEffectiveCardTypeForSlot(N,S,p==null?void 0:p.slots);return{...N,type:R??N.type}}),[T,p==null?void 0:p.slots]),B=I.useMemo(()=>La({slots:p==null?void 0:p.slots,cards:C,minInputs:y}),[p==null?void 0:p.slots,C,y]),O=I.useMemo(()=>{const N=b.findIndex(A=>(A==null?void 0:A.id)===r.id);return N<0?-1:s.getSlotIndexForCard(r,N)},[b,r]);function L(N){if(typeof N=="number")return`Tab ${N+1}`;const A=N.match(/^(\d+)-(\d+)$/);if(A){const[,R,F]=A;return`Tabs ${Number(R)+1}-${Number(F)+1}`}const S=N.match(/^(\d+)\+$/);return S?`Tabs ${Number(S[1])+1}+`:`Tab ${N}`}function g(N){return N?(Array.isArray(N)?N:[N]).join(", "):null}function w(N,A,S=[],R="",F,z,G){const V=E({key:A,defaultValue:R,settingsValue:z,sourceCard:G});return N==="input"?e.jsx(Se,{className:`h-8 w-full ${s.removeRing}`,value:String(V??""),onCommit:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}},A):N==="select"?e.jsx(De,{className:"h-8 w-full",label:"",options:S,value:String(V!==void 0?V:R??""),onValueChange:U=>{f({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}}):null}function E({key:N,defaultValue:A,settingsValue:S,sourceCard:R}){const F=S==null?void 0:S[N];return F!==void 0?F:N==="title"&&(R==null?void 0:R.title)!==void 0?R.title:N==="description"&&(R==null?void 0:R.description)!==void 0?R.description:A}function f({key:N,value:A,settingsField:S,settingsValue:R,sourceCard:F}){const z={...R||{}},G=N==="title"&&(F==null?void 0:F.title)!==void 0,V=N==="description"&&(F==null?void 0:F.description)!==void 0;G&&A===String((F==null?void 0:F.title)??"")||V&&A===String((F==null?void 0:F.description)??"")?delete z[N]:z[N]=A,c({...t||{},[S]:z})}function M({settingsSchema:N,settingsField:A,settingsValue:S,sourceCard:R,headerLabel:F}){const z=Object.entries(N||{});return e.jsxs("div",{className:"space-y-3",children:[F&&e.jsx(s.Label,{children:F}),z.map(([G,V])=>{var U;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:V.title}),((U=V.docs)==null?void 0:U.description)&&e.jsx(s.TooltipProvider,{delayDuration:0,children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:V.docs.description})})]})})]}),w(V.ui,G,V.options,V.defaultValue,A,S,R)]},G)})]})}function j(){return e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Slot Guide"}),e.jsx("div",{className:"space-y-3 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs",children:p!=null&&p.slots&&p.slots.length>0?e.jsx("div",{className:"space-y-3",children:p.slots.map((N,A)=>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:L(N.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:N.label})]}),N.description&&e.jsx("p",{className:"text-muted-foreground",children:N.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[g(N.expectedType)&&e.jsxs("span",{children:["Expected: ",g(N.expectedType)]}),N.required&&e.jsx("span",{children:"Required"})]})]},`${N.label}-${A}`))}):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."}),(y||h)&&e.jsxs("p",{children:[y?`Min ${y} tabs`:"",y&&h?" • ":"",h?`Max ${h} tabs`:""]})]})})]}),u&&B.length>0&&e.jsx(s.Alert,{className:"border-yellow-500/40 bg-yellow-500/10 text-yellow-900 dark:text-yellow-100",children:e.jsx(s.AlertDescription,{children:e.jsx("ul",{className:"list-disc space-y-1 pl-4 text-xs",children:B.map((N,A)=>e.jsx("li",{children:N.message},`${N.type}-${A}`))})})}),p&&!u&&p.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:r})})}),p&&u&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[v&&p.settings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:l||r,headerLabel:"Global Settings"})}),p.slotSettings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.slotSettings,settingsField:"slotSettings",settingsValue:t==null?void 0:t.slotSettings,sourceCard:r,headerLabel:(()=>{const N=r.tabTitle||r.title,A=O>=0?O:0,S=v?"Slot 0":`Slot ${A}`;return N?`${S}: ${N} Settings`:`${S} Settings`})()})})]})]})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"",children:[e.jsxs(s.AccordionItem,{value:"plugin-settings",children:[e.jsx(s.AccordionTrigger,{children:"Plugin"}),e.jsx(s.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[(!u||v)&&e.jsx(De,{icon:e.jsx(_s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:a,value:(d==null?void 0:d.url)||"",onValueChange:N=>c({...t||{url:"",componentName:""},url:N})}),u&&!v&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Switch to the config tab to change the plugin or component."})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&(!u||v)&&e.jsx(e.Fragment,{children:o&&e.jsx(De,{icon:e.jsx(Bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.map(N=>({value:N.name,label:N.name})))||[],value:t.componentName||"",onValueChange:N=>{var R;const A=(R=x==null?void 0:x.visuals)==null?void 0:R.find(F=>F.name===N),S=o==null?void 0:o.find(F=>F.name===N);c({...t,componentName:N,visualType:(A==null?void 0:A.visualType)||(S==null?void 0:S.type)||"single",minInputs:A==null?void 0:A.minInputs,maxInputs:A==null?void 0:A.maxInputs,pluginChartType:A==null?void 0:A.chartType})}})})]})})]}),((d==null?void 0:d.componentName)||(t==null?void 0:t.componentName))&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:(p==null?void 0:p.name)||"Settings"}),(p==null?void 0:p.docs)&&e.jsxs(s.HoverCard,{openDelay:0,closeDelay:100,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,onClick:N=>N.stopPropagation(),children:e.jsx(s.Info,{className:"h-3.5 w-3.5 cursor-help text-muted-foreground transition-colors hover:text-foreground"})}),e.jsx(s.HoverCardContent,{side:"right",align:"start",className:"max-h-[40vh] w-[500px] overflow-y-auto text-left",children:e.jsxs("div",{className:"space-y-4 text-left",children:[p.docs.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.docs.description}),p.docs.dataSchema&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Data Schema"}),e.jsx("div",{className:"prose prose-sm dark:prose-invert prose-pre:bg-muted prose-pre:text-xs max-w-none",children:e.jsx(s.Markdown,{remarkPlugins:[s.remarkGfm],components:Ma,children:p.docs.dataSchema})})]}),(()=>{var A;const N=(A=p.docs)==null?void 0:A.useCases;return!N||N.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:N.map((S,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:S})]},R))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function Oa({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(l,d,o){const x=[...t];x[l]={...x[l],[d]:o},n(x)}function i(l){const d=[...t];d.splice(l,1),n(d)}function c(){n([...t,a])}return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{children:"Color Range"}),e.jsx(s.Button,{onClick:c,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((l,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:o=>r(d,"start",o.target.value),value:l.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:l.end,onChange:o=>r(d,"end",o.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:o=>r(d,"color",o.target.value),value:l.color,className:s.cn(`h-7 min-w-14 p-0 ${s.removeRing}`),type:"color",list:"presetColors"}),e.jsxs("datalist",{id:"presetColors",children:[e.jsx("option",{children:s.colors.green[600]}),e.jsx("option",{children:s.colors.red[500]}),e.jsx("option",{children:s.colors.yellow[400]}),e.jsx("option",{children:s.colors.orange[500]})]}),e.jsx(s.Button,{onClick:()=>i(d),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},d))]})}function Fa(){var p,m,u,v,y;const t=s.useEditorStore(h=>h.card.preferences),n=s.useEditorStore(h=>h.actions.setCardPreferences),a=s.useEditorStore(h=>h.card),r=s.hasValidCardConfig(a.config),i=s.useEditorStore(h=>h.actions.setNumberFormat);s.useEditorStore(h=>{var b,T;return(T=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:T.decimalPlaces});const c=s.useEditorStore(h=>{var b,T;return(T=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:T.locale}),l=s.useEditorStore(h=>{var b,T;return(T=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:T.currency});s.useEditorStore(h=>h.actions.setFilterOnClickField);const d=s.useEditorStore(h=>{var b,T;return(T=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:T.colorRanges})||[],o=s.useEditorStore(h=>h.actions.setColorRanges),x=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(h=>h.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((p=t==null?void 0:t.formatNumber)!=null&&p.enabled),onCheckedChange:h=>{n({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:h}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((m=t==null?void 0:t.formatNumber)==null?void 0:m.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:c||"none",onValueChange:h=>{var b,T,C;return i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",h,((C=t==null?void 0:t.formatNumber)==null?void 0:C.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Format"}),e.jsx(s.SelectItem,{value:"none",children:"Auto"},"none"),s.LOCALE_CURRENCY_PAIRS.map(h=>e.jsx(s.SelectItem,{value:h.locale,children:h.locale},h.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:l||"none",onValueChange:h=>{var b,T,C;console.log("currency",h),i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,h==="none"?"":h,((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-6 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Currency"}),e.jsx(s.SelectItem,{value:"none",children:"None"},"none"),x.map(h=>e.jsx(s.SelectItem,{value:h,children:h},h))]})})]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Decimals"}),e.jsxs(s.Select,{value:((v=(u=t==null?void 0:t.formatNumber)==null?void 0:u.decimalPlaces)==null?void 0:v.toString())||"0",onValueChange:h=>{var b,T,C;return i(Number(h),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.suffix)||"")},children:[e.jsx(s.SelectTrigger,{className:"col-span-3 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["0","1","2","3","4"].map(h=>e.jsx(s.SelectItem,{value:h,children:h},h))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((y=t==null?void 0:t.formatNumber)==null?void 0:y.suffix)||"",className:"h-8 font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"K, M, B, %",onChange:h=>{var b,T,C;return i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((T=t==null?void 0:t.formatNumber)==null?void 0:T.currency)||"",((C=t==null?void 0:t.formatNumber)==null?void 0:C.locale)||"",h.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Oa,{colorRanges:d,setColorRanges:o})]})]})}const Ra={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 is(t){return Ra[t]}function Ba({chartType:t,showDocsLink:n=!0}){const a=is(t);return a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Query Format"}),e.jsx("code",{className:"block rounded-md bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:a.query})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Fields"}),e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Field"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),e.jsx("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),e.jsx("tbody",{children:a.fields.map((r,i)=>e.jsxs("tr",{className:i<a.fields.length-1?"border-b":"",children:[e.jsxs("td",{className:"px-2.5 py-1.5 font-medium text-foreground",children:[r.name,r.optional&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:"?"})]}),e.jsx("td",{className:"px-2.5 py-1.5 font-mono text-muted-foreground",children:r.type}),e.jsx("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:r.description||"—"})]},r.name))})]})})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:a.description}),n&&a.docsUrl&&e.jsxs("a",{href:a.docsUrl,target:"_blank",rel:"noopener noreferrer",onClick:r=>r.stopPropagation(),className:"inline-flex items-center gap-1.5 text-xs font-medium text-primary hover:underline",children:["View documentation",e.jsx(s.ExternalLink,{className:"h-3 w-3"})]})]}):null}function Pa({chartType:t}){return is(t)?e.jsxs(s.HoverCard,{openDelay:200,children:[e.jsx(s.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(s.HoverCardContent,{className:"w-80 p-4",side:"left",align:"start",sideOffset:8,children:e.jsx(Ba,{chartType:t})})]}):null}function $e({chartType:t,suffix:n="Configuration"}){const a=is(t),r=(a==null?void 0:a.label)||t;return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-medium",children:[r," ",n]}),e.jsx(Pa,{chartType:t})]})}function Va(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($e,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Fa,{})})]})}function Os({children:t,summary:n,open:a,className:r}){return e.jsxs("details",{open:a,className:s.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(s.Label,{children:n}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}function ot(){const[t,n]=I.useState([]),a=s.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:i}=s.useEditorStore(x=>x.actions),c=s.useEditorStore(x=>x.queryResultColumns);s.useEditorStore(x=>{var p;return(p=x.card.preferences)==null?void 0:p.filterOnClickColumnIndex}),I.useEffect(()=>{c&&n(new Array(c.length).fill(!1))},[c]);function l(x,p){var m,u;p?a!=null&&a.onClickFilter&&((m=a==null?void 0:a.onClickFilter)==null?void 0:m.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(u=a==null?void 0:a.onClickFilter)==null?void 0:u.filter(v=>v.columnIndex!==x)}),n(v=>{const y=[...v];return y[x]=!1,y}))}function d(x,p){var u;const m=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.map(v=>v.columnIndex===x?{...v,expression:p.target.value}:v);i({...a,onClickFilter:m})}function o(x){var p,m,u,v;if(t!=null&&t[x]||(m=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(y=>y.columnIndex===x))!=null&&m.expression)return e.jsx(s.Input,{value:(v=(u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(y=>y.columnIndex===x))==null?void 0:v.expression,onChange:y=>d(x,y),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:c==null?void 0:c.map((x,p)=>{var m,u;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((m=a==null?void 0:a.onClickFilter)!=null&&m.find(v=>v.columnIndex===p)),onCheckedChange:v=>l(p,v)}),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:((u=a==null?void 0:a.onClickFilter)==null?void 0:u.find(v=>v.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(v=>{const y=[...v];return y[p]=!v[p],y})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),o(p)]})},x)})})}const za=[{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"}],$a=["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"],qa=$a.map(t=>({label:t,value:t}));function Ka(){var o,x,p,m,u,v,y,h,b,T,C,B,O,L,g,w,E,f;const t=s.useEditorStore(M=>M.card),n=(x=(o=t==null?void 0:t.preferences)==null?void 0:o.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=I.useState(((m=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:m.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:c}=s.useTopoJson(t),l=Object.keys((c==null?void 0:c.objects)||{}).map(M=>({label:M,value:M}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"map"}),e.jsx(Os,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(De,{className:"h-9",options:d,onValueChange:M=>{console.log("value",M),i({...t.preferences,mapVisualOptions:{topoJsonUrl:M}})},value:n||"",label:"Select Map"}),n==="custom"&&e.jsx(s.Input,{onChange:M=>{r(M.target.value)},onBlur:()=>{var M;console.log("onBlur",a),i({...t.preferences,mapVisualOptions:{...(M=t.preferences)==null?void 0:M.mapVisualOptions,customTopoJsonUrl:a}})},value:a,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(De,{className:"h-9",options:l,value:((v=(u=t.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:v.objectKey)||"",label:"Map Object",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,objectKey:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(De,{className:"h-9",options:za,value:((h=(y=t.preferences)==null?void 0:y.mapVisualOptions)==null?void 0:h.projection)||"",label:"Projection",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projection:M}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(De,{className:"h-9",options:qa,value:((T=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:T.colorScale)||"",label:"Select Color Scale",onValueChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,colorScale:M}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(Os,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(C=t.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:M=>{var j;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionScale:Number(M.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((g=(L=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:g[0])||0,onChange:M=>{var j,k,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(M.target.value),((P=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((f=(E=(w=t.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:f[1])||0,onChange:M=>{var j,k,D,P;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((P=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:P[0])||0,Number(M.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ot,{})]})}function it({color:t,onColorChange:n,onClose:a}){const[r,i]=I.useState(0),[c,l]=I.useState(100),[d,o]=I.useState(50),[x,p]=I.useState(t);I.useEffect(()=>{const b=Fs(t);if(b){const T=Rs(b.r,b.g,b.b);i(T.h),l(T.s),o(T.l),p(t)}},[t]);const m=b=>{i(b),v(b,c,d)},u=b=>{const T=b.currentTarget.getBoundingClientRect(),C=Math.max(0,Math.min(1,(b.clientX-T.left)/T.width)),B=Math.max(0,Math.min(1,(b.clientY-T.top)/T.height)),O=C*100,L=(1-B)*100;l(O),o(L),v(r,O,L)},v=(b,T,C)=>{const B=Ua(b,T,C),O=Ga(B.r,B.g,B.b);p(O)},y=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const T=Fs(b);if(T){const C=Rs(T.r,T.g,T.b);i(C.h),l(C.s),o(C.l)}}},h=()=>{/^#[0-9A-Fa-f]{6}$/.test(x)&&(n(x),a())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:u,onMouseMove:b=>{b.buttons===1&&u(b)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${c}%`,top:`${100-d}%`,backgroundColor:x}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:b=>m(Number(b.target.value)),className:"w-full h-4 rounded-lg appearance-none cursor-pointer",style:{background:"linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)"}})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"HEX"}),e.jsx(s.Input,{value:x,onChange:b=>y(b.target.value),placeholder:"#000000",className:"font-mono"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor:t}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"CURRENT"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full border shadow-sm",style:{backgroundColor: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(s.Button,{variant:"outline",onClick:a,children:"Cancel"}),e.jsx(s.Button,{onClick:h,children:"OK"})]})]})}function Fs(t){const n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Ga(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Rs(t,n,a){t/=255,n/=255,a/=255;const r=Math.max(t,n,a),i=Math.min(t,n,a);let c=0,l=0;const d=(r+i)/2;if(r!==i){const o=r-i;switch(l=d>.5?o/(2-r-i):o/(r+i),r){case t:c=((n-a)/o+(n<a?6:0))/6;break;case n:c=((a-t)/o+2)/6;break;case a:c=((t-n)/o+4)/6;break}}return{h:Math.round(c*360),s:Math.round(l*100),l:Math.round(d*100)}}function Ua(t,n,a){t/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const l=(x,p,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?x+(p-x)*6*m:m<.5?p:m<.6666666666666666?x+(p-x)*(.6666666666666666-m)*6:x),d=a<.5?a*(1+n):a+n-a*n,o=2*a-d;r=l(o,d,t+1/3),i=l(o,d,t),c=l(o,d,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const Bs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],_a=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:n,label:a}){const[r,i]=I.useState(!1),[c,l]=I.useState(!1),d=()=>{const o=Bs.find(x=>x.value===t);return o?o.color:t.startsWith("#")?t:Bs[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:i,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:d()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:_a.map(o=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",d()===o?"border-gray-900":"border-transparent"),style:{backgroundColor:o},onClick:()=>{n(o),i(!1)},children:e.jsx("span",{className:"sr-only",children:o})},o))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{l(!0),i(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>l(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:d(),onColorChange:o=>{n(o),l(!1)},onClose:()=>l(!1)})})]})]})}const Ha=["auto","number","currency","percent","scientific","date"],Ja=[{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"}],Ya=[{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"}],Qa=t=>t.charAt(0).toUpperCase()+t.slice(1);function qe({formatOptions:t={},onFormatOptionsChange:n,showTitle:a=!0,title:r="NUMBER FORMAT"}){const i=t.type||"auto",c=(d,o)=>{n({...t,[d]:o})},l=()=>i==="currency"?2:i==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[a&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:i,onValueChange:d=>c("type",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ha.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:d==="auto"?"Auto (Default)":Qa(d)},d))})]})]}),i!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(i)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",min:"0",max:"10",placeholder:"0",value:t.decimalPlaces??l(),onChange:d=>c("decimalPlaces",parseInt(d.target.value)||0),className:"h-8 text-xs"})})]}),i==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Currency"}),e.jsxs(s.Select,{value:t.currency||"USD",onValueChange:d=>c("currency",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ja.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),["number","currency"].includes(i)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:t.useSuffix??!1,onCheckedChange:d=>c("useSuffix",d)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Locale"}),e.jsxs(s.Select,{value:t.locale||"en-US",onValueChange:d=>c("locale",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ya.map(d=>e.jsx(s.SelectItem,{value:d.value,className:"text-xs",children:d.label},d.value))})]})]}),i==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Prefix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., $",value:t.prefix||"",onChange:d=>c("prefix",d.target.value),className:"h-8 text-xs"})})]}),i==="number"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Suffix"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{placeholder:"e.g., units",value:t.suffix||"",onChange:d=>c("suffix",d.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(i)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Negative in ()"}),e.jsx(s.SmallSwitch,{checked:t.negativeInParentheses??!1,onCheckedChange:d=>c("negativeInParentheses",d)})]}),i==="percent"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Multiply By"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"number",placeholder:"100",value:t.multiplyBy??"",onChange:d=>c("multiplyBy",d.target.value?parseFloat(d.target.value):void 0),className:"h-8 text-xs"})})]}),i==="date"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-20 text-xs text-muted-foreground",children:"Format"}),e.jsx("div",{className:"flex-1",children:e.jsx(s.Input,{type:"text",placeholder:"MM/DD/YYYY",value:t.dateFormat||"",onChange:d=>c("dateFormat",d.target.value),className:"h-8 text-xs"})})]})]})]})}function Wa(){const t=s.useDashboardStore(d=>d.dashboard.filters),n=s.useEditorStore(d=>d.frame),{setFrame:a}=s.useEditorActions(),{columns:r}=s.useColumns(),{assignFilter:i}=s.useAssignFilter();function c(d){const o=i(d,"frame");a({...n,filterId:o})}const l=t==null?void 0:t.find(d=>d.id===n.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(Xa,{onSelect:c,columns:r}),l&&e.jsx(s.FilterHeader,{filter:l})]})}function Xa({columns:t,onSelect:n}){var l;const[a,r]=as.useState(!1),[i,c]=as.useState("");return e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[i?((l=t.find(d=>d.name===i))==null?void 0:l.label)||i:"Select Column...",e.jsx(s.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No column found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(d=>e.jsxs(s.CommandItem,{value:d.name,onSelect:o=>{const x=o===i?"":o;c(x),r(!1),x&&n(d)},children:[d.label||d.name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",i===d.name?"opacity-100":"opacity-0")})]},d.id))})]})]})})]})}const Za=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],en=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function sn({cardType:t="table"}){var p,m,u,v,y;const n=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var b;return(b=h.card)==null?void 0:b.preferences}),r=s.useEditorStore(h=>h.actions.setCardPreferences),c=(((p=n.config)==null?void 0:p.metricColumns)||[]).some(h=>h.comparisonType&&h.comparisonType!=="none"),l=((m=a==null?void 0:a.tableVisualOptions)==null?void 0:m.metricComparison)||{},d=h=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...l,...h}}})},o={increase:((u=l.colors)==null?void 0:u.increase)||"green",decrease:((v=l.colors)==null?void 0:v.decrease)||"red",neutral:((y=l.colors)==null?void 0:y.neutral)||"neutral"},x=h=>{r({...a,allowDownload:h})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsxs(s.Accordion,{defaultValue:["item-3"],type:"multiple",children:[c&&e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated As"}),e.jsxs(s.Select,{value:l.calculatedAs||"change_difference",onValueChange:h=>d({calculatedAs:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Za.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Number Format"}),e.jsx(qe,{formatOptions:l.formatOptions||{},onFormatOptionsChange:h=>d({formatOptions:h}),showTitle:!1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator Style"}),e.jsxs(s.Select,{value:l.indicatorStyle||"arrow_badge",onValueChange:h=>d({indicatorStyle:h}),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:en.map(h=>e.jsx(s.SelectItem,{value:h.value,className:"text-xs",children:h.label},h.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Colors"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Le,{value:o.increase,onChange:h=>d({colors:{...o,increase:h}}),label:"Increase"}),e.jsx(Le,{value:o.decrease,onChange:h=>d({colors:{...o,decrease:h}}),label:"Decrease"}),e.jsx(Le,{value:o.neutral,onChange:h=>d({colors:{...o,neutral:h}}),label:"No Change"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Lower is Better"}),e.jsx(s.Checkbox,{checked:l.lowerIsBetter||!1,onCheckedChange:h=>d({lowerIsBetter:!!h})})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{children:"Click Filters"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(ot,{}),e.jsx(Wa,{})]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:x,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}function tn(){var r;const t=s.useEditorStore(i=>i.card.preferences),{setCardPreferences:n}=s.useEditorStore(i=>i.actions);function a(i){n({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:i==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:a,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function an(){return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:"text"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Text Type"}),e.jsx(tn,{})]})]})}const nn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function rn(){var L,g,w,E,f,M,j,k,D,P;const t=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>{var A;return(A=N.card)==null?void 0:A.preferences}),a=ye.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),c=I.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:l}=s.useDashboardCardQuery(c),[d,o]=I.useState({}),[x,p]=I.useState(null),[m,u]=I.useState(null),v=I.useMemo(()=>{var R,F,z,G,V,U,Q;if(!(l!=null&&l.records)||l.records.length===0)return[];const N=a==="stackedBar"||a==="stackedLine",A=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",S=((R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns)&&t.config.pivotByColumns.length>0;if((N||A)&&S){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const J=new Set;return l.pivotSchema.forEach(Z=>{Z.alias&&J.add(Z.alias)}),Array.from(J)}if(l.records.length>0){const J=l.records[0],Z=Object.keys(J),q=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(ne=>{q.add(ne.label||ne.name),q.add(ne.alias||ne.name)});const Y=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(ne=>{const _=ne.alias||ne.name;Y.add(_),Y.add(`${_}_count`),Y.add(`${_}_sum`),Y.add(`${_}_avg`),Y.add(`${_}_min`),Y.add(`${_}_max`);const W=ne.entityName||ne.qualifiedEntityName;W&&(Y.add(`${W}_${_}`),Y.add(`${W}_${_}_count`))}),Z.filter(ne=>!q.has(ne)&&!Y.has(ne))}}if((A||N)&&!S&&((V=(G=t==null?void 0:t.config)==null?void 0:G.metricColumns)!=null&&V.length))return t.config.metricColumns.map(J=>J.alias||J.label||J.name);if((Q=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&Q.length){const J=t.config.groupByColumns[0],Z=J.label||J.name,q=new Set;return l.records.forEach(Y=>{const se=Y[Z];se!=null&&q.add(String(se))}),Array.from(q)}return[]},[l,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(g=t==null?void 0:t.config)==null?void 0:g.pivotByColumns,(w=t==null?void 0:t.config)==null?void 0:w.metricColumns,t==null?void 0:t.type]),y=I.useMemo(()=>s.getDefaultChartColors(),[]);I.useEffect(()=>{const N={};v.forEach((A,S)=>{N[A]=s.getColorForValue(A,S,n==null?void 0:n.colorConfig)}),o(N)},[v,n==null?void 0:n.colorConfig,y]);const h=(N,A)=>{const S={...d,[N]:A};o(S);const R={...n||{},colorConfig:{segments:S}};r(R);const F={...t,preferences:R};i(F)},b=(N,A)=>{var V;const S=y[A%y.length],{[N]:R,...F}=((V=n==null?void 0:n.colorConfig)==null?void 0:V.segments)||{},z={...n||{},colorConfig:{segments:F}};r(z);const G={...t,preferences:z};i(G),o(U=>({...U,[N]:S}))};if(!v.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns)==null?void 0:f.length)||((j=(M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)==null?void 0:j.length):(D=(k=t==null?void 0:t.config)==null?void 0:k.groupByColumns)==null?void 0:D.length)||["table","kpi","text","custom","heatmap"].includes(a))return null;const B=()=>{const N={...n||{},colorConfig:{segments:{}}};r(N);const A={...t,preferences:N};i(A);const S={};v.forEach((R,F)=>{S[R]=s.getColorForValue(R,F,void 0)}),o(S)},O=Object.keys(((P=n==null?void 0:n.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Colors"})]})}),e.jsx(s.AccordionContent,{className:"",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("div",{className:"flex items-center justify-between",children:O&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:B,children:[e.jsx(Is,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:v.map((N,A)=>{const S=s.isDefaultColor(d[N],A),R=!S;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===N,onOpenChange:F=>p(F?N:null),children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"h-5 w-5 shrink-0 rounded border border-input shadow-sm transition-colors hover:border-gray-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",style:{backgroundColor:d[N]}})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-3",children:e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Theme Colors"}),e.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:y.slice(0,10).map((F,z)=>e.jsxs("button",{className:s.cn("relative h-5 w-5 rounded border-2 transition-all hover:scale-110",d[N]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{h(N,F),p(null)},children:[z===A%y.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:F})]},`default-${z}`))})]}),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:nn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[N]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{h(N,F),p(null)},children:e.jsx("span",{className:"sr-only",children:F})},`preset-${z}`))})]}),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:()=>{u({value:N,color:d[N]}),p(null)},children:"Custom color"}),!S&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(N,A),p(null)},children:[e.jsx(Is,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:N}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},N)})}),m&&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:()=>u(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:m.color,onColorChange:N=>{h(m.value,N),u(null)},onClose:()=>u(null)})})]})]})})]})}function Te({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,l]=I.useState(t??""),[d,o]=I.useState(!1);I.useEffect(()=>{l(t??"")},[t]);const x=()=>{n(c),o(!1)},p=()=>{l(t??""),o(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${i}`,children:[e.jsx(s.Input$1,{placeholder:a,type:r,value:d?c:t??"",onChange:m=>{l(m.target.value),o(!0)},onFocus:()=>o(!0),onClick:m=>m.stopPropagation(),className:"h-8 text-xs",onPointerDown:m=>m.stopPropagation(),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&d&&c!==t?x():m.key==="Escape"&&p()},"aria-label":a||"Edit field"}),d&&c!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:x,children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:p,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function Xe({axis:t,label:n,type:a,config:r,onChange:i,defaultTitle:c,hidePosition:l}){var v,y,h,b,T,C,B,O,L,g,w,E,f,M;const d=(j,k)=>{i({...r??{},[j]:k})},o=(j,k)=>{var A,S,R,F;const D=j==="enabled"&&k===!0,P=(A=r==null?void 0:r.name)==null?void 0:A.text,N=D&&!P&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?k:((S=r==null?void 0:r.name)==null?void 0:S.enabled)??!1,text:j==="text"?k:N?c:P,fontSize:j==="fontSize"?k:(R=r==null?void 0:r.name)==null?void 0:R.fontSize,fontWeight:j==="fontWeight"?k:(F=r==null?void 0:r.name)==null?void 0:F.fontWeight}})},x=(j,k)=>{var D,P;i({...r??{},labels:{enabled:j==="enabled"?k:((D=r==null?void 0:r.labels)==null?void 0:D.enabled)??!0,rotation:j==="rotation"?k:(P=r==null?void 0:r.labels)==null?void 0:P.rotation}})},p=(j,k)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:k===""?"auto":Number(k)}})},m=t==="x"?["auto","top","bottom"]:["auto","left","right"],u=["auto","0","45","90","-45","-90"];return e.jsxs(s.AccordionItem,{value:`${t}-axis`,className:"border-b-0",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx(s.AccordionTrigger,{className:"flex grow items-center justify-between gap-3 py-2 text-sm font-medium hover:no-underline",children:e.jsx("div",{className:"flex grow items-center justify-between gap-2",children:e.jsx("span",{children:n})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:j=>d("enabled",j),onClick:j=>j.stopPropagation()})]}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:`${t}-title-enabled`,checked:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,onCheckedChange:j=>o("enabled",j===!0)}),e.jsx(s.Label,{htmlFor:`${t}-title-enabled`,className:"text-xs font-medium cursor-pointer",children:"TITLE"})]}),((y=r==null?void 0:r.name)==null?void 0:y.enabled)&&e.jsxs("div",{className:"space-y-2 pl-6",children:[e.jsx(Te,{placeholder:`${n} title`,value:((h=r==null?void 0:r.name)==null?void 0:h.text)||"",onSave:j=>o("text",j),className:""}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Size"}),e.jsx("div",{className:"w-14",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((b=r==null?void 0:r.name)==null?void 0:b.fontSize)||12),onSave:j=>o("fontSize",Number(j)||12),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Weight"}),e.jsxs(s.Select,{value:((T=r==null?void 0:r.name)==null?void 0:T.fontWeight)||"normal",onValueChange:j=>o("fontWeight",j),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]})]})]})]}),!l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"POSITION"}),e.jsxs(s.Select,{value:(r==null?void 0:r.position)||"auto",onValueChange:j=>d("position",j),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":s.titleCase(j)},j))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((C=r==null?void 0:r.labels)==null?void 0:C.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((B=r==null?void 0:r.labels)==null?void 0:B.enabled)!==!1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Rotation"}),e.jsxs(s.Select,{value:String(((O=r==null?void 0:r.labels)==null?void 0:O.rotation)||"auto"),onValueChange:j=>x("rotation",j==="auto"?"auto":Number(j)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(j=>e.jsx(s.SelectItem,{value:j,className:"text-xs",children:j==="auto"?"Auto (Default)":`${j}°`},j))})]})]})]}),a==="value"&&e.jsx(qe,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:j=>i({...r,formatOptions:j}),showTitle:!0,title:"FORMAT"}),a==="value"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"SCALE"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Min"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"auto",value:((L=r==null?void 0:r.scale)==null?void 0:L.min)==="auto"||((g=r==null?void 0:r.scale)==null?void 0:g.min)===void 0?"":String(r.scale.min),onSave:j=>p("min",j),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"auto",value:((w=r==null?void 0:r.scale)==null?void 0:w.max)==="auto"||((E=r==null?void 0:r.scale)==null?void 0:E.max)===void 0?"":String(r.scale.max),onSave:j=>p("max",j),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"w-8 text-xs text-muted-foreground",children:"Step"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"auto",value:((f=r==null?void 0:r.scale)==null?void 0:f.stepSize)==="auto"||((M=r==null?void 0:r.scale)==null?void 0:M.stepSize)===void 0?"":String(r.scale.stepSize),onSave:j=>p("stepSize",j),className:""})})]})]})]})]})]})}function Ze(t,n,a){var c,l,d;if(t==="x"){const o=(l=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:l[0];return(o==null?void 0:o.label)||(o==null?void 0:o.name)||""}const r=((d=n==null?void 0:n.config)==null?void 0:d.metricColumns)||[],i=(a==null?void 0:a.datasetOptions)||[];if(t==="y"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return!m||m.yAxisId!=="y2"});return o.length===1&&(o[0].label||o[0].name)||""}if(t==="y2"){const o=r.filter((x,p)=>{const m=i.find(u=>u.idx===p);return(m==null?void 0:m.yAxisId)==="y2"});return o.length===1&&(o[0].label||o[0].name)||""}return""}function ln(){const t=s.useEditorStore(o=>o.card),n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=ye.useEffectiveEditorCardType();if(!t||["tornado","pyramid","kpi","treemap"].includes(i))return null;const c=s.AxisConfigurator.getAxisInfo(i,n);if(!c.hasXAxis&&!c.hasYAxis)return null;const l=(o,x)=>{let p;o==="x"?p="xAxisConfig":o==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const m={...n||{},[p]:x};a(m);const u={...t,preferences:m};r(u)},d=c.hasY2Axis&&i==="combo";return e.jsxs(s.AccordionItem,{value:"axes",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Axes"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[c.hasXAxis&&e.jsx(Xe,{axis:"x",label:"X-Axis",type:c.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"x"),n==null?void 0:n.xAxisConfig),onChange:o=>l("x",o),defaultTitle:Ze("x",t,n)}),c.hasYAxis&&e.jsx(Xe,{axis:"y",label:d?"Y-Axis (Left)":"Y-Axis",type:c.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(i,"y"),n==null?void 0:n.yAxisConfig),onChange:o=>l("y",o),defaultTitle:Ze("y",t,n)}),d&&e.jsx(Xe,{axis:"y2",label:"Y2-Axis (Right)",type:"value",config:s.mergeAxisConfig({enabled:!0,position:"right"},n==null?void 0:n.secondaryYAxisConfig),onChange:o=>l("y2",o),defaultTitle:Ze("y2",t,n),hidePosition:!0})]})})]})}function on(){const t=s.useEditorStore(m=>m.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(m=>{var u,v,y,h;return(h=(y=(v=(u=m.card)==null?void 0:u.preferences)==null?void 0:v.chartOptions)==null?void 0:y.plugins)==null?void 0:h.legend}),{setLegendOptions:r}=s.useEditorActions();if(!t||!s.chartSupportsLegend(n))return null;const i=s.getDefaultLegendConfig(n),c=(i==null?void 0:i.display)??!0,l=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",o=(m,u)=>{const v={...a,[m]:u};r(v)},x=["top","bottom","left","right"],p=["start","center","end"];return e.jsxs(s.AccordionItem,{value:"legend",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Legend"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.display)??c,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??c)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:(a==null?void 0:a.position)||l,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||d,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function cn(){var A,S,R,F,z,G,V,U,Q,J,Z;const t=s.useEditorStore(q=>q.card),n=ye.useEffectiveEditorCardType(),a=s.useEditorStore(q=>{var Y,se;return(se=(Y=q.card)==null?void 0:Y.preferences)==null?void 0:se.dataLabelsConfig}),r=s.useEditorStore(q=>{var Y;return(Y=q.card)==null?void 0:Y.preferences}),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const l=n==="bullet"?((A=r==null?void 0:r.bulletConfig)==null?void 0:A.orientation)??(((S=r==null?void 0:r.chartOptions)==null?void 0:S.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=l!=null?l==="horizontal":((R=r==null?void 0:r.chartOptions)==null?void 0:R.indexAxis)==="y",o=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,m=n==="bubble"||n==="scatter",u=(z=(F=r==null?void 0:r.chartOptions)==null?void 0:F.plugins)==null?void 0:z.datalabels,v=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),y=s.getDefaultDataLabelsConfig(n,t.preferences),h=a??y,b=(y==null?void 0:y.enabled)??v??!1,T=(a==null?void 0:a.enabled)!==void 0?a.enabled:b,C=(q,Y)=>{const _={...y??{},...a??{},[q]:Y};q==="enabled"&&(_.display=Y,Y&&m&&!_.position&&(_.position="bottom")),q==="position"&&m&&(_.position="bottom");const W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},B=(q,Y)=>{const se=a??{},_={...y??{},...se,font:{...se.font||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},O=(q,Y)=>{const se=a??{},_={...y??{},...se,formatOptions:{...se.formatOptions||{},[q]:Y}},W={...t.preferences||{},dataLabelsConfig:_};i(W);const le={...t,preferences:W};c(le)},L=()=>{const q=n;return q==="stackedBar"||q==="stackedLine"||q==="pie"||q==="doughnut"?"center":d?"right":"top"},g=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",E=L();let f=[];if(g)if(m)f=["bottom"];else if(o||x)f=["center"];else{const q=d?["center","left","right"]:["center","top","bottom"];f=["auto",...n==="bullet"?q:q.filter(se=>se!==E),"custom"]}const M=()=>s.titleCase(E),j=["center","start","end"],k=["center","start","end","top","bottom"],D=p?["auto","number","currency","percent","none"]:["number","currency","percent","none"],P=[{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"}],N=[{value:"en-US",label:"English (US)"},{value:"en-GB",label:"English (UK)"},{value:"de-DE",label:"German"},{value:"fr-FR",label:"French"},{value:"es-ES",label:"Spanish"},{value:"it-IT",label:"Italian"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"zh-CN",label:"Chinese (Simplified)"}];return e.jsxs(s.AccordionItem,{value:"data-labels",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Data Labels"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Display"}),e.jsx(s.SmallSwitch,{checked:T,onCheckedChange:q=>C("enabled",q)})]}),T&&e.jsxs(e.Fragment,{children:[g&&!o&&!x&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Position"}),e.jsxs(s.Select,{value:m?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:q=>C("position",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"?M():q==="custom"?"Custom (Advanced)":s.titleCase(q)},q))})]})]}),o&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Show Total"}),e.jsx(s.SmallSwitch,{checked:(a==null?void 0:a.showTotal)??!1,onCheckedChange:q=>C("showTotal",q)})]}),(h==null?void 0:h.position)==="custom"&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Anchor"}),e.jsxs(s.Select,{value:(h==null?void 0:h.anchor)||"center",onValueChange:q=>C("anchor",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:j.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-16",children:"Align"}),e.jsxs(s.Select,{value:String((h==null?void 0:h.align)||"center"),onValueChange:q=>C("align",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:k.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:s.titleCase(q)},q))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(h==null?void 0:h.format)||(p?"auto":"none"),onValueChange:q=>C("format",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:D.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"&&p?"Auto (Use Axis)":q==="none"?"None (Raw Value)":s.titleCase(q)},q))})]})]}),(h==null?void 0:h.format)&&!["auto","none"].includes(h.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(h.format)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Decimals"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(((G=h==null?void 0:h.formatOptions)==null?void 0:G.decimalPlaces)??(h.format==="currency"?2:h.format==="percent"?1:0)),onSave:q=>O("decimalPlaces",Number(q)),className:""})})]}),h.format==="currency"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Currency"}),e.jsxs(s.Select,{value:((V=h==null?void 0:h.formatOptions)==null?void 0:V.currency)||"USD",onValueChange:q=>O("currency",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:P.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]}),["number","currency"].includes(h.format)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((U=h==null?void 0:h.formatOptions)==null?void 0:U.useSuffix)??!1,onCheckedChange:q=>O("useSuffix",q)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Locale"}),e.jsxs(s.Select,{value:((Q=h==null?void 0:h.formatOptions)==null?void 0:Q.locale)||"en-US",onValueChange:q=>O("locale",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(q=>e.jsx(s.SelectItem,{value:q.value,className:"text-xs",children:q.label},q.value))})]})]})]}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Appearance"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Size"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((J=h==null?void 0:h.font)==null?void 0:J.size)||12),onSave:q=>B("size",Number(q)),className:""})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Weight"}),e.jsxs(s.Select,{value:((Z=h==null?void 0:h.font)==null?void 0:Z.weight)||"normal",onValueChange:q=>B("weight",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Color"}),e.jsxs(s.Select,{value:(h==null?void 0:h.color)==="auto"||!(h!=null&&h.color)?"auto":"custom",onValueChange:q=>{q==="auto"&&C("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Smart Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom (Coming Soon)"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground w-20",children:"Rotation"}),e.jsx("div",{className:"flex-1",children:e.jsx(Te,{type:"number",placeholder:"0",value:String((h==null?void 0:h.rotation)||0),onSave:q=>C("rotation",Number(q)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}const Ps={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
179
179
  Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function dn(){var u,v,y,h,b,T,C,B,O,L;const t=s.useEditorStore(g=>g.card),{setCardPreferences:n}=s.useEditorActions(),a=ye.useEffectiveEditorCardType(),r=((u=t.config)==null?void 0:u.metricColumns)||[],i=((v=t.config)==null?void 0:v.groupByColumns)||[],c=r.length===2&&i.length===0,l=r.some(g=>g.comparisonType&&g.comparisonType!=="none");if(!(a==="kpi"&&(c||l)))return null;const o=((h=(y=t.preferences)==null?void 0:y.kpiVisualOptions)==null?void 0:h.metricComparison)||{},x=g=>{var E;const w={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...o,...g}}};n(w)},p=l||o.enabled,m=r.some(g=>g.comparisonType==="previous_period"||g.comparisonType==="same_period_last_year"||g.comparisonType==="start_vs_end");return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[c&&r.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:g=>x({enabled:g,...g&&!o.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const g=o.calculationType||"difference",w=Ps[g];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:w==null?void 0:w.label}),e.jsx("p",{children:w==null?void 0:w.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:w==null?void 0:w.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",w==null?void 0:w.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:g=>x({calculationType:g}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(Ps).map(([g,w])=>e.jsx(s.SelectItem,{value:g,className:"text-xs",children:w.label},g))})]})]}),e.jsx(qe,{formatOptions:o.formatOptions||{},onFormatOptionsChange:g=>x({formatOptions:g}),showTitle:!0,title:"COMPARISON FORMAT"}),(m||c)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"right",onValueChange:g=>x({position:g}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:o.showArrow!==!1,onCheckedChange:g=>x({showArrow:g})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:o.showColor!==!1,onCheckedChange:g=>x({showColor:g})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((b=o.colorConfig)==null?void 0:b.increase)||"green",onChange:g=>x({colorConfig:{...o.colorConfig,increase:g}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((T=o.colorConfig)==null?void 0:T.decrease)||"red",onChange:g=>x({colorConfig:{...o.colorConfig,decrease:g}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((C=o.colorConfig)==null?void 0:C.noChange)||"neutral",onChange:g=>x({colorConfig:{...o.colorConfig,noChange:g}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:o.conditionalLabel||!1,onCheckedChange:g=>x({conditionalLabel:g})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((B=o.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,increase:g.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((O=o.conditionalLabels)==null?void 0:O.decrease)??"Decrease",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,decrease:g.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.noChange)??"No change",onChange:g=>x({conditionalLabels:{...o.conditionalLabels,noChange:g.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:o.labelName??"",onChange:g=>x({labelName:g.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function un(){var c,l;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(ye.useEffectiveEditorCardType()!=="kpi")return null;const r=((l=(c=t.preferences)==null?void 0:c.kpiVisualOptions)==null?void 0:l.formatOptions)||{},i=d=>{var x;const o={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:d}};n(o)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(qe,{formatOptions:r,onFormatOptionsChange:i,showTitle:!1})})]})}function mn(){var c;const t=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.type}),n=s.useEditorStore(l=>{var d;return(d=l.card)==null?void 0:d.preferences}),{setCardPreferences:a}=s.useEditorActions();if(t!=="treemap")return null;const r=((c=n==null?void 0:n.chartOptions)==null?void 0:c.treemapColorMode)??"branch",i=l=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:l}};a(d)};return e.jsxs(s.AccordionItem,{value:"treemap-color-mode",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.TbChartTreemap,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Treemap Colors"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:e.jsxs(s.RadioGroup,{value:r,onValueChange:l=>i(l??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-branch",value:"branch"}),e.jsxs(s.Label,{htmlFor:"treemap-color-branch",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Shade by value (default)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Keeps parent hue and adjusts lightness based on the node's share within the branch."})]})]}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:"treemap-color-category",value:"category"}),e.jsxs(s.Label,{htmlFor:"treemap-color-category",className:"flex flex-col text-sm font-normal leading-tight",children:[e.jsx("span",{className:"font-medium",children:"Single color per category"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Applies the top-level color to all descendants without lightening/darkening."})]})]})]})})]})}const xn=Object.keys(s.HEATMAP_PRESET_PALETTES);function hn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var v;return(v=u.card)==null?void 0:v.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",l=i.legendPosition??"bottom",d=I.useMemo(()=>i.colorRange&&i.colorRange[0]&&i.colorRange[1]?[i.colorRange[0],i.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[i.colorRange]),o=u=>{const v={...i,...u};v.colorPalette!=="custom"?delete v.colorRange:(!v.colorRange||!v.colorRange[0]||!v.colorRange[1])&&(v.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:v})},x=u=>{o({colorPalette:u,colorRange:u==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(u,v)=>{const y=[...d];y[u]=v,o({colorPalette:"custom",colorRange:y})},m=u=>{o({legendPosition:u})};return r?e.jsxs(s.AccordionItem,{value:"heatmap-color-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Grid3x3,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Heatmap Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs(s.RadioGroup,{value:c,onValueChange:u=>x(u??"blue"),className:"space-y-3",children:[xn.map(u=>{const v=s.HEATMAP_PRESET_PALETTES[u];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${u}`,value:u}),e.jsxs(s.Label,{htmlFor:`heatmap-${u}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:v.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${v.start}, ${v.end})`}})]})]},u)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),c==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Le,{value:d[0],onChange:u=>p(0,u),label:"Start color"}),e.jsx(Le,{value:d[1],onChange:u=>p(1,u),label:"End color"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Color scale position"}),e.jsxs(s.Select,{value:l,onValueChange:u=>m(u??"bottom"),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:["top","bottom","left","right"].map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:u[0].toUpperCase()+u.slice(1)},u))})]})]})]})]}):null}const Vs=["poor","satisfactory","good"];function zs(t){if(!t)return;const n={...t};return n.targetMetricKey||delete n.targetMetricKey,n.comparativeMetricKey||delete n.comparativeMetricKey,!n.targetValue&&n.targetValue!==0&&delete n.targetValue,(!n.rangeKeys||Object.keys(n.rangeKeys).length===0)&&delete n.rangeKeys,(!n.ranges||Object.keys(n.ranges).length===0)&&delete n.ranges,(!n.rangeLabels||Object.keys(n.rangeLabels).length===0)&&delete n.rangeLabels,n}function pn(){var D,P;const t=s.useEditorStore(N=>N.card.preferences),n=s.useEditorStore(N=>N.card),a=s.useEditorStore(N=>N.isDevMode),{setCardPreferences:r,setChartOrientation:i}=s.useEditorActions(),c=I.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),d=s.hasValidCardConfig(n==null?void 0:n.config)&&!a,[o,x]=I.useState(c.showRanges??!1),[p,m]=I.useState(c.rangesArePercentages??!1),u=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[v,y]=I.useState(u);I.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),I.useEffect(()=>{m(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const h=c.targetValue===void 0?"":String(c.targetValue);I.useEffect(()=>{const N=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;y(N)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const b=I.useMemo(()=>{var N,A;return((A=(N=n==null?void 0:n.config)==null?void 0:N.metricColumns)==null?void 0:A.map(S=>{const R=S.label||S.name||S.alias||"";return{value:R,label:R}}))||[]},[(D=n==null?void 0:n.config)==null?void 0:D.metricColumns]);I.useEffect(()=>{var V,U;if(!t||b.length===0)return;const N={};let A=!1;const S=(V=b[1])==null?void 0:V.value;!c.targetMetricKey&&S&&(N.targetMetricKey=S,A=!0);const R=(U=b[2])==null?void 0:U.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&R&&(N.comparativeMetricKey=R,A=!0);const F=b.slice(3),z={...c.rangeKeys||{}};let G=!1;if(Vs.forEach((Q,J)=>{!z[Q]&&F[J]&&(z[Q]=F[J].value,G=!0)}),G&&(N.rangeKeys=z,A=!0,c.showRanges===void 0&&(N.showRanges=!0)),A){const Q=zs({...c,...N});r({...t,bulletConfig:Q})}},[b,c,t,r]);const T=N=>{const A=zs({...c,...N});r({...t,bulletConfig:A})},C=(N,A)=>{const S={...c.rangeKeys||{},[N]:A.trim()};A.trim()||delete S[N],T({rangeKeys:Object.keys(S).length>0?S:void 0})},B=(N,A)=>{const S=A===""?void 0:Number(A),R={...c.ranges||{}};S===void 0||Number.isNaN(S)?delete R[N]:R[N]=S,T({ranges:Object.keys(R).length?R:void 0})},O=N=>{if(N===""){T({targetValue:void 0});return}const A=Number(N);T({targetValue:Number.isNaN(A)?void 0:A})},L=(N,A)=>{const S=A.trim(),R={...c.rangeLabels||{}};S?R[N]=S:delete R[N],T({rangeLabels:Object.keys(R).length>0?R:void 0})},g=N=>{x(N),T({showRanges:N})},w=N=>{m(N),T({rangesArePercentages:N})},E=c.orientation||(((P=t==null?void 0:t.chartOptions)==null?void 0:P.indexAxis)==="y"?"horizontal":"vertical"),f=N=>{T({orientation:N}),i(N==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...b.map(N=>({value:N.value,label:N.label}))],j=M,k=N=>{if(y(N),!N){T({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){T({disableAutoComparative:!1});return}if(c.comparativeMetricKey)T({disableAutoComparative:!1});else{const A=b.find(S=>S.value!==c.targetMetricKey);T({comparativeMetricKey:A==null?void 0:A.value,disableAutoComparative:!1})}};return e.jsxs(s.AccordionItem,{value:"bullet-config",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.BulletChartIcon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bullet Chart"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-6 border-t border-border/50 py-4",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"ORIENTATION"}),e.jsxs(s.Select,{value:E,onValueChange:N=>f(N),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"horizontal",className:"text-xs",children:"Horizontal"}),e.jsx(s.SelectItem,{value:"vertical",className:"text-xs",children:"Vertical"})]})]})]}),d&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET METRIC"}),e.jsxs(s.Select,{value:c.targetMetricKey||"__none",onValueChange:N=>T({targetMetricKey:N==="__none"?void 0:N}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"__none",className:"text-xs",children:"None"}),b.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),d?e.jsxs(s.Select,{value:c.comparativeMetricKey||"__none",onValueChange:N=>T({comparativeMetricKey:N==="__none"?void 0:N,disableAutoComparative:N==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:M.map(N=>e.jsx(s.SelectItem,{value:N.value,className:"text-xs",children:N.label},N.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:v,onCheckedChange:N=>k(N)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Se,{type:"number",className:"h-8 text-xs",value:h,onCommit:O,placeholder:"Optional numeric fallback"})]})]}),e.jsxs("section",{className:"space-y-4 rounded-md border border-border/60 p-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"QUALITATIVE RANGES"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:200,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(s.Info,{className:"h-3.5 w-3.5"})})}),e.jsx(s.TooltipContent,{side:"top",children:"Use columns or static values for Poor / Average / Good."})]})})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs font-medium",children:e.jsx(s.SmallSwitch,{checked:o,onCheckedChange:g})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!o,onChange:N=>w(N.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),o&&e.jsx("div",{className:"space-y-3",children:Vs.map(N=>{var A,S,R,F,z;return e.jsxs("div",{className:"space-y-2 rounded-md border border-border/60 bg-muted/40 p-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," LABEL"]}),e.jsx(Se,{placeholder:`Display label (${N})`,value:((A=c.rangeLabels)==null?void 0:A[N])||"",onCommit:G=>L(N,G),className:"h-8 text-xs"})]}),d?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN"]}),e.jsxs(s.Select,{value:((S=c.rangeKeys)==null?void 0:S[N])||"__none",onValueChange:G=>{G==="__none"?C(N,""):C(N,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:j.map(G=>e.jsx(s.SelectItem,{value:G.value,className:"text-xs",children:G.label},G.value))})]})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," COLUMN KEY"]}),e.jsx(Se,{placeholder:"Column key",value:((R=c.rangeKeys)==null?void 0:R[N])||"",onCommit:G=>C(N,G),className:"h-8 text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[N," VALUE"]}),e.jsx(Se,{type:"number",placeholder:p?"0.80":"Static value",value:((F=c.ranges)==null?void 0:F[N])===void 0?"":String((z=c.ranges)==null?void 0:z[N]),onCommit:G=>B(N,G),className:"h-8 text-xs"})]})]},N)})})]})]})]})}function $s(t){if(!t)return;const n={...t};if(n.xMetricKey||delete n.xMetricKey,n.yMetricKey||delete n.yMetricKey,n.radiusMetricKey||delete n.radiusMetricKey,n.labelKey||delete n.labelKey,n.groupKey||delete n.groupKey,n.enableGrouping===void 0&&delete n.enableGrouping,n.radiusScale||delete n.radiusScale,n.fixedRadius===void 0&&delete n.fixedRadius,n.minRadius===void 0&&delete n.minRadius,n.maxRadius===void 0&&delete n.maxRadius,Object.keys(n).length!==0)return n}function fn(){var L,g,w,E,f,M,j,k,D,P,N,A;const t=s.useEditorStore(S=>S.card.preferences),n=s.useEditorStore(S=>S.card),a=ye.useEffectiveEditorCardType(),r=s.useEditorStore(S=>S.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions(),l=a==="bubble",d=a==="scatter",o=I.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,m=I.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.metricColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(L=n==null?void 0:n.config)==null?void 0:L.metricColumns]),u=I.useMemo(()=>{var S,R;return((R=(S=n==null?void 0:n.config)==null?void 0:S.groupByColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(g=n==null?void 0:n.config)==null?void 0:g.groupByColumns]),v=I.useMemo(()=>o.enableGrouping!==void 0?o.enableGrouping:!r&&u.length>=2,[o.enableGrouping,r,u.length]),[y,h]=I.useState(v);I.useEffect(()=>{h(v)},[v]);const b=S=>{const R={...t||{},bubbleScatterConfig:S};i(R),n&&c({...n,preferences:R})},T=S=>{i(S),n&&c({...n,preferences:S})};I.useEffect(()=>{if(!t||m.length===0)return;const S={};let R=!1;if(!o.xMetricKey&&m[0]&&(S.xMetricKey=m[0].value,R=!0),!o.yMetricKey&&m[1]&&(S.yMetricKey=m[1].value,R=!0),l&&!o.radiusMetricKey&&m[2]&&(S.radiusMetricKey=m[2].value,R=!0),!o.labelKey&&u[0]&&(S.labelKey=u[0].value,R=!0),v&&!o.groupKey&&u[1]&&(S.groupKey=u[1].value,S.enableGrouping=!0,R=!0),R){const F=$s({...o,...S});b(F)}},[m,u,o,t,i,l,v]);const C=S=>{const R=$s({...o,...S});b(R)},B=S=>{h(S),C({enableGrouping:S,groupKey:S?o.groupKey:void 0})};if(!l&&!d)return null;const O=l?s.Circle:s.ChartScatter;return e.jsxs(s.AccordionItem,{value:"bubble-scatter-config",children:[e.jsx(s.AccordionTrigger,{className:"py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsxs("span",{children:[l?"Bubble":"Scatter"," Configuration"]})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-1 pb-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-muted-foreground",children:["Dimensions",e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{children:e.jsx(s.Info,{className:"h-3 w-3"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Label identifies each point. Group creates separate series in the legend."})})]})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Label Column"}),p?e.jsxs(s.Select,{value:o.labelKey||"",onValueChange:S=>C({labelKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for labels",value:o.labelKey||"",onCommit:S=>C({labelKey:S})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Group points into series"}),e.jsx(s.SmallSwitch,{checked:y,onCheckedChange:B})]}),y&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Group By"}),p?e.jsxs(s.Select,{value:o.groupKey||"",onValueChange:S=>C({groupKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:u.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:o.groupKey||"",onCommit:S=>C({groupKey:S})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Metrics"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Axis"}),p?e.jsxs(s.Select,{value:o.xMetricKey||"",onValueChange:S=>C({xMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:o.xMetricKey||"",onCommit:S=>C({xMetricKey:S})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:o.yMetricKey||"",onValueChange:S=>C({yMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:o.yMetricKey||"",onCommit:S=>C({yMetricKey:S})})]}),l&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:o.radiusMetricKey||"",onValueChange:S=>C({radiusMetricKey:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:m.map(S=>e.jsx(s.SelectItem,{value:S.value,children:S.label},S.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for radius",value:o.radiusMetricKey||"",onCommit:S=>C({radiusMetricKey:S})})]})]}),l&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:o.radiusScale||"sqrt",onValueChange:S=>C({radiusScale:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"sqrt",children:"Square Root (area-proportional)"}),e.jsx(s.SelectItem,{value:"linear",children:"Linear"}),e.jsx(s.SelectItem,{value:"fixed",children:"Fixed Size"})]})]})]}),o.radiusScale!=="fixed"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Min Radius"}),e.jsx(Se,{className:"h-8 text-xs",type:"number",placeholder:"5",value:((w=o.minRadius)==null?void 0:w.toString())||"",onCommit:S=>C({minRadius:S?Number(S):void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Max Radius"}),e.jsx(Se,{className:"h-8 text-xs",type:"number",placeholder:"30",value:((E=o.maxRadius)==null?void 0:E.toString())||"",onCommit:S=>C({maxRadius:S?Number(S):void 0})})]})]}),o.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",o.fixedRadius||10]}),e.jsx(s.Slider,{value:[o.fixedRadius||10],onValueChange:([S])=>C({fixedRadius:S}),min:3,max:30,step:1,className:"py-2"})]})]}),d&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Point Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Point Size: ",o.fixedRadius||5]}),e.jsx(s.Slider,{value:[o.fixedRadius||5],onValueChange:([S])=>C({fixedRadius:S}),min:2,max:15,step:1,className:"py-2"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Axis Titles"}),e.jsx(s.SmallSwitch,{checked:((M=(f=t==null?void 0:t.xAxisConfig)==null?void 0:f.name)==null?void 0:M.enabled)??!1,onCheckedChange:S=>{var z,G,V,U;const R=o.xMetricKey||"X Axis",F=o.yMetricKey||"Y Axis";T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:S,text:((G=(z=t==null?void 0:t.xAxisConfig)==null?void 0:z.name)==null?void 0:G.text)||R}},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{enabled:S,text:((U=(V=t==null?void 0:t.yAxisConfig)==null?void 0:V.name)==null?void 0:U.text)||F}}})}})]}),((k=(j=t==null?void 0:t.xAxisConfig)==null?void 0:j.name)==null?void 0:k.enabled)&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"X Title"}),e.jsx(Se,{className:"h-8 text-xs",placeholder:o.xMetricKey||"X Axis",value:((P=(D=t==null?void 0:t.xAxisConfig)==null?void 0:D.name)==null?void 0:P.text)||"",onCommit:S=>{var R;T({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.xMetricKey||"X Axis"}}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Title"}),e.jsx(Se,{className:"h-8 text-xs",placeholder:o.yMetricKey||"Y Axis",value:((A=(N=t==null?void 0:t.yAxisConfig)==null?void 0:N.name)==null?void 0:A.text)||"",onCommit:S=>{var R;T({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:S||o.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const gn=[{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 jn(){const t=s.useEditorStore(u=>u.card),n=s.useEditorStore(u=>{var v;return(v=u.card)==null?void 0:v.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",l=i.shrinkFraction??1,d=i.labelThreshold??0,o=u=>{const v={...i,...u};a({...n||{},funnelConfig:v})},x=u=>{o({percentMode:u})},p=u=>{o({shrinkFraction:u[0]})},m=u=>{o({labelThreshold:u[0]})};return r?e.jsxs(s.AccordionItem,{value:"funnel-config",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-3 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Filter,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Funnel Settings"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 border-t border-border bg-background/50 px-3 py-4 text-sm",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"PERCENTAGE MODE"}),e.jsx(s.RadioGroup,{value:c,onValueChange:u=>x(u),className:"space-y-2",children:gn.map(u=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`funnel-${u.value}`,value:u.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${u.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:u.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u.description})]})]},u.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[l],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(l*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Slider,{value:[d],onValueChange:m,min:0,max:25,step:1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Hide Small"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:d===0?"Showing all labels":`Hide labels below ${d}%`})]})]})]}):null}function Ke(){const t=s.useEditorStore(c=>c.card),{data:n}=s.useDashboardCardQuery(t),{keys:a}=s.getKeys((n==null?void 0:n.records)||[]),r=a.slice(1).filter(c=>!s.METADATA_KEYS.includes(c));let i=r;if(["stackedBar","stackedLine"].includes(t.type)){const c=s.pivotData({dataArray:(n==null?void 0:n.records)||[],groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:l}=s.getKeys(c);i=l.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const bn=[{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"}],yn=[{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)"}],vn=["center","start","end"],Nn=["center","start","end","top","bottom"];function Ge({config:t,onChange:n,isHorizontal:a=!1,showAutoFormat:r=!0,positionOptions:i,showAppearance:c=!0}){var y,h,b,T,C,B;const l=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],o=(O,L)=>{const g={...t,[O]:L};n(g)},x=(O,L)=>{const g={...t,font:{...(t==null?void 0:t.font)||{},[O]:L}};n(g)},p=(O,L)=>{const g={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[O]:L}};n(g)},m=()=>a?"Right":"Top",u=t||{},v=u.format||(r?"auto":"number");return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:u.position||"auto",onValueChange:O=>o("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:l.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?m():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),u.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(s.Label,{className:"text-xs",children:"Anchor"}),e.jsxs(s.Select,{value:u.anchor||"center",onValueChange:O=>o("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:vn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Align"}),e.jsxs(s.Select,{value:String(u.align||"center"),onValueChange:O=>o("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Nn.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Format"}),e.jsxs(s.Select,{value:v,onValueChange:O=>o("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&r?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),!["auto","none"].includes(v)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(v)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Decimals"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"0",value:String(((y=u.formatOptions)==null?void 0:y.decimalPlaces)??(v==="currency"?2:v==="percent"?1:0)),onSave:O=>p("decimalPlaces",Number(O)),className:""})})]}),v==="currency"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Currency"}),e.jsxs(s.Select,{value:((h=u.formatOptions)==null?void 0:h.currency)||"USD",onValueChange:O=>p("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:bn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(v)&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Abbreviate (K, M, B)"}),e.jsx(s.SmallSwitch,{checked:((b=u.formatOptions)==null?void 0:b.useSuffix)??!1,onCheckedChange:O=>p("useSuffix",O)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Locale"}),e.jsxs(s.Select,{value:((T=u.formatOptions)==null?void 0:T.locale)||"en-US",onValueChange:O=>p("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:yn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.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(s.Label,{className:"text-xs",children:"Size"}),e.jsx("div",{className:"w-16",children:e.jsx(Te,{type:"number",placeholder:"12",value:String(((C=u.font)==null?void 0:C.size)||12),onSave:O=>x("size",Number(O)),className:""})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Weight"}),e.jsxs(s.Select,{value:((B=u.font)==null?void 0:B.weight)||"normal",onValueChange:O=>x("weight",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"normal",className:"text-xs",children:"Normal"}),e.jsx(s.SelectItem,{value:"bold",className:"text-xs",children:"Bold"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs",children:"Color"}),e.jsxs(s.Select,{value:u.color==="auto"||!u.color?"auto":"custom",onValueChange:O=>{O==="auto"&&o("color","auto")},children:[e.jsx(s.SelectTrigger,{className:"h-7 w-28 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"auto",className:"text-xs",children:"Auto (Contrast)"}),e.jsx(s.SelectItem,{value:"custom",disabled:!0,className:"text-xs",children:"Custom"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.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(Te,{type:"number",placeholder:"0",value:String(u.rotation||0),onSave:O=>o("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const Cn=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],Sn=[0,1,2,3,4,5,6,8,10],wn=[{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 │"}],Tn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function En(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="combo"?null:e.jsxs(s.AccordionItem,{value:"combo-series",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(In,{})})]})}function In(){const{transformedMetricKeys:t}=Ke();return t.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:t.map((n,a)=>e.jsx(kn,{metricKey:n,idx:a},n))})}function kn({metricKey:t,idx:n}){var T;const[a,r]=I.useState(!1),i=s.useEditorStore(C=>{var B;return(B=C.card)==null?void 0:B.preferences}),c=s.useEditorStore(C=>{var B,O;return(O=(B=C.card)==null?void 0:B.preferences)==null?void 0:O.datasetOptions}),l=c==null?void 0:c.find(C=>C.idx===n),{setCardPreferences:d}=s.useEditorStore(C=>C.actions),o=(l==null?void 0:l.type)||"bar",x=(l==null?void 0:l.yAxisId)||"y",p=((T=l==null?void 0:l.dataLabels)==null?void 0:T.enabled)??!1,m=o==="line"?s.ChartLine:s.ChartColumnIncreasing;function u(C){const B={idx:n,type:o,yAxisId:x,dataLabels:l==null?void 0:l.dataLabels,...C};if(!l)d({...i||{},datasetOptions:[...c||[],B]});else{const O=c==null?void 0:c.map(L=>L.idx===n?{...L,...B}:L);d({...i||{},datasetOptions:O})}}function v(C){u({type:C})}function y(C){u({yAxisId:C})}function h(C){u({dataLabels:{...l==null?void 0:l.dataLabels,enabled:C}})}function b(C){u({dataLabels:C})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.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(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsxs("span",{className:s.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(m,{className:"h-3 w-3"}),o==="line"?"Line":"Bar"]}),e.jsx("span",{className:s.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(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Chart Type"}),e.jsx("div",{className:"flex gap-2",children:Cn.map(({type:C,icon:B,label:O})=>{const L=o===C;return e.jsxs("button",{onClick:()=>v(C),className:s.cn("flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors",L?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:[e.jsx(B,{className:"h-4 w-4"}),e.jsx("span",{children:O})]},C)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Axis"}),e.jsxs(s.Select,{value:x,onValueChange:C=>y(C),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"y",className:"text-xs",children:"Y1 (Left)"}),e.jsx(s.SelectItem,{value:"y2",className:"text-xs",children:"Y2 (Right)"})]})]})]})]}),o==="line"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:C=>u({lineStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Tn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:C=>u({pointRadius:Number(C)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Sn.map(C=>e.jsx(s.SelectItem,{value:String(C),className:"text-xs",children:C===0?"None":C},C))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:C=>u({pointStyle:C}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:wn.map(({value:C,label:B})=>e.jsx(s.SelectItem,{value:C,className:"text-xs",children:B},C))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:b,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const es=[{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"}],An=[0,1,2,3,4,5,6,8,10],Dn=[{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 │"}],Ln=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Mn(t){return t==null?"origin":t===!1?"false":t}function On(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return t!=="area"&&t!=="stackedArea"?null:e.jsxs(s.AccordionItem,{value:"area-series",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Fn,{})})]})}function Fn(){const{transformedMetricKeys:t}=Ke();return t.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:t.map((n,a)=>e.jsx(Rn,{metricKey:n,idx:a},n))})}function Rn({metricKey:t,idx:n}){var h;const[a,r]=I.useState(!1),i=s.useEditorStore(b=>{var T;return(T=b.card)==null?void 0:T.preferences}),c=s.useEditorStore(b=>{var T,C;return(C=(T=b.card)==null?void 0:T.preferences)==null?void 0:C.datasetOptions}),l=c==null?void 0:c.find(b=>b.idx===n),{setCardPreferences:d}=s.useEditorStore(b=>b.actions),o=Mn(l==null?void 0:l.fill),x=((h=l==null?void 0:l.dataLabels)==null?void 0:h.enabled)??!1,p=es.find(b=>b.value===o)||es[0];function m(b){const T={idx:n,fill:o,dataLabels:l==null?void 0:l.dataLabels,...b};if(!l)d({...i||{},datasetOptions:[...c||[],T]});else{const C=c==null?void 0:c.map(B=>B.idx===n?{...B,...T}:B);d({...i||{},datasetOptions:C})}}function u(b){m({fill:b==="false"?!1:b})}function v(b){m({dataLabels:{...l==null?void 0:l.dataLabels,enabled:b}})}function y(b){m({dataLabels:b})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.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(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.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(s.ChartArea,{className:"h-3 w-3"}),p.label.split(" ")[0]]})})]})}),e.jsx(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Fill Target"}),e.jsxs(s.Select,{value:o,onValueChange:b=>u(b),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:es.map(b=>e.jsx(s.SelectItem,{value:b.value,className:"text-xs",children:e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{children:b.label})})},b.value))})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:(l==null?void 0:l.lineStyle)||"solid",onValueChange:b=>m({lineStyle:b}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Ln.map(({value:b,label:T})=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:T},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String((l==null?void 0:l.pointRadius)??3),onValueChange:b=>m({pointRadius:Number(b)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:An.map(b=>e.jsx(s.SelectItem,{value:String(b),className:"text-xs",children:b===0?"None":b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:(l==null?void 0:l.pointStyle)||"circle",onValueChange:b=>m({pointStyle:b}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Dn.map(({value:b,label:T})=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:T},b))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:v})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bn=[0,1,2,3,4,5,6,8,10],Pn=[{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 │"}],ss=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Vn(){return s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type})!=="line"?null:e.jsxs(s.AccordionItem,{value:"line-series",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(zn,{})})]})}function zn(){const{transformedMetricKeys:t}=Ke();return t.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:t.map((n,a)=>e.jsx($n,{metricKey:n,idx:a},n))})}function $n({metricKey:t,idx:n}){var b;const[a,r]=I.useState(!1),i=s.useEditorStore(T=>{var C;return(C=T.card)==null?void 0:C.preferences}),c=s.useEditorStore(T=>{var C,B;return(B=(C=T.card)==null?void 0:C.preferences)==null?void 0:B.datasetOptions}),l=c==null?void 0:c.find(T=>T.idx===n),{setCardPreferences:d}=s.useEditorStore(T=>T.actions),o=(l==null?void 0:l.lineStyle)||"solid",x=(l==null?void 0:l.pointRadius)??3,p=(l==null?void 0:l.pointStyle)||"circle",m=((b=l==null?void 0:l.dataLabels)==null?void 0:b.enabled)??!1,u=ss.find(T=>T.value===o)||ss[0];function v(T){const C={idx:n,lineStyle:o,pointRadius:x,pointStyle:p,dataLabels:l==null?void 0:l.dataLabels,...T};if(!l)d({...i||{},datasetOptions:[...c||[],C]});else{const B=c==null?void 0:c.map(O=>O.idx===n?{...O,...C}:O);d({...i||{},datasetOptions:B})}}function y(T){v({dataLabels:{...l==null?void 0:l.dataLabels,enabled:T}})}function h(T){v({dataLabels:T})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.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(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsxs("span",{className:s.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(s.TrendingUp,{className:"h-3 w-3"}),u.label.split(" ")[0]]})})]})}),e.jsx(s.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(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Pattern"}),e.jsxs(s.Select,{value:o,onValueChange:T=>v({lineStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:ss.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Size"}),e.jsxs(s.Select,{value:String(x),onValueChange:T=>v({pointRadius:Number(T)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Bn.map(T=>e.jsx(s.SelectItem,{value:String(T),className:"text-xs",children:T===0?"None":T},T))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Point Shape"}),e.jsxs(s.Select,{value:p,onValueChange:T=>v({pointStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Pn.map(({value:T,label:C})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:C},T))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:m,onCheckedChange:y})]}),m&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:l==null?void 0:l.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const qn=[0,2,4,6,8,10,12,16,20];function Kn(){const t=s.useEditorStore(n=>{var a;return(a=n.card)==null?void 0:a.type});return!t||!["bar","horizontalBar","stackedBar"].includes(t)?null:e.jsxs(s.AccordionItem,{value:"bar-series",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Layers,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Series"})]})}),e.jsx(s.AccordionContent,{className:"pt-2",children:e.jsx(Gn,{})})]})}function Gn(){const{transformedMetricKeys:t}=Ke();return t.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:t.map((n,a)=>e.jsx(Un,{metricKey:n,idx:a},n))})}function Un({metricKey:t,idx:n}){var y;const[a,r]=I.useState(!1),i=s.useEditorStore(h=>{var b;return(b=h.card)==null?void 0:b.type}),c=s.useEditorStore(h=>{var b;return(b=h.card)==null?void 0:b.preferences}),l=s.useEditorStore(h=>{var b,T;return(T=(b=h.card)==null?void 0:b.preferences)==null?void 0:T.datasetOptions}),d=l==null?void 0:l.find(h=>h.idx===n),{setCardPreferences:o}=s.useEditorStore(h=>h.actions),x=(d==null?void 0:d.borderRadius)??0,p=((y=d==null?void 0:d.dataLabels)==null?void 0:y.enabled)??!1;function m(h){const b={idx:n,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...h};if(!d)o({...c||{},datasetOptions:[...l||[],b]});else{const T=l==null?void 0:l.map(C=>C.idx===n?{...C,...b}:C);o({...c||{},datasetOptions:T})}}function u(h){m({dataLabels:{...d==null?void 0:d.dataLabels,enabled:h}})}function v(h){m({dataLabels:h})}return e.jsx(s.Collapsible,{open:a,onOpenChange:r,children:e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30",children:[e.jsx(s.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(s.ChevronRight,{className:s.cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90")}),e.jsx("span",{className:"max-w-[100px] truncate text-xs font-medium",title:t,children:t})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:x>0&&e.jsxs("span",{className:s.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(s.ChartColumn,{className:"h-3 w-3"}),"r:",x]})})]})}),e.jsx(s.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(s.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(s.Label,{className:"text-xs text-muted-foreground",children:"Corner Radius"}),e.jsxs(s.Select,{value:String(x),onValueChange:h=>m({borderRadius:Number(h)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:qn.map(h=>e.jsx(s.SelectItem,{value:String(h),className:"text-xs",children:h===0?"None":`${h}px`},h))})]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:u})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:d==null?void 0:d.dataLabels,onChange:v,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const _n=[0,1,2,3,4,5,6,8,10],Hn=[{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 │"}],Jn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Yn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const l=(d,o)=>{const x={...n||{},lineStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"line-style",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Line Style"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Line Pattern"}),e.jsxs(s.Select,{value:(r==null?void 0:r.lineStyle)||"solid",onValueChange:d=>l("lineStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Jn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Size"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.pointRadius)??3),onValueChange:d=>l("pointRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:_n.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":d},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Point Shape"}),e.jsxs(s.Select,{value:(r==null?void 0:r.pointStyle)||"circle",onValueChange:d=>l("pointStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Hn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}const Qn=[0,2,4,6,8,10,12,16,20],Wn=[{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%"}],Xn=[{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 Zn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var o;return(o=d.card)==null?void 0:o.preferences}),a=ye.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const l=(d,o)=>{const x={...n||{},barStyleConfig:{...r,[d]:o}};i(x),c({...t,preferences:x})};return e.jsxs(s.AccordionItem,{value:"bar-style",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ChartColumn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"Bar Style"})]})}),e.jsx(s.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(s.Label,{className:"text-xs font-medium",children:"Corner Radius"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.borderRadius)??0),onValueChange:d=>l("borderRadius",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Qn.map(d=>e.jsx(s.SelectItem,{value:String(d),className:"text-xs",children:d===0?"None":`${d}px`},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Bar Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.barPercentage)??.9),onValueChange:d=>l("barPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Wn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Category Width"}),e.jsxs(s.Select,{value:String((r==null?void 0:r.categoryPercentage)??.8),onValueChange:d=>l("categoryPercentage",Number(d)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Xn.map(({value:d,label:o})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:o},d))})]})]})]})})]})}function er(){const t=s.useEditorStore(a=>{var r,i;return(i=(r=a==null?void 0:a.card)==null?void 0:r.preferences)==null?void 0:i.sortChart}),{setSortChart:n}=s.useEditorActions();return e.jsxs(s.AccordionItem,{value:"stacked-sort",children:[e.jsx(s.AccordionTrigger,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.ArrowUpDown,{className:"h-4 w-4"}),"Sort"]})}),e.jsx(s.AccordionContent,{className:"space-y-4 px-1",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort Order"}),e.jsx(De,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"Ascending",value:"asc"},{label:"Descending",value:"desc"}],value:t||"none",onValueChange:a=>{n(a)}})]})})]})}const sr=["kpi"],qs={none:"None",previous_period:"Previous Period",same_period_last_year:"Same Period Last Year",start_vs_end:"Start vs End",target:"Target"},ts=2;function Re(t){return typeof t=="string"?t.trim().toLowerCase():((t==null?void 0:t.id)||(t==null?void 0:t.qualifiedFieldName)||(t==null?void 0:t.name)||(t==null?void 0:t.label)||"").trim().toLowerCase()}function tr(t){if(!(t!=null&&t.name)||!(t!=null&&t.dataType)||t.role==="metric")return!1;const n=s.getDataType(t.dataType);return["date","string","boolean"].includes(n)}function ar(t){return{...t,role:"groupby"}}function nr(){var C,B,O,L;const t=s.useEditorStore(g=>g.card),n=s.useEditorStore(g=>g.actions.updateCardConfig),a=ye.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((C=t.config)==null?void 0:C.metricColumns)||[],c=((B=t.config)==null?void 0:B.summary)||{},l=c.breakdownDimensions||[],d=sr.includes(a),o=i.length>0,x=c.enabled===!0,p=d&&o,m=((O=t.config)==null?void 0:O.comparisonType)||((L=i.find(g=>g.comparisonType&&g.comparisonType!=="none"))==null?void 0:L.comparisonType)||"none",u=qs[m]||qs.none,v=Array.from(new Map(r.filter(tr).map(g=>[Re(g),ar(g)])).values()),y=new Set(v.map(g=>Re(g))),h=new Set(l.map(g=>Re(g)).filter(g=>g&&y.has(g)));if(!d)return null;const b=g=>{n(t.id,{summary:{...c,...g}})},T=(g,w)=>{const E=Re(g),f=v.filter(j=>h.has(Re(j))),M=w?h.has(E)?f:[...f,g].slice(0,ts):f.filter(j=>Re(j)!==E);b({breakdownDimensions:M})};return e.jsxs(s.AccordionItem,{value:"summary",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.FileText,{className:"h-4 w-4"}),e.jsx("span",{children:"Summary"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{htmlFor:"summary-enabled",className:"text-xs",children:"Enable Summary"}),!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add at least one metric to enable summary."})]}),e.jsx(s.SmallSwitch,{id:"summary-enabled",checked:x,disabled:!p,onCheckedChange:g=>{if(!g){b({enabled:!1,showOnCard:!1,includeInDashboardSummary:!1});return}b({enabled:!0,showOnCard:c.showOnCard??!0,includeInDashboardSummary:c.includeInDashboardSummary??!0,anomalyEnabled:c.anomalyEnabled??!0})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Comparison"}),e.jsxs("p",{className:"rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs",children:["Using: ",u]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparison is configured from card/metric comparison settings."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-show-on-card",className:"text-xs",children:"Show summary on card"}),e.jsx(s.SmallSwitch,{id:"summary-show-on-card",checked:c.showOnCard===!0,disabled:!x,onCheckedChange:g=>b({showOnCard:g})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-include-rollup",className:"text-xs",children:"Include in dashboard summary"}),e.jsx(s.SmallSwitch,{id:"summary-include-rollup",checked:c.includeInDashboardSummary===!0,disabled:!x,onCheckedChange:g=>b({includeInDashboardSummary:g})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Breakdown Dimensions"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.length,"/",ts]})]}),v.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No dimension fields available for breakdown."}):e.jsx("div",{className:"max-h-40 space-y-2 overflow-y-auto rounded-md border border-border p-2",children:v.map(g=>{const w=Re(g),E=h.has(w),f=h.size>=ts,M=!x||!E&&f;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx(s.Checkbox,{id:`summary-breakdown-${w}`,checked:E,disabled:M,onCheckedChange:j=>T(g,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:g.label||g.name})]},w)})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"summary-anomaly",className:"text-xs",children:"Detect anomalies"}),e.jsx(s.SmallSwitch,{id:"summary-anomaly",checked:c.anomalyEnabled!==!1,disabled:!x,onCheckedChange:g=>b({anomalyEnabled:g})})]})]})]})}function ct({mode:t}){const n=s.useEditorStore(a=>{var r;return(r=a.card)==null?void 0:r.type});return e.jsxs(e.Fragment,{children:[n==="combo"&&e.jsx(En,{}),(n==="area"||n==="stackedArea")&&e.jsx(On,{}),n==="line"&&e.jsx(Vn,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Kn,{}),e.jsx(Yn,{}),e.jsx(Zn,{}),e.jsx(mn,{}),t==="config"&&e.jsx(un,{}),t==="config"&&e.jsx(dn,{}),t==="config"&&e.jsx(nr,{}),e.jsx(hn,{}),n==="bullet"&&e.jsx(pn,{}),n==="funnel"&&e.jsx(jn,{}),(n==="bubble"||n==="scatter")&&e.jsx(fn,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(er,{}),e.jsx(rn,{}),e.jsx(ln,{}),e.jsx(on,{}),e.jsx(cn,{})]})}function rr(){const t=s.useEditorStore(a=>a.card),n=t==null?void 0:t.type;return n?e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx($e,{chartType:n}),e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:e.jsx(ct,{mode:"dev"})})]}):null}function lr(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(Va,{});case"table":return e.jsx(sn,{});case"map":return e.jsx(Ka,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(lt,{})});case"text":return e.jsx(an,{});default:return e.jsx(rr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function or(){const t=I.useRef(null),n=I.useRef(null),a=s.useEditorStore(i=>i.isShowingVisual),r=s.useEditorStore(i=>i.showAIDialog);return I.useEffect(()=>{var i,c,l,d;r?((i=t.current)==null||i.resize(0),(c=n.current)==null||c.resize(0)):((l=t.current)==null||l.resize(25),(d=n.current)==null||d.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(ma,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(lr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ms,{})})]}):e.jsx(Ms,{})})]})}function ir(t){var he;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=I.useState(""),[r,i]=I.useState(null),{authToken:c,tokenProps:l}=s.useSemaphorContext(),d=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.sql}),o=s.useEditorStore($=>$.isDevMode),x=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.python}),{setCardPython:p,setCardSql:m,setRunSql:u,switchCardType:v,setQueryConfig:y}=s.useEditorActions(),h=s.useEditorStore($=>$.currentAssitantScope)||[],b=s.useEditorStore($=>$.userInputForAI),T=s.useEditorStore($=>$.triggerAIRun),C=s.useEditorStore($=>$.card),B=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),L=s.useEditorStore($=>$.selectedConnectionId),g=s.useEditorStore($=>$.selectedSchemaName),w=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:E,refetch:f,data:M}=s.useDashboardCardQuery(C),{setTriggerAIRun:j,setCurrentAssitantScope:k,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:P,connectionType:N,selectedDatamodelId:A}=s.useEditorAside(),S=(he=s.useDashboardQuery().data)==null?void 0:he.assistantProfileId,{messages:R,setMessages:F,regenerate:z,error:G,sendMessage:V,status:U,addToolResult:Q,stop:J,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${l.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const $=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:S,isDevMode:o,aiContext:$.currentAIContext,reasoningEffort:$.reasoningEffort,showReasoning:$.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:$,body:H})=>({body:{...H,messages:s.cleanupIncompleteMessages($)}})}),onError:$=>{var H;if($.name==="AbortError"||(H=$.message)!=null&&H.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",$)},onToolCall:q,onFinish({isAbort:$,isDisconnect:H,isError:ae}){a(""),console.log($?"[Editor Assistant] Stream aborted by user":H?"[Editor Assistant] Stream disconnected (network error)":ae?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});I.useEffect(()=>{T&&b&&(V({role:"user",parts:[{type:"text",text:b}]}),j(!1))},[T,b,V,j]);async function q({toolCall:$}){var H,ae,ie,ge,je,ve,Ne,Ie,X,oe,ue,xe,we,Ce,Me,Oe;if(["createChartFromSql","createForecast"].includes($.toolName)){const te=((H=$.input)==null?void 0:H.sql)??((ae=$.args)==null?void 0:ae.sql),me=((ie=$.input)==null?void 0:ie.python)??((ge=$.args)==null?void 0:ge.python),pe=((je=$.input)==null?void 0:je.chartType)??((ve=$.args)==null?void 0:ve.chartType);v(pe),m(te),p(me),u(!0),Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!d){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",sql:d,python:x||""}})}else if($.toolName==="generateQueryConfig"){a("Generating query config...");const te=((Ne=$.input)==null?void 0:Ne.chartType)??((Ie=$.args)==null?void 0:Ie.chartType),me=((X=$.input)==null?void 0:X.queryConfig)??((oe=$.args)==null?void 0:oe.queryConfig);((ue=$.input)==null?void 0:ue.cardConfig)??((xe=$.args)==null||xe.cardConfig),v(te),D(me),m(void 0),p(void 0);const pe=await f();if((we=pe==null?void 0:pe.data)!=null&&we.error){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",queryConfig:me,message:(Ce=pe==null?void 0:pe.data)==null?void 0:Ce.error.message}});return}if((Me=pe==null?void 0:pe.data)!=null&&Me.records){Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized"}});return}Q({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized",records:(Oe=pe==null?void 0:pe.data)==null?void 0:Oe.records}})}else a("Analyzing...")}function Y($){const H=s.removeFromScopeArray(h,$);se(H)}function se($){const H=s.sanitizeAIScope($);k(H),F(ae=>[...ae,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(H)}`}]}])}function ne(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelId:A||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:N||""},H=s.dedup([...h,$]);se(H)}function _(){const $={databaseName:B||"",schemaName:g||"",tableName:O||"",datamodelName:s.resolveDatamodelName(P),connectionId:L||"",connectionType:N||"",datamodelId:A||""};if(!s.isInAiScopeArray([...w||[],...h],$)||h.length===0){const ae=s.dedup([...w||[],...h,$]).filter(ie=>ie.connectionId===$.connectionId);se(ae)}}const W=!["ready","error"].includes(U),le=s.getErrorMessage(G);return{messages:R,setMessages:F,sendMessage:V,regenerate:z,isLoading:W,handleSetAIScope:_,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Y,currentAssitantScope:h,setCurrentAssitantScope:k,stop:J,status:U,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:le,clearError:Z}}const cr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Ks({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=I.useRef(null),[i,c]=I.useState(!1),[l,d]=I.useState(s.isDevEnv),[o,x]=I.useState(!1),[p,m]=I.useState(!1),[u,v]=I.useState(!1),y=t??u,h=s.useCurrentAIContext(),{setCurrentAIContext:b}=s.useAIActions(),{clearQueue:T}=s.useQueueActions(),{clearFileAttachments:C}=s.useFileActions(),B=s.useFileAttachments("editor"),O=s.useDashboardStore(te=>te.dashboard.aiContext),L=s.useEditorStore(te=>te.card.dataSource),g=s.useEditorStore(te=>te.actions.setCardSql),w=s.useEditorStore(te=>te.actions.setRunSql),E=s.useEditorStore(te=>te.showAIDialog),f=s.useDashboardStore(te=>te.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:j}=s.useEditorActions(),{setDataSource:k}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:P,setMessages:N,sendMessage:A,isLoading:S,stop:R,status:F,llmUsage:z,errorMessage:G,clearError:V}=ir(),[U,Q]=I.useState(""),J=te=>{Q(te.target.value)},Z=te=>{te.preventDefault();const me=U.trim();if(!me&&B.length===0)return;const pe=[];me&&pe.push({type:"text",text:me}),B.forEach(Fe=>{Fe.data&&pe.push({type:"file",mediaType:Fe.type,filename:Fe.name,url:`data:${Fe.type};base64,${Fe.data}`})}),A({role:"user",parts:pe}),Q(""),C("editor"),H({force:!0})},{visibleMessages:q,hasMoreMessages:Y,totalMessageCount:se,loadMoreMessages:ne,resetMessageWindow:_}=s.useMessageWindow(P,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:W,isAtBottom:le,hasNewMessages:he,newMessageCount:$,scrollToBottom:H,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(q,{threshold:50,behavior:"smooth",isStreaming:S});I.useEffect(()=>{var te;E&&((te=r.current)==null||te.focus(),b({selectedEntities:(L==null?void 0:L.selectedEntities)||[]}))},[E,L,b]),s.useAutoSubmitQueue({assistantType:"editor",status:F,isLoading:S,sendMessage:A});const{hasActiveTools:ge}=s.useActiveToolStatus(P),je=I.useCallback(te=>{n==null||n(te),t===void 0&&v(te)},[t,n]);I.useEffect(()=>{if(!y)return;function te(me){me.key==="Escape"&&je(!1)}return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[y,je]);const ve=I.useCallback(te=>{A({role:"user",parts:[{type:"text",text:te}]}),H({force:!0})},[A,H]),Ne=I.useCallback(async()=>{const te=JSON.stringify(P??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(te),s.ue.success("Conversation copied")}catch(me){console.error("Failed to copy conversation",me),s.ue.error("Unable to copy conversation")}},[P]),Ie=I.useCallback(()=>{je(!y)},[y,je]);function X(te,me){me==="sql"?(g(te),w(!0)):me==="python"&&(j(te),w(!0))}function oe(){h.selectedEntities.length===0&&b({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})}function ue(te){oe();const me={role:"user",parts:[{type:"text",text:te.title+" "+te.subtitle}]};A(me)}function xe(te){oe(),A({role:"user",parts:[{type:"text",text:te}]})}function we(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,onCheckedChange:d,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:x,children:"System Message"})]})]})}function Ce(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Me=(U==null?void 0:U.length)===0&&(P==null?void 0:P.filter(te=>te.role==="user").length)===0,Oe=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",y&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ce(),f&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[we(),l&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Ne,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:y?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:Ie,children:y?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{N([]),T("editor"),V(),_()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{M(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:W,className:"mt-2 flex w-full grow basis-0",onScroll:ae,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:ne,className:"text-xs",children:["Load ",Math.min(5,se-q.length)," ","more messages (",se-q.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:q,showTools:l,handleRun:X,showSystemMessage:o,onQuickReply:ve,disableQuickReplies:S}),!ge&&e.jsx(s.AssistantStatus,{status:F,errorMessage:G})]})}),E&&!le&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{H({force:!0}),ie()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),he&&$>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:$>9?"9+":$})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Me&&!D&&e.jsx(s.Placeholders,{onClick:ue,placeholders:cr}),e.jsx("div",{children:Me&&D&&e.jsx(s.SeedQuestions,{seedQuestions:D.seedQuestions||[],handleSeedQuestionClick:xe})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:Q,stop:R,input:U,handleInputChange:J,handleSubmit:te=>{oe(),Z(te),H({force:!0})},isLoading:S,status:F,assistantType:"editor",onFocus:()=>{}})]}),z&&i&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",z.inputTokens," prompt tokens, ",z.outputTokens," ","completion tokens, ",z.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(L==null?void 0:L.selectedEntities)||[],open:p,onOpenChange:m,dataSource:L||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return y&&a?Lt.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:Oe})}),a):Oe}function dr(t,n,a){if(!n)return!1;const r=n.qualifiedFieldName,i=n.qualifiedEntityName,c=i&&n.name?`${i}.${n.name}`:r;return t.some(l=>{if(!(s.getDataType(l.dataType||"")==="date"))return!1;const o=s.getSelectedDateFilterColumn(l,a),x=o.split("."),p=x[x.length-1]||o,m=x.length>1?x.slice(0,-1).join("."):void 0,u=l.qualifiedTableName||m,v=u?`${u}.${p}`:void 0;return r?v?v===c||v.endsWith(`.${r}`):p===n.name:v?v===c:p===n.name})}const cs=({dataType:t})=>s.getFieldIconComponent(t);function ur({aliasTemplate:t,onAliasTemplateChange:n}){var o;const[a,r]=I.useState(t),[i,c]=I.useState(!1),l=(o=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:o[0],d=l?`e.g. Min Sales in {{${l.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Input$1,{placeholder:d,value:i?a:t,onChange:x=>{r(x.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&i&&a!==t?(n(a),c(!1)):x.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),i&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),c(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function mr({valueAliases:t,onValueAliasesChange:n}){const[a,r]=I.useState(null),[i,c]=I.useState(""),[l,d]=I.useState(""),o=()=>{n({...t,"":""})},x=m=>{const u={...t};delete u[m],n(u)},p=m=>{const u={...t};delete u[m],u[i]=l,n(u),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([m,u],v)=>e.jsx("div",{className:"flex items-center gap-2",children:a===m?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:i,onChange:y=>c(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?p(m):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:l,onChange:y=>d(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?p(m):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>p(m),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(m),c(m),d(u)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(m),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},m+v)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:o,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function xr({idx:t}){var d;const n=s.useEditorStore(o=>{var x;return(x=o.card)==null?void 0:x.preferences}),a=s.useEditorStore(o=>{var x;return(x=o.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(o=>o.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(o=>o.idx===t);function l(o,x){(o==="end"||o==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:o!=="none",align:o,anchor:o,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const m={...c};m.datalabels=p;const u=a==null?void 0:a.map(v=>v.idx===x?m:v);r({...n,datasetOptions:u})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(s.Tag,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(s.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>l("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>l("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Gt,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Ht,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})}),e.jsx("button",{onClick:()=>l("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(_t,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function ds({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",n),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function hr(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function pr({col:t,idx:n,className:a,iconClassName:r,children:i}){const c=s.useEditorStore(p=>{var m;return(m=p.card)==null?void 0:m.preferences}),l=s.useEditorStore(p=>{var m,u;return(u=(m=p.card)==null?void 0:m.preferences)==null?void 0:u.datasetOptions}),d=l==null?void 0:l.find(p=>p.idx===n),{setCardPreferences:o}=s.useEditorStore(p=>p.actions);function x(p){if(!d)o({...c,datasetOptions:[...l||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const m={...d};m.type=p==="area"?"line":p,m.fill=p==="area"?"origin":"";const u=l==null?void 0:l.map(v=>v.idx===n?m:v);o({...c,datasetOptions:u})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(ds,{className:"max-w-[100px]",title:t,children:hr(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>x("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>x("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>x("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(xr,{idx:n})]})]})}function fr(){const t=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>d.isDevMode),a=s.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=s.useEditorStore(d=>d.actions);function i(d){var p;const o={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...a,chartOptions:{...a==null?void 0:a.chartOptions,plugins:{...(p=a==null?void 0:a.chartOptions)==null?void 0:p.plugins,...o}}};r(x)}function c(){var d,o,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:"Data Labels"}),e.jsx(s.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"start",children:"Start"}),e.jsx(s.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{value:"end",children:"End"})]})})]})]})}function l(){var d,o,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:o.datalabels)==null?void 0:x.anchor)||"none",onValueChange:i,defaultValue:"none",children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select position"})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(s.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(t)&&e.jsx(s.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:n?c():l()})}function gr({column:t}){const n=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>{var x,p;return(p=(x=o.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(o=>o.label))||[],i=r==null?void 0:r.find(o=>o===t.label||o===t.name),c=i?r.indexOf(i):-1;function l(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(pr,{idx:c,col:i,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(fr,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&l(),["pie","doughnut"].includes(n)&&d()]})}function jr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(x=>x.card),l=c==null?void 0:c.dataSource,d=["attribute-values",t.entityName,t.name,n,a],o=s.useQuery({queryKey:d,queryFn:async()=>{if(!(l!=null&&l.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const x={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},p={connection_id:l.connectionId,cardConfig:x,cardDataSource:l,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",p);const m=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(m!=null&&m.error)return console.error("Error fetching attribute values:",m.error),[];const u=t.name;return((m==null?void 0:m.records)||[]).map(y=>{const h=y[u]||y[t.alias||u]||y[t.label];return{id:h||"",value:h||"",label:String(h||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(l!=null&&l.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:o.data||[],isLoading:o.isLoading,isFetching:o.isFetching,isError:o.isError,error:o.error,refetch:o.refetch}}function dt({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var B,O;const l=!!i,[d,o]=I.useState(l?"values":"fields"),[x,p]=I.useState(""),[m,u]=I.useState({id:(i==null?void 0:i.id)||s.v4(),field:(i==null?void 0:i.field)||null,selectedValues:i?Array.isArray(i.value)?i.value:[i.value]:[]}),v=a.filter(L=>{var w;return l?!1:!((w=r==null?void 0:r.conditions)==null?void 0:w.some(E=>E.field.id===L.id))&&L.label.toLowerCase().includes(x.toLowerCase())}),y=L=>{u({...m,field:L}),o("values")},h=()=>{if(m.field&&m.selectedValues.length>0){const L={id:m.id,field:m.field,operator:"in",value:m.selectedValues};let g;if(l){const w=((r==null?void 0:r.conditions)||[]).map(E=>E.id===i.id?L:E);g={...r,conditions:w}}else{const w=(r==null?void 0:r.conditions)||[];g={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...w,L],groups:[]}}c(g),n(!1)}},b=()=>{if(!l||!i)return;const L=((r==null?void 0:r.conditions)||[]).filter(g=>g.id!==i.id);if(L.length>0){const g={...r,conditions:L};c(g)}else c(void 0);n(!1)},T=L=>{u({...m,selectedValues:L})},C=()=>{l&&i?(u({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),o("values")):(u({id:s.v4(),field:null,selectedValues:[]}),o("fields")),p("")};return I.useEffect(()=>{t&&C()},[t,l,i]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:l?`Edit Filter: ${(B=m.field)==null?void 0:B.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(O=m.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!l&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&d==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(L=>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:[L.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(L.value)?`${L.value.length} values`:String(L.value)})]},L.id))})]}),d==="fields"&&!l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:x,onChange:L=>p(L.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:v.map(L=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>y(L),children:[e.jsx(cs,{dataType:s.getDataType(L.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:L.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[L.entityName,".",L.name]})]})]},L.id))}),v.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),v.length===0&&!x&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(br,{field:m.field,selectedValues:m.selectedValues,onValuesChange:T,onBack:l?void 0:()=>o("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:l?e.jsx(s.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:C,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:h,disabled:!m.field||m.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function br({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=I.useState(""),{values:l,isLoading:d,isFetching:o}=jr({field:t,searchQuery:i,limit:500}),x=i?l.filter(u=>String(u.value).toLowerCase().includes(i.toLowerCase())):l,p=u=>{const v=n.includes(u);a(v?n.filter(y=>y!==u):[...n,u])},m=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(u=>u.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:i,onChange:u=>c(u.target.value),className:"pl-10"})]}),d||o?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===x.length&&x.length>0,onCheckedChange:m}),e.jsxs(s.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(u=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(u.value),children:[e.jsx(s.Checkbox,{checked:n.includes(u.value),onCheckedChange:()=>p(u.value)}),e.jsx(ds,{className:"text-sm",children:u.label})]},u.id))})]})]})}function yr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:l}){var vs,Ns,Cs,Ss,ws,Ts,Es;const{attributes:d,listeners:o,setNodeRef:x,transform:p,transition:m,isDragging:u}=s.useSortable({id:t.id}),v=s.useEditorStore(K=>K.card),y=s.useEditorStore(K=>K.frame),{scopedFields:h}=s.useScopedFields(),{userContext:b}=s.useCurrentUserInfo(),T=(b==null?void 0:b.type)==="organization",C=(vs=v.dataSource)==null?void 0:vs.semanticDomainId,{promoteMetric:B}=s.usePromoteCalculatedMetricToDomain({domainId:C}),{updateLabel:O,handleAggregationChange:L,handleDateFormatChange:g,handleGranularityChange:w,handleAliasTemplateChange:E,handleValueAliasesChange:f,removeField:M,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:P,handleMetricTargetValueChange:N}=s.useFieldManagement(v),[A,S]=I.useState(!1),[R,F]=I.useState(!1),[z,G]=I.useState(!1),[V,U]=I.useState(null),[Q,J]=I.useState(t.dateFormat||"YYYY-MM-DD"),[Z,q]=I.useState(t.customFormat||""),[Y,se]=I.useState(!!t.customFormat),[ne,_]=I.useState(t.granularity||"day"),[W,le]=I.useState(t.aliasTemplate||""),[he,$]=I.useState(t.valueAliases||{}),[H,ae]=I.useState((Ns=t.parameters)==null?void 0:Ns.filters),ie=K=>{K==="custom"?se(!0):(se(!1),J(K),(n==="groupBy"||_e)&&g(a,K,"",n))},ge=K=>{q(K),(n==="groupBy"||_e)&&g(a,"custom",K,n)},je=K=>{var re;_(K);const ee=(re=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:re.value;ee&&!Y&&(J(ee),n==="groupBy"&&g(a,ee,"",n)),n==="groupBy"&&w(a,K)},ve=K=>{le(K),n==="metrics"&&E(a,K)},Ne=K=>{$(K),n==="metrics"&&f(a,K)},Ie=K=>{O(n,a,K)},X=K=>K!=null&&K.startsWith("card-source-")?K.replace("card-source-",""):K,oe=(K,ce,ee)=>{const re=X(K.id),de=X(ce.id);return re&&de&&re===de?!0:K.name===ce.name&&K.role===ce.role},xe=s.isCalculatedMetric(t)?(Cs=y==null?void 0:y.calculatedFields)==null?void 0:Cs.find(K=>oe(K,t)):void 0,we=t.fieldScope==="dashboard"||t.fieldScope===void 0&&!!xe,Ce=t.fieldScope==="domain",Me=Ce?"domain":we?"dashboard":"card",Oe=Ce?t:we&&xe?xe:t,te=K=>{var ce;if(ae(K),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:K}},re=[...((ce=v.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(v.id,{metricColumns:re})}F(!1)},me=async K=>{await B(K),kt()},pe=()=>{M(n,a)},Fe={transform:s.CSS.Transform.toString(p),transition:m},ms=s.getDataType(t.dataType),Ue=ms==="date",xs=l==="kpi",_e=n==="detailColumns",hs=((Ss=v.config)==null?void 0:Ss.metricColumns)||[],Ve=((ws=v.config)==null?void 0:ws.groupByColumns)||[],ps=s.useDashboardStore(K=>{var ce;return(ce=K.dashboard)==null?void 0:ce.filters})??[],fs=s.useDashboardStore(K=>K.filterValues),mt=s.getDateFormatOptionsForGranularity(ne),xt=!!l&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(l),ht=l==="kpi"||l==="table",ke=I.useMemo(()=>Ve.find(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),gs=I.useMemo(()=>Ve.some(K=>s.getDataType(K.dataType||"")==="date"),[Ve]),pt=I.useMemo(()=>{var re;if(!ke)return!1;const K=(re=v.config)==null?void 0:re.filters;if(!K)return!1;const ce=de=>{const fe=de.field;return fe?ke.id&&fe.id===ke.id||ke.qualifiedFieldName&&fe.qualifiedFieldName===ke.qualifiedFieldName?!0:fe.name===ke.name:!1},ee=de=>de.conditions.some(be=>s.getDataType(be.field.dataType||"")==="date"&&ce(be))?!0:de.groups.some(be=>ee(be));return ee(K)},[(Ts=v.config)==null?void 0:Ts.filters,ke]),ft=I.useMemo(()=>dr(ps,ke,fs),[ps,fs,ke]),js=pt||ft,gt=I.useMemo(()=>hs.some(K=>K.comparisonType==="start_vs_end"),[hs]),jt=n!=="pivotBy",bt=Ue&&n==="groupBy"&&(!xs||gt),yt=!xs&&Ue&&(n==="groupBy"||_e),vt=l==="kpi"&&Ue&&n==="groupBy",Nt=n==="metrics",bs=xt&&n==="metrics",Ct=()=>{const K=t,ce=n==="metrics"&&s.isCalculatedMetric(K);return e.jsxs("div",{className:"space-y-1",children:[!ce&&e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:ee=>{ee.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),ce&&K.calculatedFormula&&e.jsxs("div",{title:s.formatDisplayFormula(K.calculatedFormula),onPointerDown:ee=>{ee.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:["= ",s.formatDisplayFormula(K.calculatedFormula)]})]})},St=()=>jt?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Te,{value:t.label??"",onSave:Ie,placeholder:"Display label...",type:"text"})]}):null,ys=()=>bt?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:ne,onValueChange:je,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K,children:s.toTitleCase(K)},K))})]})]}):null,wt=()=>yt?e.jsxs(e.Fragment,{children:[ys(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:Y?"custom":Q,onValueChange:ie,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:mt.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),Y&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:Z,onChange:K=>{K.stopPropagation(),ge(K.target.value)},onClick:K=>K.stopPropagation(),className:"h-8 text-xs"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Examples: YYYY-MM-DD, MM/DD/YY, DD-MMM-YYYY HH:mm"})]})]})]}):null,Tt=()=>{var ce,ee,re,de;const K=vt;return K?e.jsx(e.Fragment,{children:K&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ce=v.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:k})]})}),((ee=v.config)==null?void 0:ee.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((re=v.config)==null?void 0:re.trendlineWindow)||30,onChange:fe=>{const be=parseInt(fe.target.value)||30;D(be)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:((de=v.config)==null?void 0:de.trendlineGranularity)||"day",onValueChange:P,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})}):null},Et=()=>{if(!Nt)return null;const K=t,ce=s.isCalculatedMetric(K);return e.jsxs(e.Fragment,{children:[ce&&T&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Formula"}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>G(!0),children:[e.jsx(s.Pencil,{className:"mr-2 h-3 w-3"}),"Edit Formula"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:ee=>{L(a,ee)},disabled:ce,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),bs&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:K.comparisonType||"none",onValueChange:ee=>j(a,ee),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),(()=>{const ee=!gs||!js,re=gs?js?void 0:"Add a date filter to enable":"Add a date groupBy to enable",de=(fe,be)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:fe,disabled:ee,title:re,children:be})}),ee&&re&&e.jsx(s.TooltipContent,{side:"right",children:re})]})});return e.jsxs(e.Fragment,{children:[de("previous_period","Previous Period"),de("same_period_last_year","Same Period Last Year"),de("start_vs_end","Start vs End")]})})(),ht&&e.jsx(s.SelectItem,{value:"target",children:"Target"})]})]})]}),bs&&K.comparisonType==="target"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(s.Input$1,{type:"number",value:K.targetValue!==void 0&&K.targetValue!==null?String(K.targetValue):"",onChange:ee=>{const re=ee.target.value;if(re===""){N(a,void 0);return}const de=Number(re);N(a,Number.isFinite(de)?de:void 0)},className:"h-8 text-xs",placeholder:"Enter target value..."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(H==null?void 0:H.conditions)&&H.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:H.conditions.map(ee=>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:()=>{U(ee),F(!0)},children:[e.jsxs("span",{className:"font-medium",children:[ee.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(ee.value)?ee.value.length===1?String(ee.value[0]):ee.value.length<=2?ee.value.join(", "):`${ee.value.slice(0,2).join(", ")} +${ee.value.length-2}`:String(ee.value)})}),Array.isArray(ee.value)&&ee.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",ee.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:ee.value.map((re,de)=>e.jsx("div",{children:String(re)},de))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:re=>{var fe;re.stopPropagation();const de=H.conditions.filter(be=>be.id!==ee.id);if(de.length>0){const be={...H,conditions:de};te(be)}else if(ae(void 0),n==="metrics"){const be={...t,parameters:{...t.parameters,filters:void 0}},Ae=[...((fe=v.config)==null?void 0:fe.metricColumns)||[]];Ae[a]=be,s.useEditorStore.getState().actions.updateCardConfig(v.id,{metricColumns:Ae})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},ee.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{U(null),F(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(gr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(ur,{aliasTemplate:W,onAliasTemplateChange:ve}),e.jsx(mr,{valueAliases:he,onValueAliasesChange:Ne})]})]})},{columns:It=[],refetch:kt}=s.useColumns(),At=(H==null?void 0:H.conditions)&&H.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:x,style:Fe,...d,...o,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${u?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(cs,{dataType:ms}),e.jsx(ds,{className:s.cn("w-[140px] flex-1 text-sm",At&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Es=H==null?void 0:H.conditions)==null?void 0:Es.length)&&!A&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:H.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:H.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),S(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),i(r==="asc"?"desc":"asc")},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),pe()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Ct(),St(),l==="kpi"&&ys(),wt(),Tt(),Et()]})]}),R&&e.jsx(dt,{open:R,onOpenChange:K=>{F(K),K||U(null)},availableFields:It,existingFilters:H,editingCondition:V,onSave:K=>{var ce;if(K)te(K);else if(ae(void 0),n==="metrics"){const ee={...t,parameters:{...t.parameters,filters:void 0}},re=[...((ce=v.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(v.id,{metricColumns:re})}U(null)}}),z&&n==="metrics"&&e.jsx(s.CalculatedFieldEditor,{open:z,onOpenChange:G,availableFields:h,existingField:Oe,existingFieldScope:Me,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:K=>{var Ae;if(K.role!=="metric")return;const ce=[...((Ae=v.config)==null?void 0:Ae.metricColumns)||[]];ce[a]=K;const{frame:ee,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(v.id,{metricColumns:ce}),!s.isCalculatedMetric(K))return;const de=ee.calculatedFields||[],fe=de.findIndex(Ee=>Ee.name===t.name&&Ee.role===t.role);if(fe<0)return;const be=de.map((Ee,ze)=>ze===fe?{...K,id:Ee.id}:Ee);re.updateFrame({calculatedFields:be})},onSaveToDashboard:K=>{var ze;if(K.role!=="metric")return;const{frame:ce,actions:ee}=s.useEditorStore.getState(),re=ce.calculatedFields||[],de=re.findIndex(He=>oe(He,K)),fe=de>=0&&re[de].id!==K.id?{...K,id:re[de].id}:K,be=de>=0?re.map((He,Dt)=>Dt===de?fe:He):[...re,fe];ee.updateFrame({calculatedFields:be});const Ae=[...((ze=v.config)==null?void 0:ze.metricColumns)||[]],Ee=t;Ae[a]={...fe,id:Ee.id,aliasTemplate:Ee.aliasTemplate,valueAliases:Ee.valueAliases,parameters:Ee.parameters,customFormat:Ee.customFormat},ee.updateCardConfig(v.id,{metricColumns:Ae})},onPromoteMetricToDomain:C&&T?me:void 0,domainId:C,cardId:v.id})]})}function vr({concept:t}){const n=()=>{switch(t){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-100 text-xs font-medium dark:bg-blue-200/20",children:"Product"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Sales"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"Profit"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/50 text-xs font-medium dark:bg-blue-200/20",children:"Electronics"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$5,200"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$1,300"})]}),e.jsxs("div",{className:"flex border-b dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/30 text-xs font-medium dark:bg-blue-300/20",children:"Clothing"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$3,100"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$620"})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-1/3 bg-blue-200/20 text-xs font-medium dark:bg-blue-200/20",children:"Food"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$2,400"}),e.jsx("div",{className:"w-1/3 text-center text-xs",children:"$480"})]})]})]});case"pivotBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Pivot Columns = Pivot By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that split your data into multiple columns or series."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Region"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"North"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"South"}),e.jsx("div",{className:"w-1/4 rounded-t bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"East"})]}),e.jsxs("div",{className:"flex border-b py-1 dark:border-border",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$2,300"}),e.jsx("div",{className:"w-1/4 bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$1,800"}),e.jsx("div",{className:"w-1/4 bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$3,400"})]}),e.jsxs("div",{className:"flex py-1",children:[e.jsx("div",{className:"w-1/4 text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$460"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-100 text-center text-xs dark:bg-purple-400/20",children:"$360"}),e.jsx("div",{className:"w-1/4 rounded-b bg-purple-50 text-center text-xs dark:bg-purple-300/20",children:"$680"})]})]})]});case"metrics":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Metric Values (Cells)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that represent the values shown in your visualization."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"col-span-1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q1"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q2"}),e.jsx("div",{className:"col-span-1 text-center text-xs font-medium",children:"Q3"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Sales"}),e.jsx("div",{className:"rounded bg-blue-100 p-1 text-center text-xs dark:bg-blue-300/20",children:"$2,300"}),e.jsx("div",{className:"rounded bg-blue-200 p-1 text-center text-xs dark:bg-blue-400/20",children:"$3,100"}),e.jsx("div",{className:"rounded bg-blue-300 p-1 text-center text-xs dark:bg-blue-500/20",children:"$4,200"})]}),e.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-1",children:[e.jsx("div",{className:"text-xs font-medium",children:"Profit"}),e.jsx("div",{className:"rounded bg-green-100 p-1 text-center text-xs dark:bg-green-300/20",children:"$460"}),e.jsx("div",{className:"rounded bg-green-200 p-1 text-center text-xs dark:bg-green-400/20",children:"$620"}),e.jsx("div",{className:"rounded bg-green-300 p-1 text-center text-xs dark:bg-green-500/20",children:"$840"})]})]})]});case"detailColumns":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Columns"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields to display as columns in the detail table. No aggregation applied - shows raw values from the database."})]});default:return null}};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function Pe({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:l=null}){const{isOver:d,setNodeRef:o}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(b=>b.card),m=s.useEditorStore(b=>b.card.type),u=n.length>0,v=I.useMemo(()=>!l||!d?!0:s.validateFieldForChartType(l,t,m).isValid,[l,d,t,m]),y=(b,T)=>{var B;!((B=p.config)!=null&&B.sortByColumns)||p.config.sortByColumns.findIndex(O=>O.id===b)===-1||x(p.id,b,{direction:T})};if(t==="sortBy"&&i===!1)return null;const h=t!=="sortBy"&&m!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),h&&e.jsx(vr,{concept:t})]}),e.jsx("div",{ref:o,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":d&&v,"border-red-500 bg-red-50 dark:bg-red-950":d&&!v,"border-muted-foreground/30 bg-muted/40":!d&&u,"min-h-[60px] border-muted-foreground/20 bg-background":!d&&!u}),children:n.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{id:t,items:n.map(b=>b.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((b,T)=>{const B=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(yr,{field:b,zone:t,index:T,sortDirection:B,onSortDirectionChange:O=>y(b.id,O),hasPivotColumns:c,cardType:m})})},b.id)})})})})]})}function Nr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var Q,J,Z,q;const[l,d]=I.useState(!1),o=s.useEditorStore(Y=>{var se;return!!((se=Y.card.customCardPreferences)!=null&&se.url)}),x=s.useEditorStore(Y=>Y.card),p=s.useEditorStore(Y=>Y.frame),m=s.findCustomVisualConfigCard(p,x),{manifest:u}=s.useCustomVisual(((Q=m==null?void 0:m.customCardPreferences)==null?void 0:Q.url)||""),v=(J=u==null?void 0:u.visuals)==null?void 0:J.find(Y=>{var se;return Y.name===((se=m==null?void 0:m.customCardPreferences)==null?void 0:se.componentName)}),y=s.resolveMultiInputType(m,v)==="multiple",h=y&&!!((Z=m==null?void 0:m.customCardPreferences)!=null&&Z.url),b=s.getConfigSlotExpectedType(v==null?void 0:v.slots),T=s.useEditorStore(Y=>Y.actions.updateCardConfig),C=s.useEditorStore(Y=>Y.actions.updateFrame),{scopedFields:B,refetch:O}=s.useScopedFields(),{userContext:L}=s.useCurrentUserInfo(),g=y&&(m==null?void 0:m.id)===x.id&&b?b:x==null?void 0:x.type,w=g==="detailTable",E=t.length>0||a.length>0||i.length>0,f=!w&&(g!=="kpi"||a.length<=2),M=!w,j=!w&&g!=="kpi",k=g!=="kpi"&&E,D=w,P=w?"Drop fields from Columns":"Drop fields from Rows or Metrics",N=(q=x.dataSource)==null?void 0:q.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:N}),S=(L==null?void 0:L.type)==="organization",R=Y=>{const se=p.calculatedFields||[],ne=se.findIndex(H=>H.name===Y.name&&H.role===Y.role),_=ne>=0?{...Y,id:se[ne].id}:Y,W=ne>=0?se.map((H,ae)=>ae===ne?_:H):[...se,_];C({calculatedFields:W});const le=s.getNewField(_,"metrics",a),he=a.findIndex(H=>H.name===le.name&&H.role===le.role),$=he>=0?a.map((H,ae)=>ae===he?{...H,...le,id:H.id}:H):[...a,le];T(x.id,{metricColumns:$})},F=async Y=>{await A(Y),O()},z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(g),G=j&&!z,V=()=>g==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},U=()=>g==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return e.jsxs(e.Fragment,{children:[e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[f&&e.jsx(Pe,{zone:"groupBy",fields:t,label:V().label,placeholder:V().placeholder,activeField:c}),G&&e.jsx(Pe,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:c}),M&&e.jsx(Pe,{zone:"metrics",fields:a,label:U().label,placeholder:U().placeholder,hasPivotColumns:n.length>0,activeField:c}),D&&e.jsx(Pe,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drag columns to display"}),a.length>=1&&S&&e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"mt-2 w-full justify-start text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Create Metric"]}),k&&e.jsx(Pe,{zone:"sortBy",fields:r,label:"Sort By",placeholder:P,activeField:c})]})]}),(!o||h)&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CHART SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:e.jsx(ct,{mode:"config"})})})]}),(o||h)&&e.jsxs(s.AccordionItem,{value:"plugin",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"COMPONENT SETTINGS"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsx(lt,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:l,onOpenChange:d,availableFields:B,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Y=>{Y.role==="metric"&&T(x.id,{metricColumns:[...a,Y]})},onSaveToDashboard:Y=>{Y.role==="metric"&&R(Y)},onPromoteMetricToDomain:N&&S?F:void 0,domainId:N,cardId:x.id})]})}function Cr({onEditJoins:t}){const n=s.useEditorStore(d=>d.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,i=(r==null?void 0:r.joins)||[];if(i.length===0)return null;const c=d=>!d||d.length===0?"No conditions":d.map(o=>{var u,v,y,h;const x=`${(u=o.source)==null?void 0:u.entityName}.${(v=o.source)==null?void 0:v.name}`,p=`${(y=o.target)==null?void 0:y.entityName}.${(h=o.target)==null?void 0:h.name}`,m=o.operator||"=";return`${x} ${m} ${p}`}).join(" AND "),l=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((o,x)=>({id:x,operator:o.operator,condition:c(o.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:i.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:i.map((d,o)=>{const x=l(d),p=Array.isArray(x);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:d.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:d.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:d.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:p?x.map(m=>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:m.condition}),m.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",m.operator,")"]})]},m.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x})})})]},d.id||o)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const Gs={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function Sr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d}){var E,f;const[o,x]=I.useState(()=>Gs.getItem("chart-selector-expanded")==="true"),[p,m]=I.useState(!1),u=s.useEditorStore(M=>M.card),v=s.useEditorStore(M=>M.actions.updateCardConfig),y=a.length>0||r.length>0||i.length>0||l.length>0,{data:h,autoJoinMetadata:b}=s.useDashboardCardQuery(u),T=((E=u==null?void 0:u.config)==null?void 0:E.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),C=((f=u==null?void 0:u.dataSource)==null?void 0:f.selectedEntities)||[],B=M=>{v(u.id,{...u==null?void 0:u.config,joinPlan:M}),m(!1)},O=()=>{v(u.id,{...u==null?void 0:u.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},g=()=>{m(!0)};I.useEffect(()=>{Gs.setItem("chart-selector-expanded",String(o))},[o]);const w=()=>{x(M=>!M)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(os,{selectedChart:t,onChartChange:n,variant:"outline"})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(s.ChartQuickSelector,{selectedChart:t,onChartChange:n,isDropdownExpanded:o,onToggleDropdown:w})})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:y||h}),children:e.jsx(ye.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(Cr,{onEditJoins:g}),e.jsx(Nr,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:l,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Xs,{open:p,onOpenChange:m,joinPlan:T,availableDataSources:C,onSave:B,onCancel:L,onRemove:O,children:e.jsx("div",{})})]})}function wr({initialFilters:t,availableFields:n}={}){const[a,r]=I.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(L=>L.card.dataSource);const{columns:i,isLoading:c}=s.useColumns(),d=n||i||[],o={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},p=L=>{const g=w=>{if(w.id===L){const E=d[0]||o,f=s.getDataType(E.dataType)==="date";return{...w,groups:[...w.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:E,operator:f?"between":"=",value:f?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(g)}};r(g(a))},m=(L,g)=>{const w=E=>E.id===L?{...E,conditions:E.conditions.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},u=(L,g)=>{const w=E=>E.id===L?{...E,groups:E.groups.filter(f=>f.id!==g)}:{...E,groups:E.groups.map(w)};r(w(a))},v=(L,g,w,E)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const f=M=>M.id===L?{...M,conditions:M.conditions.map(j=>j.id===g?{...j,[w]:E}:j)}:{...M,groups:M.groups.map(f)};r(f(a))},y=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:f.conditions.map(M=>M.id===g?{...M,...w}:M)}:{...f,groups:f.groups.map(E)};r(E(a))},h=(L,g)=>{const w=E=>E.id===L?{...E,logicalOperator:g}:{...E,groups:E.groups.map(w)};r(w(a))},b=(L,g)=>{const w=E=>E.id===L?{...E,negate:g}:{...E,groups:E.groups.map(w)};r(w(a))},T=(L,g,w)=>{const E=f=>f.id===L?{...f,conditions:s.arrayMove(f.conditions,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},C=(L,g,w)=>{const E=f=>f.id===L?{...f,groups:s.arrayMove(f.groups,g,w)}:{...f,groups:f.groups.map(E)};r(E(a))},B=L=>{if(!L||L.conditions.length===0&&L.groups.length===0)return"-- No filters defined";const g=E=>{let f="";typeof E.field=="object"?f=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:f=String(E.field);const M=E.operator;let j=E.value;if(E.field.dataType==="string"&&!["in","not in"].includes(E.operator))typeof j=="string"?j=`'${j}'`:Array.isArray(j)&&(j=`'${j.join(", ")}'`);else if(E.field.dataType==="date"||E.field.dataType==="datetime"||E.field.dataType==="timestamp")if(E.operator==="between"&&Array.isArray(j)&&j.length===2){const k=j[0]?`'${j[0]}'`:"NULL",D=j[1]?`'${j[1]}'`:"NULL";return`${f} BETWEEN ${k} AND ${D}`}else if((E.operator==="in"||E.operator==="not in")&&Array.isArray(j)){const k=j.map(D=>D?`'${D}'`:"NULL").join(", ");return`${f} ${M} (${k})`}else typeof j=="string"||j instanceof Date?j=`'${j}'`:Array.isArray(j)&&j.length>0&&(j=`'${j[0]}'`);else if(["in","not in"].includes(E.operator)){let k=[];Array.isArray(j)?k=j.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof j=="string"?k=j.split(",").map(D=>{const P=D.trim();return E.field.dataType==="string"?`'${P}'`:P}):typeof j=="number"&&(k=[String(j)]),j=`(${k.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${f} LIKE '${j.replace(/'/g,"")}%'`:`${f} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${f} LIKE '%${j.replace(/'/g,"")}'`:`${f} LIKE '%${String(j)}'`;case"isNull":return`${f} IS NULL`;case"isNotNull":return`${f} IS NOT NULL`;default:return`${f} ${M} ${j}`}},w=E=>{const f=E.conditions.map(g),M=E.groups.map(P=>w(P)),j=[...f,...M].filter(Boolean);if(j.length===0)return"";const k=j.join(` ${E.logicalOperator} `),D=j.length>1?`(${k})`:k;return E.negate?`NOT ${D}`:D};return w(L)},O=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:d,isLoading:c,addCondition:x,addGroup:p,removeCondition:m,removeGroup:u,updateCondition:v,updateConditionFields:y,updateGroupOperator:h,updateGroupNegate:b,reorderConditions:T,reorderGroups:C,generateSQLPreview:B,hasAnyFilters:O}}function Tr({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const Er=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Ir({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,l]=I.useState(!1),d=I.useMemo(()=>{const o={};return a.forEach(x=>{const p=Er(x);o[p]||(o[p]={}),o[p][x.entityId]||(o[p][x.entityId]=[]),o[p][x.entityId].push(x)}),o},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:l,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",i),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Tr,{children:[t.entityName,".",t.name]})}):r,e.jsx(s.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(d).map(([o,x])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),o]}),children:Object.entries(x).map(([p,m])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[s.getEntityIcon(m[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:m[0].entityName})]}),m.map((u,v)=>e.jsxs(s.CommandItem,{value:u.id,onSelect:()=>{n(u),l(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===u.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:u.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:u.description&&e.jsx("span",{children:u.description})})]})]},u.id+v))]},`${o}-${p}`))},o))})]})})]})}function us(t){var h;const n=s.useEditorStore(b=>b.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),i=s.useEditorStore(b=>b.card.config),c=i==null?void 0:i.joinPlan,l={...t,alias:t.name,label:"value",role:"groupby"},d={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},o={...l,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[l],metricColumns:[d],sortByColumns:[o]},p=((h=n.dataSource)==null?void 0:h.connectionId)||n.connectionId,{data:m,isPending:u,error:v}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:p,cardConfig:x,cardDataSource:n.dataSource})}catch(b){console.log(t),console.error("error",b)}},enabled:!!p,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((m==null?void 0:m.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:u,error:v}}function kr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,l]=as.useState(!1),{filterValues:d}=us(t),o=p=>{a(n.filter(m=>m!==p))},x=p=>{n.includes(p)?a(n.filter(m=>m!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:c,onOpenChange:l,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:n.length>0?n.map(p=>{const m=d.find(u=>u.value===p);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[m==null?void 0:m.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:u=>{u.key==="Enter"&&o(p)},onMouseDown:u=>{u.preventDefault(),u.stopPropagation()},onClick:u=>{u.stopPropagation(),o(p)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},p)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:d.map((p,m)=>e.jsxs(s.CommandItem,{onSelect:()=>x(p.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(p.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:p.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p.count})]})]},p.value+m))})]})]})})]})})}function Ar({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:l,error:d}=us(t);return l?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:i||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((o,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:o.value,children:o.label},o.value+x))})]})}function Dr({value:t,operator:n,onChange:a,className:r}){var o,x,p;const{tokenProps:i}=s.useSemaphorContext(),c=((x=(o=i==null?void 0:i.params)==null?void 0:o.calendarContext)==null?void 0:x.tz)||((p=i==null?void 0:i.params)==null?void 0:p.timezone),l=I.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const m=t[0]?new Date(t[0]):void 0,u=t[1]?new Date(t[1]):void 0;if(m&&u)return{from:m,to:u}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:m}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:m,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const m=new Date(t);if(!isNaN(m.getTime()))return{from:void 0,to:m}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const m=new Date(t[0]),u=t.length>1?new Date(t[t.length-1]):m;if(!isNaN(m.getTime()))return{from:m,to:u}}}},[t,n]),d=m=>{if(!m){a(void 0);return}if(m.from&&m.to)a([m.from.toISOString(),m.to.toISOString()]);else if(m.from){const u=new Date(m.from);u.setHours(23,59,59,999),a([m.from.toISOString(),u.toISOString()])}else if(m.to){const u=new Date(m.to);u.setHours(0,0,0,0),a([u.toISOString(),m.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:l,onChange:d,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Lr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Mr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Or=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Fr=["=","!=","isNull","isNotNull"],Rr=["between","isNull","isNotNull"],Br={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function Us(t){return Br[t]||s.titleCase(t)}function Pr(t){switch(t){case"string":return Mr;case"number":return Or;case"boolean":return Fr;case"date":return Rr;default:return Lr}}function ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:l,availableFields:d,updateConditionFields:o}){const{attributes:x,listeners:p,setNodeRef:m,transform:u,transition:v,isDragging:y}=s.useSortable({id:t.id}),{isPending:h,error:b}=us(t.field),T={transform:s.CSS.Transform.toString(u),transition:v};return e.jsxs("div",{ref:m,style:T,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${y?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:C=>l(a,C),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(Ir,{value:t.field,onValueChange:C=>{const B=C,O=s.getDataType(B.dataType)==="date";o(a,t.id,{field:B,value:"",operator:O?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:C=>{C==="in"||C==="not in"?o(a,t.id,{operator:C,value:[]}):C==="isNull"||C==="isNotNull"?o(a,t.id,{operator:C,value:null}):o(a,t.id,{operator:C,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Us(t.operator):""})}),e.jsx(s.SelectContent,{children:Pr(s.getDataType(t.field.dataType)).map(C=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:C,children:Us(C)},C))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?h?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):b?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(kr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(C=>typeof C=="string")?t.value:[],onChange:C=>o(a,t.id,{value:C}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Ar,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:C=>o(a,t.id,{value:C}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:C=>o(a,t.id,{value:C==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Dr,{value:t.value,operator:t.operator,onChange:C=>o(a,t.id,{value:C}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:C=>i(a,t.id,"value",C.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Vr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onReorderConditions:x,onReorderGroups:p,onAddCondition:m,onAddGroup:u,availableFields:v,renderFilterGroup:y,updateConditionFields:h}){const{attributes:b,listeners:T,setNodeRef:C,transform:B,transition:O,isDragging:L}=s.useSortable({id:t.id}),g={transform:s.CSS.Transform.toString(B),transition:O},w=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id){const k=t.conditions.findIndex(P=>P.id===M.id),D=t.conditions.findIndex(P=>P.id===j.id);k!==-1&&D!==-1&&x(t.id,k,D)}},E=f=>{const{active:M,over:j}=f;if(j&&M.id!==j.id&&a){const k=t.groups.findIndex(P=>P.id===M.id),D=t.groups.findIndex(P=>P.id===j.id);k!==-1&&D!==-1&&p(a,k,D)}};return e.jsxs("div",{ref:C,style:g,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${L?"z-50 opacity-50":""}`,children:[n>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...b,...T,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>i(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:f=>r(t.id,f),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&c(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:w,children:e.jsx(s.SortableContext,{items:t.conditions.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((f,M)=>e.jsx(ut,{condition:f,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:l,onUpdateField:d,onRemoveCondition:o,onUpdateGroupOperator:r,availableFields:v,updateConditionFields:h},f.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:E,children:e.jsx(s.SortableContext,{items:t.groups.map(f=>f.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(f=>y(f,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>m(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function zr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:l,isLoading:d,addCondition:o,addGroup:x,removeCondition:p,removeGroup:m,updateCondition:u,updateConditionFields:v,updateGroupOperator:y,updateGroupNegate:h,reorderConditions:b,reorderGroups:T,generateSQLPreview:C,hasAnyFilters:B,setCurrentFilters:O}=wr({initialFilters:t,availableFields:n}),L=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[g,w]=I.useState(!1),E=(j,k,D)=>{const P=N=>N.id===j?{...N,conditions:N.conditions.map(A=>A.id===k?{...A,field:D,dataType:D.dataType}:A)}:{...N,groups:N.groups.map(P)};O(P(c))},f=(j,k=0,D)=>k===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:A}=P;if(A&&N.id!==A.id){const S=j.conditions.findIndex(F=>F.id===N.id),R=j.conditions.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&b(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((P,N)=>e.jsx(ut,{condition:P,index:N,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onUpdateGroupOperator:y,availableFields:l,updateConditionFields:v},P.id))})}),e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:P=>{const{active:N,over:A}=P;if(A&&N.id!==A.id){const S=j.groups.findIndex(F=>F.id===N.id),R=j.groups.findIndex(F=>F.id===A.id);S!==-1&&R!==-1&&T(j.id,S,R)}},children:e.jsx(s.SortableContext,{items:j.groups.map(P=>P.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(P=>f(P,k+1,j.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>o(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),g&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},j.id):e.jsx(Vr,{group:j,depth:k,parentGroupId:D,onUpdateGroupOperator:y,onUpdateGroupNegate:h,onRemoveGroup:m,onUpdateCondition:u,onUpdateField:E,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:T,onAddCondition:o,onAddGroup:x,availableFields:l,renderFilterGroup:f,updateConditionFields:v},j.id),M=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600"}),e.jsx("span",{className:"ml-2 text-sm text-gray-600",children:"Loading columns..."})]}):f(c),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:g,onCheckedChange:j=>w(j)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:C(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:i,children:"Cancel"}),M>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(B?c:null),children:"Apply Filters"})]})]})}function $r({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:l}){const d=x=>{a(t,x),l(!1)},o=()=>{r(t),l(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:l,children:[c&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(zr,{filters:n,availableFields:i,onSave:d,onCancel:()=>l(!1),onClearAll:o})]})]})}function qr({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var T,C;const[i,c]=I.useState(null),l=s.useEditorStore(B=>B.card),d=s.useEditorStore(B=>B.actions.updateCardConfig),o=(T=l==null?void 0:l.config)==null?void 0:T.joinPlan,x=I.useCallback(B=>B.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||B.entityName==="calculated_fields"||B.qualifiedEntityName==="calculated_fields",[]),p=(C=l==null?void 0:l.dataSource)==null?void 0:C.semanticDomainId,{data:m}=s.useJoinabilityMap(p),u=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],v=I.useCallback(B=>B.startsWith("card-source-")?"source":B.startsWith("card-")?null:B.startsWith("source-")||n.find(O=>O.id===B)?"source":a("groupBy").find(O=>O.id===B)?"groupBy":a("metrics").find(O=>O.id===B)?"metrics":a("pivotBy").find(O=>O.id===B)?"pivotBy":a("sortBy").find(O=>O.id===B)?"sortBy":a("detailColumns").find(O=>O.id===B)?"detailColumns":null,[n,a]),y=I.useCallback(B=>{c(B.active.id)},[]),h=I.useCallback(B=>{var M;const{active:O,over:L}=B;if(!L||!t){c(null);return}const g=O.id,w=L.id,E=v(g),f=v(w)||w;if(f==="sortBy"){if(E==="source"){const j=n.find(D=>D.id===g);if(!j){c(null);return}if(!(a("groupBy").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("metrics").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName)||a("detailColumns").some(D=>D.name===j.name&&D.qualifiedEntityName===j.qualifiedEntityName))){c(null);return}}else if(E==="pivotBy"){c(null);return}else if(E!=="groupBy"&&E!=="metrics"&&E!=="sortBy"&&E!=="detailColumns"){c(null);return}}if(E==="source"&&f==="sortBy"){const j=[...n].find(N=>N.id===g);if(!j){c(null);return}const k=a("sortBy");if(s.fieldAlreadyExists(j,k)){c(null);return}const D=s.validateFieldForChartType(j,"sortBy",l.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const P=s.getNewField(j,"sortBy",k);c(null),r("sortBy",[...k,P]);return}if(E==="source"&&f!=="source"&&f!=="sortBy"){const j=[...n].find(R=>R.id===g);if(!j){c(null);return}const k=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],D=k.filter(R=>!x(R));if(D.length>0){const R=D[0].qualifiedEntityName;if(!R){c(null);return}if(R!==j.qualifiedEntityName&&!x(j)&&j.qualifiedEntityName)if(p&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(j,{joinabilityMap:m.joinabilityMap,selectedFields:k,baseEntityName:(M=o==null?void 0:o.baseEntity)==null?void 0:M.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!o){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(R,j.qualifiedEntityName,o)){s.showJoinRequiredNotification(),c(null);return}}}const P=a(f);if(s.fieldAlreadyExists(j,P)){c(null);return}const N=s.validateFieldForChartType(j,f,l.type);if(!N.isValid){s.ue.error("Invalid Field Type",{description:N.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(j,f,P),S=[...P,A];c(null),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E!=="source"&&f!=="source"&&E!==f){const j=a(E),k=a(f),D=j.find(R=>R.id===g);if(!D){c(null);return}const P=s.validateFieldForChartType(D,f,l.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),c(null);return}const N=s.getNewField(D,f,k);if(c(null),f==="sortBy"){s.fieldAlreadyExists(D,k)||r(f,[...k,N]);return}const A=j.filter(R=>R.id!==g),S=[...k,N];r(E,A),r(f,S),f==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(l.type,l.config,d,t,S);return}if(E&&f&&E===f&&E!=="source"){const j=a(E),k=j.findIndex(P=>P.id===g),D=j.findIndex(P=>P.id===w);if(k!==D){const P=s.arrayMove(j,k,D);r(E,P)}}c(null)},[t,n,a,r,v,o,p,m,x,l.type,d,l.config]),b=i?u.find(B=>B.id===i):null;return{activeId:i,activeField:b,handleDragStart:y,handleDragEnd:h}}function Kr({activeView:t,onViewChange:n,splitViewEnabled:a}){const r=s.useEditorStore(d=>d.card),{config:i}=I.useContext(s.SemaphorContext).tokenProps,c=(i==null?void 0:i.showInfoTab)!==!1,l=()=>a?!1:!["table","pivotTable","aggregateTable","detailTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),l()&&e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),r.type!=="kpi"&&c&&e.jsx(s.TabsTrigger,{value:"info",className:"rounded-md transition data-[state=active]:bg-muted",children:"Info"})]})})}const Gr=[{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 Ur(){var o,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=I.useState(!1),[i,c]=I.useState(""),l=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},d=p=>{const m=p.target.value;c(m),m&&!isNaN(parseInt(m))&&n(t.id,parseInt(m))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:i,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((x=(o=t.config)==null?void 0:o.rowLimit)==null?void 0:x.toString())||"100",onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Gr.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function _r({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:l,sortState:d,splitViewEnabled:o}){const x=I.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!o||["table","pivotTable","aggregateTable","detailTable"].includes(t.type)?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"h-full min-h-0 w-full",children:[e.jsx(s.ResizablePanel,{defaultSize:60,minSize:30,role:"chart-section",className:"flex flex-col pb-3",children:e.jsx(ns,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.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 p-6",children:[(a||r)&&(n==null?void 0:n.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),(n==null?void 0:n.records)&&e.jsx(s.TableVisual,{card:t,data:x,paginationMetadata:i,onPaginationChange:c,isLoading:a||r,onSortChange:l,sortState:d})]})})]})}const Hr="semaphor-split-view-enabled";function Jr(){return Zs(Hr,!0)}function Yr({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:i,activeCard:c,columns:l,columnsLoading:d,columnsError:o}){var se,ne,_;const x=s.useEditorStore(W=>W.card),p=s.useDashboardStore(W=>W.filterValues),m=s.useDashboardStore(W=>W.selectedSheetId),u=s.useDashboardStore(W=>W.inlineFilterValuesMap[(c==null?void 0:c.id)||""]),{updateCardConfig:v,setCard:y,updateCardInFrame:h,setShowAIDialog:b}=s.useEditorActions(),T=s.useEditorStore(W=>W.showAIDialog),C=s.useDashboardStore(W=>W.isVisualEditing),[B,O]=I.useState(!1),[L,g]=I.useState(!1),[w,E]=I.useState(null),{config:f}=I.useContext(s.SemaphorContext).tokenProps,M=(f==null?void 0:f.showInfoTab)!==!1,[j,k]=Jr();s.useEditorStore(W=>{var le;return!!((le=W.card.customCardPreferences)!=null&&le.url)});const{data:D,errorMessage:P,isLoading:N,isFetching:A,errorSql:S,pagination:R,refetch:F,comparisonMetadata:z}=s.useDashboardCardQuery(c),G=I.useMemo(()=>(D==null?void 0:D.records)||[],[D==null?void 0:D.records]),[V,U]=I.useState(!1);I.useEffect(()=>{A||U(!1)},[A]);const Q=()=>{const W=!j;W&&t==="table"&&n("chart"),k(W)},J=(W,le)=>{const he={...c,paginationConfig:{page:W+1,pageSize:le}};y(he),h(he)};function Z(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(x.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(p||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Card Data Source State"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(c.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",l.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":o?"Error loading columns":JSON.stringify(l.slice(0,5),null,2)})]})]})]})}const q=W=>{if(!x.config)return;const le=s.sortStateToSortByColumns(W,x.config.metricColumns,x.config.groupByColumns,x.config.detailColumns);v(x.id,{...x.config,sortByColumns:le})},Y=I.useMemo(()=>{var W;return s.sortByColumnsToSortState((W=x.config)==null?void 0:W.sortByColumns)},[(se=x.config)==null?void 0:se.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":T&&C}),children:[a&&Z(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&T&&e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),e.jsx(Kr,{activeView:t,onViewChange:n,splitViewEnabled:j}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(ne=c.config)==null?void 0:ne.filters,cardFilterCount:s.getFilterCount(((_=c.config)==null?void 0:_.filters)||null),onFiltersClick:i,inlineFilters:c.inlineFilters,inlineFilterValues:u,sheetId:m||""}),z&&x.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:z,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ur,{})}),T&&e.jsx(ye.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:N||A,onClick:()=>{U(!0),F()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":V})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:j?"Hide Results Table":"Show Results Table",onClick:Q,children:j?e.jsx(Vt,{className:"size-4"}):e.jsx(ea,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(rt,{})}),!T&&e.jsx(s.IconButton,{onClick:()=>b(!T),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:s.cn("flex grow flex-col pb-6",{"pb-0":j&&!["table","pivotTable","aggregateTable","detailTable"].includes(c.type)}),children:e.jsx(_r,{card:c,queryData:D,isLoading:N,isFetching:A,pagination:R,onPaginationChange:J,onSortChange:q,sortState:Y,splitViewEnabled:j})}),t==="table"&&(D==null?void 0:D.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(N||A)&&(D==null?void 0:D.records)&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/50",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}),e.jsx(s.TableVisual,{card:c,data:G,comparisonMetadata:z,paginationMetadata:R,onPaginationChange:J,isLoading:N||A,onSortChange:q,sortState:Y})]}),t==="info"&&M&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:P?e.jsx(ls,{error:P,errorSql:S,onSendFeedback:()=>{const W=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:x.config,dataSource:c.dataSource,dashboardFilters:p,errorMessage:P,errorSql:S,generatedSql:D==null?void 0:D.sql});E(W),g(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const W=s.useEditorStore.getState().actions;W.setIsDevMode(!0),W.setCardSql(S||""),setTimeout(()=>{W.setRunSql(!0)},100)},100)}}):(D==null?void 0:D.sql)&&e.jsx(tt,{sql:D.sql,showCardDetails:!0})})})]}),w&&e.jsx(s.FeedbackDialog,{open:L,onOpenChange:g,feedbackData:w})]})]})}function Qr({activeField:t}){const[n,a]=I.useState(!0);return I.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(cs,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Wr=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},a=r=>{var i;if((i=r.reason)!=null&&i.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function Xr({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var F,z,G;const l=s.useEditorStore(V=>V.card),{updateCardConfig:d,removeGroupByColumn:o,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[m,u]=I.useState(!1),[v,y]=I.useState(!1),h=I.useRef(null),b=I.useCallback(V=>{V.preventDefault(),V.stopPropagation(),y(!0),h.current={startX:V.clientX,startWidth:i||150};const U=J=>{if(!h.current)return;const Z=J.clientX-h.current.startX,q=Math.max(80,h.current.startWidth+Z);c==null||c(t.id,q)},Q=()=>{y(!1),h.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",Q)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",Q)},[i,t.id,c]),T=(F=l==null?void 0:l.config)==null?void 0:F.filters,C=(z=T==null?void 0:T.conditions)==null?void 0:z.some(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName),B=V=>{V?p(l.id,V):d(l.id,{filters:void 0})},{attributes:O,listeners:L,setNodeRef:g,transform:w,transition:E,isDragging:f}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(w),transition:E},j=s.getDataType(t.dataType),k=Zr(j),D=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"asc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},P=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"desc"},d(l.id,{sortByColumns:J})}else d(l.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},N=()=>{var Q;const V=((Q=l==null?void 0:l.config)==null?void 0:Q.groupByColumns)||[];if(!V.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};d(l.id,{groupByColumns:[...V,J]})}},A=V=>{var J;const U=((J=l==null?void 0:l.config)==null?void 0:J.metricColumns)||[];if(!U.some(Z=>Z.name===t.name&&Z.aggregate===V)){const Z={...t,id:`metric-${t.id}-${V}-${Date.now()}`,label:`${V} of ${t.label||t.name}`,role:"metric",aggregate:V};d(l.id,{metricColumns:[...U,Z]})}},S=()=>{t.role==="groupby"?o(l.id,t.id):t.role==="metric"&&x(l.id,t.id)},R={...M,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:g,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",f&&"opacity-50",n&&"bg-primary/10",v&&"select-none"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx("button",{...O,...L,className:"cursor-grab p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsxs("button",{onClick:a,className:s.cn("flex flex-1 items-center justify-between gap-1 rounded px-2 py-2 text-left text-sm font-medium transition-colors hover:bg-muted/50",n&&"bg-primary/10"),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(k,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:t.label||t.name}),t.role==="metric"&&t.aggregate&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t.aggregate,")"]}),C&&e.jsx(s.Filter,{className:"h-3 w-3 text-primary"})]}),e.jsx(s.ChevronDown,{className:"h-3 w-3 text-muted-foreground"})]})}),e.jsxs(s.DropdownMenuContent,{align:"start",className:"w-48",children:[e.jsxs(s.DropdownMenuItem,{onClick:()=>u(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",C&&"text-primary")}),C?"Edit Filter":"Filter"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:D,children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Sort A → Z"]}),e.jsxs(s.DropdownMenuItem,{onClick:P,children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),"Sort Z → A"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuSub,{children:[e.jsxs(s.DropdownMenuSubTrigger,{children:[e.jsx(s.Calculator,{className:"mr-2 h-4 w-4"}),"Summarize"]}),e.jsxs(s.DropdownMenuSubContent,{children:[e.jsx(s.DropdownMenuItem,{onClick:()=>A("SUM"),children:"Sum"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("AVG"),children:"Average"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("COUNT"),children:"Count"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("DISTINCT"),children:"Count Distinct"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MIN"),children:"Min"}),e.jsx(s.DropdownMenuItem,{onClick:()=>A("MAX"),children:"Max"})]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N,children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(Hs,{className:"mr-2 h-4 w-4"}),"Pivot by this column"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(s.EyeOff,{className:"mr-2 h-4 w-4"}),"Hide column"]}),e.jsxs(s.DropdownMenuItem,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(s.Trash2,{className:"mr-2 h-4 w-4"}),"Remove column"]})]})]})]}),e.jsx("div",{onMouseDown:b,className:s.cn("absolute right-0 top-0 h-full w-1 cursor-col-resize bg-transparent hover:bg-primary/50",v&&"bg-primary")}),e.jsx(dt,{open:m,onOpenChange:u,availableFields:r.length>0?r:[t],existingFilters:T,editingCondition:C?(G=T==null?void 0:T.conditions)==null?void 0:G.find(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:B})]})}function Zr(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function el({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var E,f,M,j;const i=s.useEditorStore(k=>k.card),{updateCardConfig:c}=s.useEditorActions(),[l,d]=I.useState(null),[o,x]=I.useState({}),[p,m]=I.useState(!1),u=I.useMemo(()=>{var P,N;const k=((P=i==null?void 0:i.config)==null?void 0:P.groupByColumns)||[],D=((N=i==null?void 0:i.config)==null?void 0:N.metricColumns)||[];return[...k,...D]},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(f=i==null?void 0:i.config)==null?void 0:f.metricColumns]),v=I.useMemo(()=>{const k=new Set(u.map(D=>`${D.qualifiedEntityName}.${D.name}`));return r.filter(D=>!k.has(`${D.qualifiedEntityName}.${D.name}`))},[r,u]),{data:y,isLoading:h}=s.useDashboardCardQuery(i),b=(y==null?void 0:y.records)||[],T=I.useCallback((k,D)=>{x(P=>({...P,[k]:D}))},[]),C=I.useCallback(k=>{var A,S;const D=s.getDataType(k.dataType),P=((A=i==null?void 0:i.config)==null?void 0:A.groupByColumns)||[],N=((S=i==null?void 0:i.config)==null?void 0:S.metricColumns)||[];if(D==="number"){const R={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...N,R]})}else{const R={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...P,R]})}m(!1)},[(M=i==null?void 0:i.config)==null?void 0:M.groupByColumns,(j=i==null?void 0:i.config)==null?void 0:j.metricColumns,i.id,c]),B=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=k=>{d(k.active.id)},L=k=>{const{active:D,over:P}=k;if(d(null),!P||D.id===P.id)return;const N=u.findIndex(S=>S.id===D.id),A=u.findIndex(S=>S.id===P.id);if(N!==-1&&A!==-1){const S=s.arrayMove(u,N,A),R=S.filter(z=>z.role==="groupby"),F=S.filter(z=>z.role==="metric");c(i.id,{groupByColumns:R,metricColumns:F})}},g=l?u.find(k=>k.id===l):null,w=k=>{let D="";for(;k>=0;)D=String.fromCharCode(k%26+65)+D,k=Math.floor(k/26)-1;return D};return a?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(s.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):u.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:B,collisionDetection:s.closestCenter,onDragStart:O,onDragEnd:L,children:[e.jsxs("table",{className:"w-full border-collapse",children:[e.jsxs("thead",{children:[e.jsxs("tr",{className:"border-b border-border bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-20 w-12 border-r border-border bg-muted/50 px-2 py-1 text-center text-xs font-medium text-muted-foreground"}),e.jsx(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map((k,D)=>e.jsx("th",{style:{width:o[k.id]?`${o[k.id]}px`:void 0,minWidth:o[k.id]?`${o[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:w(D)},`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(s.SortableContext,{items:u.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:u.map(k=>e.jsx(Xr,{column:k,isSelected:(t==null?void 0:t.id)===k.id,onSelect:()=>n(k),availableFields:r,width:o[k.id],onWidthChange:T},k.id))}),e.jsx("th",{className:"w-10 border-r border-border bg-background px-1 py-2",children:e.jsxs(s.Popover,{open:p,onOpenChange:m,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Add column",children:e.jsx(s.Plus,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[280px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns available."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:v.map(k=>{const D=s.getDataType(k.dataType),P=D==="number"?s.Hash:D==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:k.label||k.name,onSelect:()=>C(k),children:[e.jsx(P,{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:h?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center",children:e.jsx(s.LoaderCircle,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"})})}):b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:u.length+2,className:"h-32 text-center text-muted-foreground",children:"No data available"})}):b.slice(0,100).map((k,D)=>e.jsxs("tr",{className:s.cn("border-b border-border transition-colors hover:bg-muted/50",D%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:D+1}),u.map(P=>{const N=k[P.name]??k[P.label??""];return e.jsx("td",{style:{width:o[P.id]?`${o[P.id]}px`:void 0,minWidth:o[P.id]?`${o[P.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===P.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:sl(N,P)})},`${D}-${P.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},D))})]}),e.jsx(s.DragOverlay,{children:g&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:g.label||g.name})})]})}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border bg-muted/30 px-4 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",Math.min(b.length,100)," of ",b.length," rows"]}),e.jsxs("span",{children:[u.length," columns"]})]})]})}function sl(t,n){if(t==null)return"—";if(typeof t=="number")return n.role==="metric"?new Intl.NumberFormat("en-US",{minimumFractionDigits:0,maximumFractionDigits:2}).format(t):t.toString();if(t instanceof Date||typeof t=="string"&&!isNaN(Date.parse(t))){const a=new Date(t);if(!isNaN(a.getTime()))return a.toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}return String(t)}function tl({entityGroups:t,isLoading:n=!1}){var B,O;const a=s.useEditorStore(L=>L.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=s.useEditorActions(),[l,d]=I.useState(!0),[o,x]=I.useState(""),[p,m]=I.useState(new Set),u=((B=a==null?void 0:a.config)==null?void 0:B.groupByColumns)||[],v=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],y=L=>{const g=new Set(p);g.has(L)?g.delete(L):g.add(L),m(g)},h=L=>u.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName)||v.some(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName),b=(L,g)=>{if(g)if(s.getDataType(L.dataType)==="number"){const E={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...v,E]})}else{const E={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...u,E]})}else{const w=u.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName),E=v.findIndex(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName);w!==-1&&i(a.id,u[w].id),E!==-1&&c(a.id,v[E].id)}},T=L=>{if(!o)return L;const g=o.toLowerCase();return L.filter(w=>w.name.toLowerCase().includes(g)||w.label&&w.label.toLowerCase().includes(g))},C=L=>{switch(s.getDataType(L)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return l?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>d(!1),title:"Close panel",children:e.jsx(Yt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"border-b border-border p-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input,{placeholder:"Search columns...",value:o,onChange:L=>x(L.target.value),className:"h-8 pl-8 text-sm"})]})}),(u.length>0||v.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[u.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(rs,{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:u.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:u.map(L=>{const g=C(L.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.name}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>i(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.id)})})})]}),v.length>0&&e.jsxs(s.Collapsible,{defaultOpen:!0,children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 px-3 py-2 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:"h-3.5 w-3.5 transition-transform duration-200 [[data-state=open]>&]:rotate-90"}),e.jsx(s.Calculator,{className:"h-3.5 w-3.5 text-green-500"}),e.jsx("span",{children:"Metrics"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:v.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:v.map(L=>{const g=C(L.dataType);return e.jsxs("div",{className:"group flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50",children:[e.jsx(s.GripVertical,{className:"h-3 w-3 cursor-grab text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"}),e.jsx(g,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:L.label||L.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:L.aggregate}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>c(a.id,L.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.id)})})})]})]}),e.jsx(s.ScrollArea,{className:"flex-1",children:e.jsx("div",{className:"p-2",children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):t.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No columns available"}):t.map(L=>{const g=T(L.columns);if(g.length===0)return null;const w=p.has(L.entityId)||o.length>0;return e.jsxs(s.Collapsible,{open:w,onOpenChange:()=>y(L.entityId),children:[e.jsxs(s.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm font-medium hover:bg-muted/50",children:[e.jsx(s.ChevronRight,{className:s.cn("h-3.5 w-3.5 transition-transform duration-200",w&&"rotate-90")}),e.jsx(s.Table2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate text-left",children:L.label||L.entityName}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:g.map(E=>{const f=C(E.dataType),M=h(E);return e.jsxs("label",{className:s.cn("flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/50",M&&"bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:M,onCheckedChange:j=>b(E,j),className:"h-3.5 w-3.5"}),e.jsx(f,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"flex-1 truncate",children:E.label||E.name})]},E.id)})})})]},L.entityId)})})})]}):e.jsx("div",{className:"flex h-full items-start border-l border-border bg-muted/30 p-2",children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>d(!0),title:"Open panel",children:e.jsx(Qt,{className:"h-4 w-4"})})})}const al=[{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 nl({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[l,d]=I.useState(!1),[o,x]=I.useState("column"),p=I.useRef(null);I.useEffect(()=>{const y=h=>{h.key==="Escape"&&t?r():h.key==="Enter"&&t&&!l&&a(t)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t,r,a,l]);const m=y=>{const h=`[${y.label||y.name}]`,b=p.current;if(b){const T=b.selectionStart||0,C=b.selectionEnd||0,B=t.slice(0,T)+h+t.slice(C);n(B),setTimeout(()=>{b.setSelectionRange(T+h.length,T+h.length),b.focus()},0)}else n(t+h);d(!1)},u=y=>{const h=p.current;if(h){const b=h.selectionStart||0,T=h.selectionEnd||0,C=t.slice(0,b)+y.syntax+t.slice(T);n(C),setTimeout(()=>{h.setSelectionRange(b+y.name.length+1,b+y.syntax.length-1),h.focus()},0)}else n(t+y.syntax);d(!1)},v=y=>{switch(s.getDataType(y)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5",children:[e.jsx("div",{className:"flex min-w-[100px] items-center justify-center rounded border border-border bg-background px-2 py-1 text-xs font-medium text-muted-foreground",children:i?e.jsx("span",{className:"truncate",children:i.label||i.name}):e.jsx("span",{children:"—"})}),e.jsxs(s.Popover,{open:l&&o==="function",onOpenChange:y=>{d(y),y&&x("function")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",title:"Insert function",children:e.jsx(Zt,{className:"h-4 w-4"})})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search functions..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No functions found."}),e.jsx(s.CommandGroup,{heading:"Functions",children:al.map(y=>e.jsx(s.CommandItem,{value:y.name,onSelect:()=>u(y),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:y.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.description})]}),e.jsx("span",{className:"font-mono text-xs text-muted-foreground/75",children:y.syntax})]})},y.name))})]})]})})]}),e.jsxs(s.Popover,{open:l&&o==="column",onOpenChange:y=>{d(y),y&&x("column")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground",title:"Insert column reference",children:[e.jsx("span",{children:"Columns"}),e.jsx(s.ChevronDown,{className:"h-3 w-3"})]})}),e.jsx(s.PopoverContent,{className:"w-[250px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search columns..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No columns found."}),e.jsx(s.CommandGroup,{heading:"Available Columns",children:c.map(y=>{const h=v(y.dataType);return e.jsxs(s.CommandItem,{value:y.label||y.name,onSelect:()=>m(y),children:[e.jsx(h,{className:"mr-2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:y.label||y.name})]},y.id)})})]})]})})]}),e.jsx("div",{className:"relative flex-1",children:e.jsx(s.Input,{ref:p,value:t,onChange:y=>n(y.target.value),placeholder:"Enter a formula or select a column...",className:"h-7 border-border bg-background font-mono text-sm"})}),t&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:r,title:"Cancel (Esc)",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-green-600 hover:bg-green-600/10 hover:text-green-600",onClick:()=>a(t),title:"Apply (Enter)",children:e.jsx(s.Check,{className:"h-4 w-4"})})]})]})}function rl({className:t}){var u,v,y,h;const n=s.useEditorStore(b=>b.card),[a,r]=I.useState(null),[i,c]=I.useState(""),{columns:l=[],columnGroups:d=[],isLoading:o}=s.useColumns();(u=n==null?void 0:n.config)!=null&&u.groupByColumns,(v=n==null?void 0:n.config)!=null&&v.metricColumns,(y=n==null?void 0:n.config)!=null&&y.groupByColumns,(h=n==null?void 0:n.config)!=null&&h.pivotByColumns;const x=b=>{r(b),c(b?`[${b.label||b.name}]`:"")},p=b=>{console.log("Formula submitted:",b),c(""),r(null)},m=()=>{c(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(nl,{value:i,onChange:c,onSubmit:p,onCancel:m,selectedColumn:a,availableColumns:l}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(el,{selectedColumn:a,onColumnSelect:x,isLoading:o,sourceFields:l})}),e.jsx(tl,{entityGroups:d,isLoading:o})]})]})}function ll(){var z,G;const[t,n]=I.useState("chart"),[a,r]=I.useState(!1),[i,c]=I.useState(!1),[l,d]=I.useState(!0),o=s.useEditorStore(V=>V.showAIDialog),x=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:p}=s.useEditorActions(),m=s.useEditorStore(V=>V.card.type);I.useEffect(()=>Wr(),[]);const u=V=>{p(V)},v=s.useEditorStore(V=>V.frame),y=s.useEditorStore(V=>V.card);s.useEditorStore(V=>V.activeTabCardId),s.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:h,removeCard:b,updateCard:T,setActiveCard:C,updateFilters:B}=s.useEditorActions(),{columnFields:O=[],scopedFields:L=[],isLoading:g,error:w}=s.useScopedFields(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),f=y,{getFieldsForContainer:M,setFieldsForContainer:j}=s.useFieldManagement(f),{activeField:k,handleDragStart:D,handleDragEnd:P}=qr({activeCardId:v.activeCardId,sourceFields:L,getFieldsForContainer:M,setFieldsForContainer:j}),N=(V,U)=>{U&&B(V,U)},A=V=>{var U;T(V,{config:{...(U=v.cards.find(Q=>Q.id===V))==null?void 0:U.config,filters:void 0}})},S=O,R=V=>{if(!V)return 0;let U=V.conditions.length;return V.groups.forEach(Q=>{U+=R(Q)}),U},F=R(((z=f==null?void 0:f.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:D,onDragEnd:P,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(et,{isVisible:l,onToggleVisibility:()=>d(!l)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:m==="tableBuilder"?e.jsx(rl,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!o&&e.jsx(Sr,{selectedChart:m,onChartChange:u,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:k}),e.jsx(Yr,{selectedChart:m,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:F,activeCard:f,dataSourceState:y.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:g,columnsError:w,getFieldsForContainer:M,cards:v.cards,activeCardId:v.activeCardId,addCard:h,setActiveCard:C})]})}),!l&&x&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>d(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),f&&e.jsx($r,{cardId:f.id,filters:((G=f.config)==null?void 0:G.filters)||null,onFiltersChange:N,onClearFilters:A,availableFields:S,isOpen:i,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Qr,{activeField:k||null})})]})}function ol({authToken:t,onSave:n,onClose:a}){const r=I.useRef(null),i=s.useEditorStore(g=>g.showAIDialog),c=s.useEditorStore(g=>g.isDevMode),l=s.useAssistantLayoutStore(g=>g.setFullscreen),d=s.useAssistantLayoutStore(g=>g.setPanelOpen),o=s.useAssistantLayoutStore(g=>g.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),m=s.useAssistantContainer("editor"),u=p==="editor",v=I.useCallback(g=>{o("editor",g)},[o]),{setAuthToken:y}=s.useDashboardActions(),{setShowAIDialog:h,setOnSave:b,setOnClose:T}=s.useEditorActions(),{setActiveAssistantType:C}=s.useAIActions();I.useEffect(()=>{n&&b(n),a&&T(a)},[n,b,a,T]),I.useEffect(()=>{t&&t.accessToken&&y(t)},[t,y]),I.useEffect(()=>{var g,w;i?((g=r.current)==null||g.resize(40),d("editor",!0),C("editor")):((w=r.current)==null||w.resize(0),d("editor",!1),p==="editor"&&l(null),C(null))},[i,d,C,l,p]);function B(g){var w;g<1?(h(!1),d("editor",!1),p==="editor"&&l(null),C(null),(w=r.current)==null||w.resize(0)):(i||(h(!0),C("editor")),x.isOpen||d("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(et,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(or,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:v,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})]})}function L(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",u&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(ll,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Ks,{isFullscreen:u,onFullscreenChange:g=>l(g?"editor":null),fullscreenContainer:m})})})]}),e.jsx("div",{ref:v,className:s.cn("absolute inset-0",!u&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:O()}):L()})}function il(){s.useDashboardStore(o=>o.selectedCardId);const t=s.useDashboardStore(o=>o.selectedSheetId),n=s.useDashboardStore(o=>o.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=s.useDashboardStore(o=>o.actions),i=s.useDashboardStore(o=>o.isVisualEditing),c=s.useDashboardStore(o=>o.actions.updateFrame);function l(o){var u,v,y;const x=t?(u=n==null?void 0:n.sheets)==null?void 0:u.some(h=>{var b;return h.id===t&&((b=h.frames)==null?void 0:b.some(T=>T.id===o.id))}):!1,p=(y=(v=n==null?void 0:n.sheets)==null?void 0:v.find(h=>{var b;return(b=h.frames)==null?void 0:b.some(T=>T.id===o.id)}))==null?void 0:y.id,m=x?t:p||null;m&&(c(m,o),t!==m&&r(m),a(!1))}function d(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!i}),children:e.jsx(ol,{onSave:l,onClose:d})})}exports.default=il;