react-semaphor 0.1.210 → 0.1.211

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 (32) hide show
  1. package/dist/chunks/{dashboard-controls-C08300Wi.js → dashboard-controls-7KpXzAWL.js} +592 -585
  2. package/dist/chunks/dashboard-controls-CnDq9Uh_.js +42 -0
  3. package/dist/chunks/{dashboard-json-GjDBGO26.js → dashboard-json-dqey5VK0.js} +1 -1
  4. package/dist/chunks/{dashboard-json-DlEE5-WA.js → dashboard-json-stWvjp2O.js} +1 -1
  5. package/dist/chunks/{dashboard-summary-settings-dialog-THx-gjnG.js → dashboard-summary-settings-dialog-DPEe6XBC.js} +1 -1
  6. package/dist/chunks/{dashboard-summary-settings-dialog-QUuhhXU9.js → dashboard-summary-settings-dialog-DuxhidK1.js} +1 -1
  7. package/dist/chunks/{edit-dashboard-visual-Bsmow1Pa.js → edit-dashboard-visual-CQAk_UsI.js} +483 -484
  8. package/dist/chunks/{edit-dashboard-visual-PfWJXb2-.js → edit-dashboard-visual-D_XPr8f8.js} +2 -2
  9. package/dist/chunks/{editor-action-buttons-FPyaC09X.js → editor-action-buttons-CH7W6KdH.js} +1 -1
  10. package/dist/chunks/{editor-action-buttons-DNbp_ZWy.js → editor-action-buttons-D34_GSZu.js} +27 -27
  11. package/dist/chunks/{index-CAVrkf9d.js → index-BDS2sWhv.js} +27718 -27508
  12. package/dist/chunks/index-BfiIPyeS.js +1109 -0
  13. package/dist/chunks/{notification-bell-C3a7wC1u.js → notification-bell-Cu3qDd9V.js} +251 -285
  14. package/dist/chunks/notification-bell-hijGST9g.js +6 -0
  15. package/dist/chunks/{resource-management-panel-BVTgbma8.js → resource-management-panel-BvHqslqC.js} +73 -73
  16. package/dist/chunks/{resource-management-panel-C5NjrVsA.js → resource-management-panel-gK3a6OEj.js} +1 -1
  17. package/dist/chunks/{use-role-aware-display-preferences-l7NFLYnn.js → use-role-aware-display-preferences-BlR29aKQ.js} +1 -1
  18. package/dist/chunks/{use-role-aware-display-preferences-DxCPoCgr.js → use-role-aware-display-preferences-a5FH9Y0k.js} +1 -1
  19. package/dist/chunks/{use-visual-utils-B82Q-Ytl.js → use-visual-utils-B11AA2fd.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-D9IJz9R0.js → use-visual-utils-ptPsQ3nC.js} +23 -23
  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 +251 -216
  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/main.d.ts +49 -0
  29. package/package.json +1 -1
  30. package/dist/chunks/dashboard-controls-BAOrAMV9.js +0 -42
  31. package/dist/chunks/index-CXKjmjfB.js +0 -1104
  32. package/dist/chunks/notification-bell-BqvKQSw9.js +0 -6
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-CXKjmjfB.js"),I=require("react"),fe=require("./editor-action-buttons-FPyaC09X.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-BfiIPyeS.js"),I=require("react"),fe=require("./editor-action-buttons-CH7W6KdH.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.
@@ -159,6 +159,6 @@ ${w.joinType} JOIN ${E.name}
159
159
 
160
160
  ${n||a.sql||a.python}
161
161
 
162
- `;o(x)}:void 0}}function at({className:t,...n}){var ne,_,Y,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((Y=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:Y.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),o=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[l,x]=I.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:u}=I.useContext(s.SemaphorContext),m=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:N}=s.useDashboardActions(),y=o==null?void 0:o.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)||""),S=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]),T=s.resolveMultiInputType(h,S),P=I.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:T==="multiple"}),[c,h,T]),O=I.useMemo(()=>{const $=P.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[P,a]),L=I.useMemo(()=>!h||T!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,S==null?void 0:S.slots)??a.type,[h,T,O,a,S==null?void 0:S.slots]),f=L??a.type,w=I.useMemo(()=>f===a.type?a:{...a,type:f},[a,f]),E=I.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:g,isLoading:M,isFetching:j,errorMessage:k,errorSql:D,pagination:B}=s.useDashboardCardQuery(E),{handleOpenInEditor:C,handleDebugWithAssistant:A}=tt(k,D||a.sql||a.python),v=I.useMemo(()=>(g==null?void 0:g.records)||[],[g==null?void 0:g.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=I.useMemo(()=>{var $;return f!=="pivotTable"||!(($=g==null?void 0:g.records)!=null&&$.length)?null:{records:g.records,columnSubtotalMeta:g.columnSubtotalMeta,subtotalColumns:g.subtotalColumns||[],pivotSchema:g.pivotSchema||[],groupByColumns:g.groupByColumns}},[f,g==null?void 0:g.records,g==null?void 0:g.columnSubtotalMeta,g==null?void 0:g.subtotalColumns,g==null?void 0:g.pivotSchema,g==null?void 0:g.groupByColumns]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},W=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:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:o,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,u,a,o,k,D]),J=($,H)=>{var ie,je;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((je=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&je.enableDevModePagination)&&m(!0)},Z=$=>{var ie,je,be,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(je=a.config)==null?void 0:je.groupByColumns,(be=a.config)==null?void 0:be.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)&&m(!0)},q=I.useMemo(()=>!w.id||!(g!=null&&g.records)?null:s.createChartConfig({card:w,data:g==null?void 0:g.records,cardType:f,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w.id,g==null?void 0:g.records,f,w.customCfg,w.preferences,z]);function Q($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(g!=null&&g.records&&(g==null?void 0:g.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:C,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)&&(!(g!=null&&g.records)||g.records.length===0))return f==="table"||f==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(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(f==="custom")return Q(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(f)&&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(f==="table"||f==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:w,data:v,comparisonMetadata:($=g==null?void 0:g.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:B,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(f==="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(f==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:w,data:(g==null?void 0:g.records)||[],groupByColumns:g==null?void 0:g.groupByColumns,pivotSchema:g==null?void 0:g.pivotSchema,paginationMetadata:B,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)&&(g==null?void 0:g.records)&&g.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(fe.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ua,{})})]}),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:$=>N({...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:l,onOpenChange:x,feedbackData:W,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}),ma=()=>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."})]})]}),xa=({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})})]}),ha=({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 pa(){const[t,n]=I.useState(!1),[a,r]=I.useState(""),[i,c]=I.useState(""),[o,d]=I.useState(""),[l,x]=I.useState(""),p=s.useEditorStore(w=>w.card),u=fe.useEffectiveEditorCardType(),m=s.useEditorStore(w=>w.card.customCfg),N=m?JSON.stringify(m,null,2):"",y=I.useMemo(()=>u!==p.type?{...p,type:u}:p,[p,u]),{data:h}=s.useDashboardCardQuery(y),{data:b}=s.useTopoJson(p),{setCardCustomCfg:S,setCustomVisualCode:T}=s.useEditorActions(),P=w=>{var E,g;return JSON.stringify({...w,data:{...w.data,datasets:(g=(E=w.data)==null?void 0:E.datasets)==null?void 0:g.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,g;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(P(w)),d(((g=p.preferences)==null?void 0:g.customVisualCode)||"");const M=s.merge(w,m);c(P(M))}},L=()=>{try{if(o&&T(o),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);S(E),x("")}}catch{x("Invalid JSON configuration")}},f=Object.keys(m||{}).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:f?"":"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(ma,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(at,{className:"w-1/2 rounded shadow-none"})}),e.jsx(xa,{customCode:o,cardCustomCfgString:N,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ha,{error:l,hasCardCustomConfig:!!m,onReset:()=>{c(a),S(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ga({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 As({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:o,onToggleStar:d}){return e.jsxs("button",{onClick:o,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(ga,{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 Ds=[{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 fa({onChartSelect:t,onClose:n}){const[a,r]=I.useState(""),{starredCharts:i,isStarred:c,toggleStar:o}=s.useStarredChartsStore(),{data:d=[],isLoading:l}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:u}=s.useEditorStore(g=>g.actions),m=s.useEditorStore(g=>g.card),{setCardCustomCfg:N,setCustomCardPreferences:y,setQueryConfig:h,replaceFrameCards:b,clearModeDrafts:S,initializeModeDrafts:T}=s.useEditorActions(),P=I.useMemo(()=>{if(!a)return Ds;const g=a.toLowerCase();return Ds.filter(M=>M.name.toLowerCase().includes(g))},[a]),O=I.useMemo(()=>{const g=d.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return g;const M=a.toLowerCase();return g.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=g=>{N(null),p({}),x(g),["custom","text","map"].includes(g)&&(u(!0),h(void 0)),t==null||t(g),n==null||n()},f=g=>{N(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(g);if(M==="multiple"&&g.slots&&g.slots.length>0){S();const k=s.createCardsFromSlots(g.slots,g,m);b(k),k[0]&&T(k[0]),n==null||n();return}else x("custom"),y({type:"component",visualType:M,url:g.url,componentName:g.name,icon:g.icon,pluginChartType:g.chartType,minInputs:g.minInputs,maxInputs:g.maxInputs});t==null||t("custom",g),n==null||n()},w=g=>{const M={type:"default",id:g.id,name:g.name};o(M)},E=g=>{const M={type:"custom",id:g.name,url:g.url,icon:g.icon,name:g.name};o(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:g=>r(g.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:[P.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:P.map(g=>e.jsx(As,{chartType:g.id,chartName:g.name,isCustom:!1,isStarred:c("default",g.id),onSelect:()=>L(g.id),onToggleStar:()=>w(g)},g.id))})}),O.length>0&&e.jsxs(e.Fragment,{children:[P.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((g,M)=>e.jsx(As,{chartName:g.name,isCustom:!0,pluginName:g.pluginName,isStarred:c("custom",g.name),onSelect:()=>f(g),onToggleStar:()=>E(g)},`${g.url}-${g.name}-${M}`))})]})]}),l&&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..."})]}),P.length===0&&O.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function ja({selectedChart:t,onChartChange:n}){var f,w,E,g;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:l}=s.useEditorActions(),x=I.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((f=x==null?void 0:x.customCardPreferences)==null?void 0:f.url)||""),u=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]),m=s.resolveMultiInputType(x,u)==="multiple",N=fe.useEffectiveEditorCardType(),y=m?N:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,b=(g=x==null?void 0:x.customCardPreferences)==null?void 0:g.componentName,S=m&&!!b,T=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]),P=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(Jt,{className:"h-4 w-4"})},[y,h]);return{displayChartType:y,displayLabel:T,displayIcon:P,showBadge:S,badgeLabel:b,isMultiInputContext:m,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]),o(),d(j),i&&l(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=I.useState(!1),{displayLabel:o,displayIcon:d,showBadge:l,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:u}=ja({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:o})]}),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:m=>m.preventDefault(),children:e.jsx(fa,{onChartSelect:m=>p(m),onClose:()=>c(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title: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:u,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 ba(){const t=s.useEditorStore(l=>{var x,p;return(p=(x=l.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const x=l==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,u={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(u)};function c(){const l=t??"x",x=()=>{i(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function o(){const l=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const l=t??"y",x=()=>{i(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?d():c()})}function ya({className:t}){var N,y,h,b,S,T,P,O,L,f;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,o]=I.useState(!1),d=((y=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:y.showFilterInfo)??!0,l=((b=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:b.showCardToolbar)??!0,x=((T=(S=n.preferences)==null?void 0:S.displayOptions)==null?void 0:T.showChrome)??!0,p=((O=(P=n.preferences)==null?void 0:P.displayOptions)==null?void 0:O.allowScroll)??!0,u=((f=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:f.showInlineFilterBar)??!0,m=(w,E)=>{var j;const g={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(g);const M={...n,preferences:g};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:o,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(Ys,{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=>{m("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:l,onCheckedChange:w=>{m("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=>{m("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=>{m("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:u,onCheckedChange:w=>{m("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 va(){const[t,n]=I.useState(!1),a=s.useEditorStore(u=>u.card),r=s.useEditorStore(u=>u.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(u=>u.actions.removeCardInlineFilterValue),o=(a==null?void 0:a.inlineFilters)||[];function d(u){var f,w,E,g,M;const m=((E=(w=(f=a==null?void 0:a.dataSource)==null?void 0:f.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",N=u.qualifiedFieldName||u.name;if(o.find(j=>j.column===N))return;const h=u.qualifiedFieldName?u.qualifiedFieldName.split(".").slice(0,-1).join("."):u.qualifiedEntityName||u.entityName,S=s.fmt(u.name),T=s.buildFilterFieldMeta(u),P=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((g=a==null?void 0:a.dataSource)==null?void 0:g.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(T),L={id:s.v4(),column:N,title:u.label||u.name,dataType:u.dataType,table:u.entityName||"",database:m,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(u.dataType,h,S),fieldMeta:T,semanticContext:P,width:250};i({...a,inlineFilters:[...o,L]})}function l(u){const m=o.filter(N=>N.id!==u);i({...a,inlineFilters:m}),c(a.id,u)}function x(u,m){const N=o.map(y=>y.id===u?{...y,...m}:y);i({...a,inlineFilters:N})}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":o.length>0}),children:[e.jsx(qt,{className:"h-4 w-4"}),o.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:o.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:o})})})}),o.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:o.map(u=>e.jsx(Na,{filter:u,onUpdate:m=>x(u.id,m),onRemove:()=>l(u.id)},u.id))})]})]})})]})}):null}function Na({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 nt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var o,d;return(d=(o=c.card)==null?void 0:o.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(ba,{})}),!["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(_s,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(va,{}),e.jsx(ya,{})]})}function Ca({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var B,C,A,v,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:o,setCard:d,updateCardInFrame:l,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:u}=s.useCustomVisual(((B=a==null?void 0:a.customCardPreferences)==null?void 0:B.url)||""),m=(C=u==null?void 0:u.visuals)==null?void 0:C.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),y=s.resolveMultiInputType(a,m)==="multiple",h=(m==null?void 0:m.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,b=(m==null?void 0:m.maxInputs)??((v=a==null?void 0:a.customCardPreferences)==null?void 0:v.maxInputs),S=I.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:y}),[r,a,y]),T=y?S.filter(Boolean).length:r.cards.length,P=b?T<b:!0,O=T>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),f=(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 g(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],W={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(W),o(U.id),d(U),J&&p(U)}function M(F,z){if(!P)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),o(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,...S.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function k(F){var J;if(!P)return;let z=y?"table":"bar",G="Title",V="";const U=y?Math.max(-1,...S.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:T;if(y&&((J=m==null?void 0:m.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(m.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const W={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,W)}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}),l({...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=m==null?void 0:m.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(m.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,W=y&&((Z=m==null?void 0:m.slots)==null?void 0:Z.length)&&m.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=>f(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}),l({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!W&&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:()=>g(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:!P,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 je,be,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:o,setActiveTabCardId:d,setCard:l,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:u,initializeModeDrafts:m}=s.useEditorActions(),[N,y]=I.useState({}),[h,b]=I.useState(()=>new Set),{theme:S}=s.useTheme(),T=s.useDashboardStore(X=>X.themeStyle),{authToken:P}=s.useSemaphorContext(),O=s.getTokenParams(P==null?void 0:P.accessToken),L={mode:S||"system",colors:((be=(je=T==null?void 0:T.chart)==null?void 0:je.dataset)==null?void 0:be.backgroundColor)||[]},{getCard:f,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),g=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=g?f(g):null,j=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(X=>X.name===g),k=s.resolveMultiInputType(i,j),D=a&&k==="multiple"&&!!i,B=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]),C=I.useMemo(()=>s.buildSlotOrderedCards(B),[B]),A=I.useMemo(()=>{const X=B.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[B,n]),v=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}:v!==n.type?{...n,type:v}:n,[n,v,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}))},[]),W=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}),Q=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)||""]),Y=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:Q,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Q,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),u(),m(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};o(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),l(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=C.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:[B.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:W,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:C,slotTypes:oe,multiInputData:N,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:Y})})})})]})}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(at,{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(Ca,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ls({children:t}){var A;const n=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),r=s.useEditorStore(v=>v.isDevMode),i=s.useEditorStore(v=>v.isShowingVisual),c=s.useDashboardStore(v=>v.isVisualEditing),o=s.useEditorStore(v=>v.pythonStdOut),d=s.useEditorStore(v=>v.actions.setRunSql),l=fe.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:u,setCardPreferences:m,mergeDraftsIntoCard:N,clearModeDrafts:y,initializeModeDrafts:h}=s.useEditorActions(),b=I.useMemo(()=>l!==a.type?{...a,type:l}:a,[a,l]),{data:S,isLoading:T,isFetching:P,errorMessage:O,errorSql:L,refetch:f,pagination:w}=s.useDashboardCardQuery(b),{handleDebugWithAssistant:E}=tt(O,L),g=I.useMemo(()=>(S==null?void 0:S.records)||[],[S==null?void 0:S.records]),[M,j]=I.useState(!1);I.useEffect(()=>{P||j(!1)},[P]);function k(v,R){var G,V;const F={...a,paginationConfig:{page:v+1,pageSize:R}};p(F);const z={...n,cards:n.cards.map(U=>U.id===a.id?F:U)};x(z),a.sql&&((V=(G=a.preferences)==null?void 0:G.tablePrefs)!=null&&V.enableDevModePagination)&&d(!0)}function D(v){var G,V,U,W,J;const R=s.sortStateToSortByColumns(v,(G=a.config)==null?void 0:G.metricColumns,(V=a.config)==null?void 0:V.groupByColumns,(U=a.config)==null?void 0:U.detailColumns),F={...a,config:{...a.config||{},sortByColumns:R}};p(F);const z={...n,cards:n.cards.map(Z=>Z.id===a.id?F:Z)};x(z),a.sql&&((J=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&J.enableDevModePagination)&&d(!0)}function B(){const v=JSON.stringify(S==null?void 0:S.records,null,2),R=new Blob([v],{type:"application/json"}),F=URL.createObjectURL(R),z=document.createElement("a");z.href=F,z.download=`${a.title}.json`,z.click()}function C(){const R=[Object.keys(S==null?void 0:S.records.reduce((V,U)=>({...V,...U}),{})).join(","),...((S==null?void 0:S.records)||[]).map(V=>Object.values(V).join(","))].join(`
162
+ `;o(x)}:void 0}}function at({className:t,...n}){var ne,_,Y,le,he;const a=s.useEditorStore($=>$.card),r=((ne=a.customCardPreferences)==null?void 0:ne.showCardHeader)??!0,i=((Y=(_=a.preferences)==null?void 0:_.displayOptions)==null?void 0:Y.showInlineFilterBar)??!0,c=s.useEditorStore($=>$.frame),o=s.useDashboardStore($=>$.dashboard.filters),d=s.useDashboardStore($=>$.selectedSheetId),[l,x]=I.useState(!1),{currentUser:p}=s.useCurrentUserInfo(),{tokenProps:u}=I.useContext(s.SemaphorContext),m=s.useEditorStore($=>$.actions.setRunSql),{updateFilter:N}=s.useDashboardActions(),y=o==null?void 0:o.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)||""),S=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]),T=s.resolveMultiInputType(h,S),P=I.useMemo(()=>s.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:T==="multiple"}),[c,h,T]),O=I.useMemo(()=>{const $=P.findIndex(H=>(H==null?void 0:H.id)===(a==null?void 0:a.id));return $<0?-1:s.getSlotIndexForCard(a,$)},[P,a]),L=I.useMemo(()=>!h||T!=="multiple"||O<0?a.type:s.getEffectiveCardTypeForSlot(a,O,S==null?void 0:S.slots)??a.type,[h,T,O,a,S==null?void 0:S.slots]),f=L??a.type,w=I.useMemo(()=>f===a.type?a:{...a,type:f},[a,f]),E=I.useMemo(()=>L!==a.type?{...a,type:L}:a,[a,L]),{data:g,isLoading:M,isFetching:j,errorMessage:k,errorSql:D,pagination:B}=s.useDashboardCardQuery(E),{handleOpenInEditor:C,handleDebugWithAssistant:A}=tt(k,D||a.sql||a.python),v=I.useMemo(()=>(g==null?void 0:g.records)||[],[g==null?void 0:g.records]),{setCard:R,updateCardInFrame:F}=s.useEditorActions(),{data:z}=s.useTopoJson(w),G=I.useMemo(()=>{var $;return f!=="pivotTable"||!(($=g==null?void 0:g.records)!=null&&$.length)?null:{records:g.records,columnSubtotalMeta:g.columnSubtotalMeta,subtotalColumns:g.subtotalColumns||[],pivotSchema:g.pivotSchema||[],groupByColumns:g.groupByColumns}},[f,g==null?void 0:g.records,g==null?void 0:g.columnSubtotalMeta,g==null?void 0:g.subtotalColumns,g==null?void 0:g.pivotSchema,g==null?void 0:g.groupByColumns]),V=s.usePivotTableConfig(w,G),U=()=>{x(!0)},W=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:u,systemState:{cardConfig:a.config,dataSource:a.dataSource,dashboardFilters:o,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,u,a,o,k,D]),J=($,H)=>{var ie,je;const ae={...a,paginationConfig:{page:$+1,pageSize:H}};R(ae),F(ae),a.sql&&((je=(ie=a.preferences)==null?void 0:ie.tablePrefs)!=null&&je.enableDevModePagination)&&m(!0)},Z=$=>{var ie,je,be,ve,Ne;const H=s.sortStateToSortByColumns($,(ie=a.config)==null?void 0:ie.metricColumns,(je=a.config)==null?void 0:je.groupByColumns,(be=a.config)==null?void 0:be.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)&&m(!0)},q=I.useMemo(()=>!w.id||!(g!=null&&g.records)?null:s.createChartConfig({card:w,data:g==null?void 0:g.records,cardType:f,queryConfig:w.queryConfig,customCfg:w.customCfg,preferences:w.preferences,topoJson:z}),[w,g==null?void 0:g.records,f,z]);function Q($){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCustomVisual,{card:$})})}function se(){var $;if(g!=null&&g.records&&(g==null?void 0:g.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:C,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)&&(!(g!=null&&g.records)||g.records.length===0))return f==="table"||f==="detailTable"?e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(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(f==="custom")return Q(a);if(!["table","pivotTable","aggregateTable","detailTable","custom"].includes(f)&&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(f==="table"||f==="detailTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.TableVisual,{card:w,data:v,comparisonMetadata:($=g==null?void 0:g.metadata)==null?void 0:$.comparisonMetadata,paginationMetadata:B,onPaginationChange:J,onSortChange:Z,isLoading:M||j})});if(f==="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(f==="aggregateTable")return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(s.AggregateTable,{card:w,data:(g==null?void 0:g.records)||[],groupByColumns:g==null?void 0:g.groupByColumns,pivotSchema:g==null?void 0:g.pivotSchema,paginationMetadata:B,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)&&(g==null?void 0:g.records)&&g.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(s.InfoHover,{card:a}),e.jsx(fe.VisualBadge,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(ua,{})})]}),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:$=>N({...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:l,onOpenChange:x,feedbackData:W,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}),ma=()=>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."})]})]}),xa=({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})})]}),ha=({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 pa(){const[t,n]=I.useState(!1),[a,r]=I.useState(""),[i,c]=I.useState(""),[o,d]=I.useState(""),[l,x]=I.useState(""),p=s.useEditorStore(w=>w.card),u=fe.useEffectiveEditorCardType(),m=s.useEditorStore(w=>w.card.customCfg),N=m?JSON.stringify(m,null,2):"",y=I.useMemo(()=>u!==p.type?{...p,type:u}:p,[p,u]),{data:h}=s.useDashboardCardQuery(y),{data:b}=s.useTopoJson(p),{setCardCustomCfg:S,setCustomVisualCode:T}=s.useEditorActions(),P=w=>{var E,g;return JSON.stringify({...w,data:{...w.data,datasets:(g=(E=w.data)==null?void 0:E.datasets)==null?void 0:g.map(M=>({...M,data:[]}))}},null,2)},O=()=>{var E,g;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(P(w)),d(((g=p.preferences)==null?void 0:g.customVisualCode)||"");const M=s.merge(w,m);c(P(M))}},L=()=>{try{if(o&&T(o),i){const w=JSON.parse(i),E=s.getObjectDiff(JSON.parse(a),w);S(E),x("")}}catch{x("Invalid JSON configuration")}},f=Object.keys(m||{}).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:f?"":"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(ma,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(at,{className:"w-1/2 rounded shadow-none"})}),e.jsx(xa,{customCode:o,cardCustomCfgString:N,mergedConfig:i,onConfigChange:w=>c(w??""),onCodeChange:w=>d(w??"")})]}),e.jsx(ha,{error:l,hasCardCustomConfig:!!m,onReset:()=>{c(a),S(null)},onApply:L,onClose:()=>n(!1)})]})]})}function ga({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 As({chartType:t,chartName:n,isCustom:a=!1,pluginName:r,isStarred:i,showStar:c=!0,onSelect:o,onToggleStar:d}){return e.jsxs("button",{onClick:o,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(ga,{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 Ds=[{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 fa({onChartSelect:t,onClose:n}){const[a,r]=I.useState(""),{starredCharts:i,isStarred:c,toggleStar:o}=s.useStarredChartsStore(),{data:d=[],isLoading:l}=s.useCustomVisualsQuery(),{setCardType:x,setCardPreferences:p,setIsDevMode:u}=s.useEditorStore(g=>g.actions),m=s.useEditorStore(g=>g.card),{setCardCustomCfg:N,setCustomCardPreferences:y,setQueryConfig:h,replaceFrameCards:b,clearModeDrafts:S,initializeModeDrafts:T}=s.useEditorActions(),P=I.useMemo(()=>{if(!a)return Ds;const g=a.toLowerCase();return Ds.filter(M=>M.name.toLowerCase().includes(g))},[a]),O=I.useMemo(()=>{const g=d.filter(j=>j.componentType==="chart"&&j.pluginType!=="standard");if(!a)return g;const M=a.toLowerCase();return g.filter(j=>j.name.toLowerCase().includes(M))},[d,a]),L=g=>{N(null),p({}),x(g),["custom","text","map"].includes(g)&&(u(!0),h(void 0)),t==null||t(g),n==null||n()},f=g=>{N(null),p({}),h(void 0);const M=s.resolveMultiInputTypeFromVisual(g);if(M==="multiple"&&g.slots&&g.slots.length>0){S();const k=s.createCardsFromSlots(g.slots,g,m);b(k),k[0]&&T(k[0]),n==null||n();return}else x("custom"),y({type:"component",visualType:M,url:g.url,componentName:g.name,icon:g.icon,pluginChartType:g.chartType,minInputs:g.minInputs,maxInputs:g.maxInputs});t==null||t("custom",g),n==null||n()},w=g=>{const M={type:"default",id:g.id,name:g.name};o(M)},E=g=>{const M={type:"custom",id:g.name,url:g.url,icon:g.icon,name:g.name};o(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:g=>r(g.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:[P.length>0&&e.jsx("div",{className:"mb-3",children:e.jsx("div",{className:"grid grid-cols-3 gap-2",children:P.map(g=>e.jsx(As,{chartType:g.id,chartName:g.name,isCustom:!1,isStarred:c("default",g.id),onSelect:()=>L(g.id),onToggleStar:()=>w(g)},g.id))})}),O.length>0&&e.jsxs(e.Fragment,{children:[P.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((g,M)=>e.jsx(As,{chartName:g.name,isCustom:!0,pluginName:g.pluginName,isStarred:c("custom",g.name),onSelect:()=>f(g),onToggleStar:()=>E(g)},`${g.url}-${g.name}-${M}`))})]})]}),l&&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..."})]}),P.length===0&&O.length===0&&!l&&e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No charts found"})]})]})}function ja({selectedChart:t,onChartChange:n}){var f,w,E,g;const a=s.useEditorStore(M=>M.card),r=s.useEditorStore(M=>M.frame),i=s.useEditorStore(M=>M.isDevMode),{replaceFrameCards:c,clearModeDrafts:o,initializeModeDrafts:d,setIsDevMode:l}=s.useEditorActions(),x=I.useMemo(()=>s.findCustomVisualConfigCard(r,a),[r,a]),{manifest:p}=s.useCustomVisual(((f=x==null?void 0:x.customCardPreferences)==null?void 0:f.url)||""),u=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]),m=s.resolveMultiInputType(x,u)==="multiple",N=fe.useEffectiveEditorCardType(),y=m?N:t??a.type,h=(E=a==null?void 0:a.customCardPreferences)==null?void 0:E.componentName,b=(g=x==null?void 0:x.customCardPreferences)==null?void 0:g.componentName,S=m&&!!b,T=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]),P=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(Jt,{className:"h-4 w-4"})},[y,h]);return{displayChartType:y,displayLabel:T,displayIcon:P,showBadge:S,badgeLabel:b,isMultiInputContext:m,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]),o(),d(j),i&&l(!0),n==null||n("bar")}}}function os({selectedChart:t,onChartChange:n,variant:a="ghost",className:r}){const[i,c]=I.useState(!1),{displayLabel:o,displayIcon:d,showBadge:l,badgeLabel:x,handleChartSelect:p,handleClearCustomVisual:u}=ja({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:o})]}),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:m=>m.preventDefault(),children:e.jsx(fa,{onChartSelect:m=>p(m),onClose:()=>c(!1)})})]}),l&&e.jsxs("div",{className:"absolute right-10 top-1/2 z-10 flex max-w-[140px] -translate-y-1/2 items-center gap-1 rounded-full border bg-background py-0.5 pl-2 pr-1 text-[10px] text-muted-foreground shadow-sm",title: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:u,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 ba(){const t=s.useEditorStore(l=>{var x,p;return(p=(x=l.card.preferences)==null?void 0:x.chartOptions)==null?void 0:p.indexAxis}),n=s.useEditorStore(l=>l.card.type),{setChartOrientation:a,setCardPreferences:r}=s.useEditorStore(l=>l.actions),i=l=>{if(a(l),n!=="bullet")return;const x=l==="y"?"horizontal":"vertical",p=s.useEditorStore.getState().card.preferences,u={...p||{},bulletConfig:{...(p==null?void 0:p.bulletConfig)||{},orientation:x}};r(u)};function c(){const l=t??"x",x=()=>{i(l==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="x"?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function o(){const l=()=>{i(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:l,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ye,{className:"size-4"}):e.jsx(Je,{className:"size-4"})})}function d(){const l=t??"y",x=()=>{i(l==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:x,tooltip:"Chart Orientation",children:l==="y"?e.jsx(Je,{className:"size-4"}):e.jsx(Ye,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?o():n==="bullet"?d():c()})}function ya({className:t}){var N,y,h,b,S,T,P,O,L,f;const n=s.useEditorStore(w=>w.card),{setCardPreferences:a,updateCardInFrame:r,setCard:i}=s.useEditorActions(),[c,o]=I.useState(!1),d=((y=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:y.showFilterInfo)??!0,l=((b=(h=n.preferences)==null?void 0:h.displayOptions)==null?void 0:b.showCardToolbar)??!0,x=((T=(S=n.preferences)==null?void 0:S.displayOptions)==null?void 0:T.showChrome)??!0,p=((O=(P=n.preferences)==null?void 0:P.displayOptions)==null?void 0:O.allowScroll)??!0,u=((f=(L=n.preferences)==null?void 0:L.displayOptions)==null?void 0:f.showInlineFilterBar)??!0,m=(w,E)=>{var j;const g={...n.preferences,displayOptions:{...(j=n.preferences)==null?void 0:j.displayOptions,[w]:E}};a(g);const M={...n,preferences:g};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:o,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(Ys,{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=>{m("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:l,onCheckedChange:w=>{m("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=>{m("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=>{m("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:u,onCheckedChange:w=>{m("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 va(){const[t,n]=I.useState(!1),a=s.useEditorStore(u=>u.card),r=s.useEditorStore(u=>u.selectedConnectionId),{setCard:i}=s.useEditorActions(),c=s.useDashboardStore(u=>u.actions.removeCardInlineFilterValue),o=(a==null?void 0:a.inlineFilters)||[];function d(u){var f,w,E,g,M;const m=((E=(w=(f=a==null?void 0:a.dataSource)==null?void 0:f.selectedEntities)==null?void 0:w[0])==null?void 0:E.database)||"",N=u.qualifiedFieldName||u.name;if(o.find(j=>j.column===N))return;const h=u.qualifiedFieldName?u.qualifiedFieldName.split(".").slice(0,-1).join("."):u.qualifiedEntityName||u.entityName,S=s.fmt(u.name),T=s.buildFilterFieldMeta(u),P=s.buildFilterSemanticContext(a==null?void 0:a.dataSource,{connectionId:r||((g=a==null?void 0:a.dataSource)==null?void 0:g.connectionId),connectionType:(M=a==null?void 0:a.dataSource)==null?void 0:M.connectionType}),O=s.isCalculatedFilterField(T),L={id:s.v4(),column:N,title:u.label||u.name,dataType:u.dataType,table:u.entityName||"",database:m,connectionId:r||"",operation:"in",sql:O?"":s.getDefaultFilterSql(u.dataType,h,S),fieldMeta:T,semanticContext:P,width:250};i({...a,inlineFilters:[...o,L]})}function l(u){const m=o.filter(N=>N.id!==u);i({...a,inlineFilters:m}),c(a.id,u)}function x(u,m){const N=o.map(y=>y.id===u?{...y,...m}:y);i({...a,inlineFilters:N})}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":o.length>0}),children:[e.jsx(qt,{className:"h-4 w-4"}),o.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:o.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:o})})})}),o.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:o.map(u=>e.jsx(Na,{filter:u,onUpdate:m=>x(u.id,m),onRemove:()=>l(u.id)},u.id))})]})]})})]})}):null}function Na({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 nt(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var o,d;return(d=(o=c.card)==null?void 0:o.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(ba,{})}),!["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(_s,{className:"size-4"}),a==="y"&&e.jsx(rs,{className:"size-4"}),a==="none"&&e.jsx(s.Square,{className:"size-4"})]}),e.jsx(va,{}),e.jsx(ya,{})]})}function Ca({isPreviewMode:t,onPreviewToggle:n,configCard:a}){var B,C,A,v,R;const r=s.useEditorStore(F=>F.frame),i=s.useEditorStore(F=>F.card),{setFrame:c,setActiveTabCardId:o,setCard:d,updateCardInFrame:l,clearModeDrafts:x,initializeModeDrafts:p}=s.useEditorActions(),{manifest:u}=s.useCustomVisual(((B=a==null?void 0:a.customCardPreferences)==null?void 0:B.url)||""),m=(C=u==null?void 0:u.visuals)==null?void 0:C.find(F=>{var z;return F.name===((z=a==null?void 0:a.customCardPreferences)==null?void 0:z.componentName)}),y=s.resolveMultiInputType(a,m)==="multiple",h=(m==null?void 0:m.minInputs)??((A=a==null?void 0:a.customCardPreferences)==null?void 0:A.minInputs)??1,b=(m==null?void 0:m.maxInputs)??((v=a==null?void 0:a.customCardPreferences)==null?void 0:v.maxInputs),S=I.useMemo(()=>s.getCustomVisualInputCards({frame:r,configCard:a,isMultiInputVisual:y}),[r,a,y]),T=y?S.filter(Boolean).length:r.cards.length,P=b?T<b:!0,O=T>Math.max(h||1,1),L=!!((R=a==null?void 0:a.customCardPreferences)!=null&&R.dataInputCardIds),f=(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 g(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],W={...r,cards:V,activeCardId:U.id},J=F===i.id;J&&x(),c(W),o(U.id),d(U),J&&p(U)}function M(F,z){if(!P)return;const G={...r,cards:[...r.cards,z],activeCardId:F.id};c(G),o(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,...S.map((z,G)=>s.getSlotIndexForCard(z,G)))+1:i.customCardPreferences.slotIndex}:void 0};M(i,F)}function k(F){var J;if(!P)return;let z=y?"table":"bar",G="Title",V="";const U=y?Math.max(-1,...S.map((Z,q)=>s.getSlotIndexForCard(Z,q)))+1:T;if(y&&((J=m==null?void 0:m.slots)!=null&&J.length)){const Z=s.getSlotDefinitionForIndex(m.slots,U);Z&&(z=s.getSlotExpectedChartType(Z),G=Z.label||`Tab ${U+1}`,V=Z.description||"")}const W={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,W)}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}),l({...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=m==null?void 0:m.slots)!=null&&J.length)&&G>=0?s.getSlotDefinitionForIndex(m.slots,G):null,U=V?(Array.isArray(V.expectedType)?V.expectedType[0]:V.expectedType)||"table":F.type,W=y&&((Z=m==null?void 0:m.slots)==null?void 0:Z.length)&&m.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=>f(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}),l({...i,tabTitle:q})},children:F.tabTitle||F.title},F.id)]}),r.activeCardId===F.id&&!W&&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:()=>g(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:!P,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 je,be,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:o,setActiveTabCardId:d,setCard:l,setRunSql:x,mergeDraftsIntoCard:p,clearModeDrafts:u,initializeModeDrafts:m}=s.useEditorActions(),[N,y]=I.useState({}),[h,b]=I.useState(()=>new Set),{theme:S}=s.useTheme(),T=s.useDashboardStore(X=>X.themeStyle),{authToken:P}=s.useSemaphorContext(),O=s.getTokenParams(P==null?void 0:P.accessToken),L={mode:S||"system",colors:((be=(je=T==null?void 0:T.chart)==null?void 0:je.dataset)==null?void 0:be.backgroundColor)||[]},{getCard:f,manifest:w,isLoading:E}=s.useCustomVisual(((ve=i==null?void 0:i.customCardPreferences)==null?void 0:ve.url)||""),g=(Ne=i==null?void 0:i.customCardPreferences)==null?void 0:Ne.componentName,M=g?f(g):null,j=(Ie=w==null?void 0:w.visuals)==null?void 0:Ie.find(X=>X.name===g),k=s.resolveMultiInputType(i,j),D=a&&k==="multiple"&&!!i,B=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]),C=I.useMemo(()=>s.buildSlotOrderedCards(B),[B]),A=I.useMemo(()=>{const X=B.findIndex(oe=>(oe==null?void 0:oe.id)===n.id);return X<0?-1:s.getSlotIndexForCard(n,X)},[B,n]),v=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}:v!==n.type?{...n,type:v}:n,[n,v,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}))},[]),W=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}),Q=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)||""]),Y=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:Q,filterValues:se,selectedSheetId:ne}):{cardFilters:[],cardFilterValues:[]},[i,Z,q,Q,se,ne]);function $(X){const oe=t.cards.find(ue=>ue.id===X);oe&&(p(),H(X),d(X),u(),m(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};o(xe);const we=xe.cards.find(Ce=>Ce.id===X);we.sql&&x(!0),l(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=C.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:[B.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:W,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:C,slotTypes:oe,multiInputData:N,params:O,theme:L,filters:le,filterValues:[...he||[],..._||[]],inlineFilters:Y})})})})]})}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(at,{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(Ca,{isPreviewMode:D,onPreviewToggle:r,configCard:i})]})}function Ls({children:t}){var A;const n=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),r=s.useEditorStore(v=>v.isDevMode),i=s.useEditorStore(v=>v.isShowingVisual),c=s.useDashboardStore(v=>v.isVisualEditing),o=s.useEditorStore(v=>v.pythonStdOut),d=s.useEditorStore(v=>v.actions.setRunSql),l=fe.useEffectiveEditorCardType(),{setFrame:x,setCard:p,setActiveTabCardId:u,setCardPreferences:m,mergeDraftsIntoCard:N,clearModeDrafts:y,initializeModeDrafts:h}=s.useEditorActions(),b=I.useMemo(()=>l!==a.type?{...a,type:l}:a,[a,l]),{data:S,isLoading:T,isFetching:P,errorMessage:O,errorSql:L,refetch:f,pagination:w}=s.useDashboardCardQuery(b),{handleDebugWithAssistant:E}=tt(O,L),g=I.useMemo(()=>(S==null?void 0:S.records)||[],[S==null?void 0:S.records]),[M,j]=I.useState(!1);I.useEffect(()=>{P||j(!1)},[P]);function k(v,R){var G,V;const F={...a,paginationConfig:{page:v+1,pageSize:R}};p(F);const z={...n,cards:n.cards.map(U=>U.id===a.id?F:U)};x(z),a.sql&&((V=(G=a.preferences)==null?void 0:G.tablePrefs)!=null&&V.enableDevModePagination)&&d(!0)}function D(v){var G,V,U,W,J;const R=s.sortStateToSortByColumns(v,(G=a.config)==null?void 0:G.metricColumns,(V=a.config)==null?void 0:V.groupByColumns,(U=a.config)==null?void 0:U.detailColumns),F={...a,config:{...a.config||{},sortByColumns:R}};p(F);const z={...n,cards:n.cards.map(Z=>Z.id===a.id?F:Z)};x(z),a.sql&&((J=(W=a.preferences)==null?void 0:W.tablePrefs)!=null&&J.enableDevModePagination)&&d(!0)}function B(){const v=JSON.stringify(S==null?void 0:S.records,null,2),R=new Blob([v],{type:"application/json"}),F=URL.createObjectURL(R),z=document.createElement("a");z.href=F,z.download=`${a.title}.json`,z.click()}function C(){const R=[Object.keys(S==null?void 0:S.records.reduce((V,U)=>({...V,...U}),{})).join(","),...((S==null?void 0:S.records)||[]).map(V=>Object.values(V).join(","))].join(`
163
163
  `),F=new Blob([R],{type:"text/csv"}),z=URL.createObjectURL(F),G=document.createElement("a");G.href=z,G.download=`${a.title}.csv`,G.click()}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"})}),!["table","detailTable","custom"].includes(a.type)&&c&&e.jsx(pa,{})]}),!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:C,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:B,children:e.jsx(Pt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(S==null?void 0:S.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:T||P,onClick:()=>{j(!0),f()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":M})})}),e.jsx(nt,{})]}),r&&e.jsx(wa,{})]}),i?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[o&&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:o&&e.jsx(Sa,{})}),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":o}),children:[(S==null?void 0:S.records)&&(S==null?void 0:S.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:g,comparisonMetadata:(A=S==null?void 0:S.metadata)==null?void 0:A.comparisonMetadata,paginationMetadata:w,onPaginationChange:k,onSortChange:D,isLoading:T||P}),O&&e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(ls,{error:O,errorSql:L||a.sql||a.python,onDebugWithAssistant:E,showFeedbackButton:!1})})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Sa(){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 wa(){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,o]=I.useState(t),d=I.useRef(!1);I.useEffect(()=>{o(t)},[t]);const l=()=>{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,o(t),p.currentTarget.blur())};return e.jsx(s.Input,{type:a,placeholder:r,value:c,onChange:p=>o(p.target.value),onBlur:l,onKeyDown:x,className:i})}function De({defaultValue:t,label:n,options:a,value:r,onValueChange:i,className:c,icon:o,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:[o&&e.jsx("span",{children:o}),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(l=>e.jsx(s.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}function Ta(t,n){return s.getSlotDefinitionForIndex(t,n)||null}function Pe(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 Ea(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 Ia({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 l=n[c.position];We(l)||r.push({type:"missing-required",message:`${Pe(c.position)} ("${c.label}") is required but has no data configured.`});return}const o=c.position.match(/^(\d+)-(\d+)$/);if(o){const[,l,x]=o.map(Number);for(let p=l;p<=x;p+=1){const u=n[p];if(!We(u)){r.push({type:"missing-required",message:`${Pe(p)} ("${c.label}") is required but has no data configured.`});break}}return}const d=c.position.match(/^(\d+)\+$/);if(d){const l=Number(d[1]);if(n.length<=l){r.push({type:"missing-required",message:`${Pe(l)} ("${c.label}") is required but has no data configured.`});return}for(let x=l;x<n.length;x+=1){const p=n[x];if(!We(p)){r.push({type:"missing-required",message:`${Pe(x)} ("${c.label}") is required but has no data configured.`});break}}}}),n.forEach((c,o)=>{if(!c)return;const d=Ta(t,o);if(!d||!d.expectedType)return;const l=Ea(d.expectedType);l.length!==0&&(l.includes(c.type)||r.push({type:"wrong-type",message:`${Pe(o)} ("${d.label}") expects ${l.join(", ")}, but is configured as ${c.type}.`}))})),r}const ka={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 rt(){var k,D,B;const t=s.useEditorStore(C=>C.card.customCardPreferences),{data:n}=s.usePluginQuery(),a=(n==null?void 0:n.plugins)||[],r=s.useEditorStore(C=>C.card),i=s.useEditorStore(C=>C.frame),{setCustomCardPreferences:c}=s.useEditorActions(),o=I.useMemo(()=>s.findCustomVisualConfigCard(i,r),[i,r]),d=o==null?void 0:o.customCardPreferences,{components:l,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(C=>C.name===((d==null?void 0:d.componentName)||(t==null?void 0:t.componentName))),m=s.resolveMultiInputType(o||r,p)==="multiple",N=!!o&&o.id===r.id,y=(p==null?void 0:p.minInputs)??((D=o==null?void 0:o.customCardPreferences)==null?void 0:D.minInputs),h=(p==null?void 0:p.maxInputs)??((B=o==null?void 0:o.customCardPreferences)==null?void 0:B.maxInputs),b=I.useMemo(()=>s.getCustomVisualInputCards({frame:i,configCard:o||r,isMultiInputVisual:m}),[i,o,r,m]),S=I.useMemo(()=>s.buildSlotOrderedCards(b),[b]),T=I.useMemo(()=>S.map((C,A)=>{if(!C)return null;const v=s.getSlotIndexForCard(C,A),R=s.getEffectiveCardTypeForSlot(C,v,p==null?void 0:p.slots);return{...C,type:R??C.type}}),[S,p==null?void 0:p.slots]),P=I.useMemo(()=>Ia({slots:p==null?void 0:p.slots,cards:T,minInputs:y}),[p==null?void 0:p.slots,T,y]),O=I.useMemo(()=>{const C=b.findIndex(A=>(A==null?void 0:A.id)===r.id);return C<0?-1:s.getSlotIndexForCard(r,C)},[b,r]);function L(C){if(typeof C=="number")return`Tab ${C+1}`;const A=C.match(/^(\d+)-(\d+)$/);if(A){const[,R,F]=A;return`Tabs ${Number(R)+1}-${Number(F)+1}`}const v=C.match(/^(\d+)\+$/);return v?`Tabs ${Number(v[1])+1}+`:`Tab ${C}`}function f(C){return C?(Array.isArray(C)?C:[C]).join(", "):null}function w(C,A,v=[],R="",F,z,G){const V=E({key:A,defaultValue:R,settingsValue:z,sourceCard:G});return C==="input"?e.jsx(Se,{className:`h-8 w-full ${s.removeRing}`,value:String(V??""),onCommit:U=>{g({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}},A):C==="select"?e.jsx(De,{className:"h-8 w-full",label:"",options:v,value:String(V!==void 0?V:R??""),onValueChange:U=>{g({key:A,value:U,settingsField:F,settingsValue:z,sourceCard:G})}}):null}function E({key:C,defaultValue:A,settingsValue:v,sourceCard:R}){const F=v==null?void 0:v[C];return F!==void 0?F:C==="title"&&(R==null?void 0:R.title)!==void 0?R.title:C==="description"&&(R==null?void 0:R.description)!==void 0?R.description:A}function g({key:C,value:A,settingsField:v,settingsValue:R,sourceCard:F}){const z={...R||{}},G=C==="title"&&(F==null?void 0:F.title)!==void 0,V=C==="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[C]:z[C]=A,c({...t||{},[v]:z})}function M({settingsSchema:C,settingsField:A,settingsValue:v,sourceCard:R,headerLabel:F}){const z=Object.entries(C||{});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,v,R)]},G)})]})}function j(){return e.jsxs(e.Fragment,{children:[m&&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((C,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(C.position)}),e.jsx("span",{className:"text-muted-foreground",children:"•"}),e.jsx("span",{className:"font-medium",children:C.label})]}),C.description&&e.jsx("p",{className:"text-muted-foreground",children:C.description}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-muted-foreground",children:[f(C.expectedType)&&e.jsxs("span",{children:["Expected: ",f(C.expectedType)]}),C.required&&e.jsx("span",{children:"Required"})]})]},`${C.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`:""]})]})})]}),m&&P.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:P.map((C,A)=>e.jsx("li",{children:C.message},`${C.type}-${A}`))})})}),p&&!m&&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&&m&&(p.settings||p.slotSettings)&&e.jsxs("div",{className:"mt-4 space-y-4",children:[N&&p.settings&&e.jsx("div",{className:"px-2",children:M({settingsSchema:p.settings,settingsField:"settings",settingsValue:t==null?void 0:t.settings,sourceCard:o||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 C=r.tabTitle||r.title,A=O>=0?O:0,v=N?"Slot 0":`Slot ${A}`;return C?`${v}: ${C} Settings`:`${v} 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:[(!m||N)&&e.jsx(De,{icon:e.jsx(Us,{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:C=>c({...t||{url:"",componentName:""},url:C})}),m&&!N&&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&&(!m||N)&&e.jsx(e.Fragment,{children:l&&e.jsx(De,{icon:e.jsx(Rt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(l==null?void 0:l.map(C=>({value:C.name,label:C.name})))||[],value:t.componentName||"",onValueChange:C=>{var R;const A=(R=x==null?void 0:x.visuals)==null?void 0:R.find(F=>F.name===C),v=l==null?void 0:l.find(F=>F.name===C);c({...t,componentName:C,visualType:(A==null?void 0:A.visualType)||(v==null?void 0:v.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:C=>C.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:ka,children:p.docs.dataSchema})})]}),(()=>{var A;const C=(A=p.docs)==null?void 0:A.useCases;return!C||C.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:C.map((v,R)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-1 text-primary",children:"•"}),e.jsx("span",{children:v})]},R))})]})})()]})})]})]})}),e.jsx(s.AccordionContent,{children:j()})]})]})}function Aa({colorRanges:t,setColorRanges:n}){const a={start:-1/0,end:100,color:""};function r(o,d,l){const x=[...t];x[o]={...x[o],[d]:l},n(x)}function i(o){const d=[...t];d.splice(o,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((o,d)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:l=>r(d,"start",l.target.value),value:o.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:o.end,onChange:l=>r(d,"end",l.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:l=>r(d,"color",l.target.value),value:o.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 Da(){var p,u,m,N,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,S;return(S=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.decimalPlaces});const c=s.useEditorStore(h=>{var b,S;return(S=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.locale}),o=s.useEditorStore(h=>{var b,S;return(S=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.currency});s.useEditorStore(h=>h.actions.setFilterOnClickField);const d=s.useEditorStore(h=>{var b,S;return(S=(b=h.card.preferences)==null?void 0:b.formatNumber)==null?void 0:S.colorRanges})||[],l=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"})]}),(((u=t==null?void 0:t.formatNumber)==null?void 0:u.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,S,T;return i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",h,((T=t==null?void 0:t.formatNumber)==null?void 0:T.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:o||"none",onValueChange:h=>{var b,S,T;console.log("currency",h),i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,h==="none"?"":h,((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.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:((N=(m=t==null?void 0:t.formatNumber)==null?void 0:m.decimalPlaces)==null?void 0:N.toString())||"0",onValueChange:h=>{var b,S,T;return i(Number(h),((b=t==null?void 0:t.formatNumber)==null?void 0:b.currency)||"",((S=t==null?void 0:t.formatNumber)==null?void 0:S.locale)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.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,S,T;return i(((b=t==null?void 0:t.formatNumber)==null?void 0:b.decimalPlaces)||0,((S=t==null?void 0:t.formatNumber)==null?void 0:S.currency)||"",((T=t==null?void 0:t.formatNumber)==null?void 0:T.locale)||"",h.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(Aa,{colorRanges:d,setColorRanges:l})]})]})}const La={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 lt(t){return La[t]}function Ma({chartType:t,showDocsLink:n=!0}){const a=lt(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 Oa({chartType:t}){return lt(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(Ma,{chartType:t})})]}):null}function $e({chartType:t,suffix:n="Configuration"}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium",children:n}),e.jsx(Oa,{chartType:t})]})}function Fa(){return e.jsxs("div",{className:"space-y-6 px-6 py-4",children:[e.jsx($e,{chartType:"kpi"}),e.jsx("section",{children:e.jsx(Da,{})})]})}function Ms({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 o(x,p){var u,m;p?a!=null&&a.onClickFilter&&((u=a==null?void 0:a.onClickFilter)==null?void 0:u.length)>0?i({...a,onClickFilter:[...a.onClickFilter,{columnIndex:x,expression:""}]}):i({...a,onClickFilter:[{columnIndex:x,expression:""}]}):(i({...a,onClickFilter:(m=a==null?void 0:a.onClickFilter)==null?void 0:m.filter(N=>N.columnIndex!==x)}),n(N=>{const y=[...N];return y[x]=!1,y}))}function d(x,p){var m;const u=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.map(N=>N.columnIndex===x?{...N,expression:p.target.value}:N);i({...a,onClickFilter:u})}function l(x){var p,u,m,N;if(t!=null&&t[x]||(u=(p=a==null?void 0:a.onClickFilter)==null?void 0:p.find(y=>y.columnIndex===x))!=null&&u.expression)return e.jsx(s.Input,{value:(N=(m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(y=>y.columnIndex===x))==null?void 0:N.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 u,m;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:!!((u=a==null?void 0:a.onClickFilter)!=null&&u.find(N=>N.columnIndex===p)),onCheckedChange:N=>o(p,N)}),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:((m=a==null?void 0:a.onClickFilter)==null?void 0:m.find(N=>N.columnIndex===p))&&e.jsx(s.Pencil,{onClick:()=>{n(N=>{const y=[...N];return y[p]=!N[p],y})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(p)]})},x)})})}const Ra=[{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"}],Pa=["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"],Ba=Pa.map(t=>({label:t,value:t}));function Va(){var l,x,p,u,m,N,y,h,b,S,T,P,O,L,f,w,E,g;const t=s.useEditorStore(M=>M.card),n=(x=(l=t==null?void 0:t.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:x.topoJsonUrl,[a,r]=I.useState(((u=(p=t==null?void 0:t.preferences)==null?void 0:p.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:i}=s.useEditorActions(),{data:c}=s.useTopoJson(t),o=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(Ms,{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:o,value:((N=(m=t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:N.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:Ra,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:Ba,value:((S=(b=t.preferences)==null?void 0:b.mapVisualOptions)==null?void 0:S.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(Ms,{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:((P=(T=t.preferences)==null?void 0:T.mapVisualOptions)==null?void 0:P.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:((f=(L=(O=t.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:L.projectionOffset)==null?void 0:f[0])||0,onChange:M=>{var j,k,D,B;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[Number(M.target.value),((B=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:B[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((g=(E=(w=t.preferences)==null?void 0:w.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:g[1])||0,onChange:M=>{var j,k,D,B;i({...t.preferences,mapVisualOptions:{...(j=t.preferences)==null?void 0:j.mapVisualOptions,projectionOffset:[((B=(D=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:D.projectionOffset)==null?void 0:B[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,o]=I.useState(100),[d,l]=I.useState(50),[x,p]=I.useState(t);I.useEffect(()=>{const b=Os(t);if(b){const S=Fs(b.r,b.g,b.b);i(S.h),o(S.s),l(S.l),p(t)}},[t]);const u=b=>{i(b),N(b,c,d)},m=b=>{const S=b.currentTarget.getBoundingClientRect(),T=Math.max(0,Math.min(1,(b.clientX-S.left)/S.width)),P=Math.max(0,Math.min(1,(b.clientY-S.top)/S.height)),O=T*100,L=(1-P)*100;o(O),l(L),N(r,O,L)},N=(b,S,T)=>{const P=$a(b,S,T),O=za(P.r,P.g,P.b);p(O)},y=b=>{if(p(b),/^#[0-9A-Fa-f]{6}$/.test(b)){const S=Os(b);if(S){const T=Fs(S.r,S.g,S.b);i(T.h),o(T.s),l(T.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:m,onMouseMove:b=>{b.buttons===1&&m(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=>u(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 Os(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 za(t,n,a){return"#"+((1<<24)+(t<<16)+(n<<8)+a).toString(16).slice(1)}function Fs(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,o=0;const d=(r+i)/2;if(r!==i){const l=r-i;switch(o=d>.5?l/(2-r-i):l/(r+i),r){case t:c=((n-a)/l+(n<a?6:0))/6;break;case n:c=((a-t)/l+2)/6;break;case a:c=((t-n)/l+4)/6;break}}return{h:Math.round(c*360),s:Math.round(o*100),l:Math.round(d*100)}}function $a(t,n,a){t/=360,n/=100,a/=100;let r,i,c;if(n===0)r=i=c=a;else{const o=(x,p,u)=>(u<0&&(u+=1),u>1&&(u-=1),u<.16666666666666666?x+(p-x)*6*u:u<.5?p:u<.6666666666666666?x+(p-x)*(.6666666666666666-u)*6:x),d=a<.5?a*(1+n):a+n-a*n,l=2*a-d;r=o(l,d,t+1/3),i=o(l,d,t),c=o(l,d,t-1/3)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(c*255)}}const Rs=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],qa=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Le({value:t,onChange:n,label:a}){const[r,i]=I.useState(!1),[c,o]=I.useState(!1),d=()=>{const l=Rs.find(x=>x.value===t);return l?l.color:t.startsWith("#")?t:Rs[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:qa.map(l=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",d()===l?"border-gray-900":"border-transparent"),style:{backgroundColor:l},onClick:()=>{n(l),i(!1)},children:e.jsx("span",{className:"sr-only",children:l})},l))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{o(!0),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:()=>o(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:d(),onColorChange:l=>{n(l),o(!1)},onClose:()=>o(!1)})})]})]})}const Ka=["auto","number","currency","percent","scientific","date"],Ga=[{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"}],Ua=[{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"}],_a=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,l)=>{n({...t,[d]:l})},o=()=>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:Ka.map(d=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:d==="auto"?"Auto (Default)":_a(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??o(),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:Ga.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:Ua.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 Ha(){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 l=i(d,"frame");a({...n,filterId:l})}const o=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(Ja,{onSelect:c,columns:r}),o&&e.jsx(s.FilterHeader,{filter:o})]})}function Ja({columns:t,onSelect:n}){var o;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?((o=t.find(d=>d.name===i))==null?void 0:o.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:l=>{const x=l===i?"":l;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 Ya=[{value:"difference",label:"Difference"},{value:"change",label:"Change (%)"},{value:"change_difference",label:"Change + Difference"},{value:"ratio",label:"Ratio"}],Qa=[{value:"arrow_badge",label:"Arrow + Badge"},{value:"arrow",label:"Arrow Only"},{value:"badge",label:"Badge Only"},{value:"none",label:"None"}];function Wa({cardType:t="table"}){var p,u,m,N,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"),o=((u=a==null?void 0:a.tableVisualOptions)==null?void 0:u.metricComparison)||{},d=h=>{r({...a,tableVisualOptions:{...a==null?void 0:a.tableVisualOptions,metricComparison:{...o,...h}}})},l={increase:((m=o.colors)==null?void 0:m.increase)||"green",decrease:((N=o.colors)==null?void 0:N.decrease)||"red",neutral:((y=o.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(Js,{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:o.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:Ya.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:o.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:o.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:Qa.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:l.increase,onChange:h=>d({colors:{...l,increase:h}}),label:"Increase"}),e.jsx(Le,{value:l.decrease,onChange:h=>d({colors:{...l,decrease:h}}),label:"Decrease"}),e.jsx(Le,{value:l.neutral,onChange:h=>d({colors:{...l,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:o.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(Ha,{})]})]})]}),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 Xa(){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 Za(){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(Xa,{})]})]})}const en=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function sn(){var L,f,w,E,g,M,j,k,D,B;const t=s.useEditorStore(C=>C.card),n=s.useEditorStore(C=>{var A;return(A=C.card)==null?void 0:A.preferences}),a=fe.useEffectiveEditorCardType(),{setCardPreferences:r,updateCardInFrame:i}=s.useEditorActions(),c=I.useMemo(()=>a!==t.type?{...t,type:a}:t,[t,a]),{data:o}=s.useDashboardCardQuery(c),[d,l]=I.useState({}),[x,p]=I.useState(null),[u,m]=I.useState(null),N=I.useMemo(()=>{var R,F,z,G,V,U,W;if(!(o!=null&&o.records)||o.records.length===0)return[];const C=a==="stackedBar"||a==="stackedLine",A=a==="bar"||a==="line"||a==="horizontalBar"||a==="bullet"||a==="combo"||a==="area"||a==="stackedArea",v=((R=t==null?void 0:t.config)==null?void 0:R.pivotByColumns)&&t.config.pivotByColumns.length>0;if((C||A)&&v){if(o.pivotSchema&&Array.isArray(o.pivotSchema)){const J=new Set;return o.pivotSchema.forEach(Z=>{Z.alias&&J.add(Z.alias)}),Array.from(J)}if(o.records.length>0){const J=o.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 Q=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(ne=>{const _=ne.alias||ne.name;Q.add(_),Q.add(`${_}_count`),Q.add(`${_}_sum`),Q.add(`${_}_avg`),Q.add(`${_}_min`),Q.add(`${_}_max`);const Y=ne.entityName||ne.qualifiedEntityName;Y&&(Q.add(`${Y}_${_}`),Q.add(`${Y}_${_}_count`))}),Z.filter(ne=>!q.has(ne)&&!Q.has(ne))}}if((A||C)&&!v&&((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((W=(U=t==null?void 0:t.config)==null?void 0:U.groupByColumns)!=null&&W.length){const J=t.config.groupByColumns[0],Z=J.label||J.name,q=new Set;return o.records.forEach(Q=>{const se=Q[Z];se!=null&&q.add(String(se))}),Array.from(q)}return[]},[o,(L=t==null?void 0:t.config)==null?void 0:L.groupByColumns,(f=t==null?void 0:t.config)==null?void 0:f.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 C={};N.forEach((A,v)=>{C[A]=s.getColorForValue(A,v,n==null?void 0:n.colorConfig)}),l(C)},[N,n==null?void 0:n.colorConfig,y]);const h=(C,A)=>{const v={...d,[C]:A};l(v);const R={...n||{},colorConfig:{segments:v}};r(R);const F={...t,preferences:R};i(F)},b=(C,A)=>{var V;const v=y[A%y.length],{[C]: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),l(U=>({...U,[C]:v}))};if(!N.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((g=(E=t==null?void 0:t.config)==null?void 0:E.groupByColumns)==null?void 0:g.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 P=()=>{const C={...n||{},colorConfig:{segments:{}}};r(C);const A={...t,preferences:C};i(A);const v={};N.forEach((R,F)=>{v[R]=s.getColorForValue(R,F,void 0)}),l(v)},O=Object.keys(((B=n==null?void 0:n.colorConfig)==null?void 0:B.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(Ut,{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:P,children:[e.jsx(Es,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:N.map((C,A)=>{const v=s.isDefaultColor(d[C],A),R=!v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:x===C,onOpenChange:F=>p(F?C: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[C]}})}),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[C]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{h(C,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:en.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",d[C]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{h(C,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:()=>{m({value:C,color:d[C]}),p(null)},children:"Custom color"}),!v&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{b(C,A),p(null)},children:[e.jsx(Es,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:C}),R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},C)})}),u&&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:()=>m(null)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(it,{color:u.color,onColorChange:C=>{h(u.value,C),m(null)},onClose:()=>m(null)})})]})]})})]})}function Te({value:t,onSave:n,placeholder:a="",type:r="text",className:i=""}){const[c,o]=I.useState(t??""),[d,l]=I.useState(!1);I.useEffect(()=>{o(t??"")},[t]);const x=()=>{n(c),l(!1)},p=()=>{o(t??""),l(!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:u=>{o(u.target.value),l(!0)},onFocus:()=>l(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&d&&c!==t?x():u.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:o}){var N,y,h,b,S,T,P,O,L,f,w,E,g,M;const d=(j,k)=>{i({...r??{},[j]:k})},l=(j,k)=>{var A,v,R,F;const D=j==="enabled"&&k===!0,B=(A=r==null?void 0:r.name)==null?void 0:A.text,C=D&&!B&&c;i({...r??{},name:{...r==null?void 0:r.name,enabled:j==="enabled"?k:((v=r==null?void 0:r.name)==null?void 0:v.enabled)??!1,text:j==="text"?k:C?c:B,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,B;i({...r??{},labels:{enabled:j==="enabled"?k:((D=r==null?void 0:r.labels)==null?void 0:D.enabled)??!0,rotation:j==="rotation"?k:(B=r==null?void 0:r.labels)==null?void 0:B.rotation}})},p=(j,k)=>{i({...r??{},scale:{...r==null?void 0:r.scale,[j]:k===""?"auto":Number(k)}})},u=t==="x"?["auto","top","bottom"]:["auto","left","right"],m=["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:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,onCheckedChange:j=>l("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=>l("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=>l("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:((S=r==null?void 0:r.name)==null?void 0:S.fontWeight)||"normal",onValueChange:j=>l("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"})]})]})]})]})]})]}),!o&&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:u.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:((T=r==null?void 0:r.labels)==null?void 0:T.enabled)!==!1,onCheckedChange:j=>x("enabled",j)})]}),((P=r==null?void 0:r.labels)==null?void 0:P.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:m.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"||((f=r==null?void 0:r.scale)==null?void 0:f.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:((g=r==null?void 0:r.scale)==null?void 0:g.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,o,d;if(t==="x"){const l=(o=(c=n==null?void 0:n.config)==null?void 0:c.groupByColumns)==null?void 0:o[0];return(l==null?void 0:l.label)||(l==null?void 0:l.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 l=r.filter((x,p)=>{const u=i.find(m=>m.idx===p);return!u||u.yAxisId!=="y2"});return l.length===1&&(l[0].label||l[0].name)||""}if(t==="y2"){const l=r.filter((x,p)=>{const u=i.find(m=>m.idx===p);return(u==null?void 0:u.yAxisId)==="y2"});return l.length===1&&(l[0].label||l[0].name)||""}return""}function tn(){const t=s.useEditorStore(l=>l.card),n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),{setCardPreferences:a,updateCardInFrame:r}=s.useEditorActions(),i=fe.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 o=(l,x)=>{let p;l==="x"?p="xAxisConfig":l==="y"?p="yAxisConfig":p="secondaryYAxisConfig";const u={...n||{},[p]:x};a(u);const m={...t,preferences:u};r(m)},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(Ys,{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:l=>o("x",l),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:l=>o("y",l),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:l=>o("y2",l),defaultTitle:Ze("y2",t,n),hidePosition:!0})]})})]})}function an(){const t=s.useEditorStore(u=>u.card),n=fe.useEffectiveEditorCardType(),a=s.useEditorStore(u=>{var m,N,y,h;return(h=(y=(N=(m=u.card)==null?void 0:m.preferences)==null?void 0:N.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,o=(i==null?void 0:i.position)??"top",d=(i==null?void 0:i.align)??"center",l=(u,m)=>{const N={...a,[u]:m};r(N)},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(zt,{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:u=>l("display",u)})]}),((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)||o,onValueChange:u=>l("position",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:x.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]}),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:u=>l("align",u),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:p.map(u=>e.jsx(s.SelectItem,{value:u,className:"text-xs",children:s.titleCase(u)},u))})]})]})]})]})})]})}function nn(){var A,v,R,F,z,G,V,U,W,J,Z;const t=s.useEditorStore(q=>q.card),n=fe.useEffectiveEditorCardType(),a=s.useEditorStore(q=>{var Q,se;return(se=(Q=q.card)==null?void 0:Q.preferences)==null?void 0:se.dataLabelsConfig}),r=s.useEditorStore(q=>{var Q;return(Q=q.card)==null?void 0:Q.preferences}),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(n))return null;const o=n==="bullet"?((A=r==null?void 0:r.bulletConfig)==null?void 0:A.orientation)??(((v=r==null?void 0:r.chartOptions)==null?void 0:v.indexAxis)==="x"?"vertical":"horizontal"):void 0,d=o!=null?o==="horizontal":((R=r==null?void 0:r.chartOptions)==null?void 0:R.indexAxis)==="y",l=n==="stackedBar"||n==="stackedLine",x=n==="pie"||n==="doughnut"||n==="polarArea"||n==="funnel",p=!x,u=n==="bubble"||n==="scatter",m=(z=(F=r==null?void 0:r.chartOptions)==null?void 0:F.plugins)==null?void 0:z.datalabels,N=(m==null?void 0:m.display)!==!1&&((m==null?void 0:m.anchor)||(m==null?void 0:m.align)),y=s.getDefaultDataLabelsConfig(n,t.preferences),h=a??y,b=(y==null?void 0:y.enabled)??N??!1,S=(a==null?void 0:a.enabled)!==void 0?a.enabled:b,T=(q,Q)=>{const _={...y??{},...a??{},[q]:Q};q==="enabled"&&(_.display=Q,Q&&u&&!_.position&&(_.position="bottom")),q==="position"&&u&&(_.position="bottom");const Y={...t.preferences||{},dataLabelsConfig:_};i(Y);const le={...t,preferences:Y};c(le)},P=(q,Q)=>{const se=a??{},_={...y??{},...se,font:{...se.font||{},[q]:Q}},Y={...t.preferences||{},dataLabelsConfig:_};i(Y);const le={...t,preferences:Y};c(le)},O=(q,Q)=>{const se=a??{},_={...y??{},...se,formatOptions:{...se.formatOptions||{},[q]:Q}},Y={...t.preferences||{},dataLabelsConfig:_};i(Y);const le={...t,preferences:Y};c(le)},L=()=>{const q=n;return q==="stackedBar"||q==="stackedLine"||q==="pie"||q==="doughnut"?"center":d?"right":"top"},f=n!=="treemap"&&n!=="heatmap",w=n!=="treemap",E=L();let g=[];if(f)if(u)g=["bottom"];else if(l||x)g=["center"];else{const q=d?["center","left","right"]:["center","top","bottom"];g=["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"],B=[{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"}],C=[{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(Xt,{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:S,onCheckedChange:q=>T("enabled",q)})]}),S&&e.jsxs(e.Fragment,{children:[f&&!l&&!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:u?(h==null?void 0:h.position)||"bottom":(h==null?void 0:h.position)||"auto",onValueChange:q=>T("position",q),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:g.map(q=>e.jsx(s.SelectItem,{value:q,className:"text-xs",children:q==="auto"?M():q==="custom"?"Custom (Advanced)":s.titleCase(q)},q))})]})]}),l&&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=>T("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=>T("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=>T("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=>T("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:B.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:((W=h==null?void 0:h.formatOptions)==null?void 0:W.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:C.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=>P("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=>P("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"&&T("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=>T("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%
164
164
  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 rn(){var m,N,y,h,b,S,T,P,O,L;const t=s.useEditorStore(f=>f.card),{setCardPreferences:n}=s.useEditorActions(),a=fe.useEffectiveEditorCardType(),r=((m=t.config)==null?void 0:m.metricColumns)||[],i=((N=t.config)==null?void 0:N.groupByColumns)||[],c=r.length===2&&i.length===0,o=r.some(f=>f.comparisonType&&f.comparisonType!=="none");if(!(a==="kpi"&&(c||o)))return null;const l=((h=(y=t.preferences)==null?void 0:y.kpiVisualOptions)==null?void 0:h.metricComparison)||{},x=f=>{var E;const w={...t.preferences,kpiVisualOptions:{...(E=t.preferences)==null?void 0:E.kpiVisualOptions,metricComparison:{...l,...f}}};n(w)},p=o||l.enabled,u=r.some(f=>f.comparisonType==="previous_period"||f.comparisonType==="same_period_last_year"||f.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(Js,{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:l.enabled||!1,onCheckedChange:f=>x({enabled:f,...f&&!l.calculationType?{calculationType:"difference"}:{}})})]}),p&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(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 f=l.calculationType||"difference",w=Ps[f];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:l.calculationType||"difference",onValueChange:f=>x({calculationType:f}),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(([f,w])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:w.label},f))})]})]}),e.jsx(qe,{formatOptions:l.formatOptions||{},onFormatOptionsChange:f=>x({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(u||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:l.position||"right",onValueChange:f=>x({position:f}),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:l.showArrow!==!1,onCheckedChange:f=>x({showArrow:f})}),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:l.showColor!==!1,onCheckedChange:f=>x({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),l.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Le,{value:((b=l.colorConfig)==null?void 0:b.increase)||"green",onChange:f=>x({colorConfig:{...l.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Le,{value:((S=l.colorConfig)==null?void 0:S.decrease)||"red",onChange:f=>x({colorConfig:{...l.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Le,{value:((T=l.colorConfig)==null?void 0:T.noChange)||"neutral",onChange:f=>x({colorConfig:{...l.colorConfig,noChange:f}}),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:l.conditionalLabel||!1,onCheckedChange:f=>x({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),l.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((P=l.conditionalLabels)==null?void 0:P.increase)??"Increase",onChange:f=>x({conditionalLabels:{...l.conditionalLabels,increase:f.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=l.conditionalLabels)==null?void 0:O.decrease)??"Decrease",onChange:f=>x({conditionalLabels:{...l.conditionalLabels,decrease:f.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=l.conditionalLabels)==null?void 0:L.noChange)??"No change",onChange:f=>x({conditionalLabels:{...l.conditionalLabels,noChange:f.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:l.labelName??"",onChange:f=>x({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function ln(){var c,o;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(fe.useEffectiveEditorCardType()!=="kpi")return null;const r=((o=(c=t.preferences)==null?void 0:c.kpiVisualOptions)==null?void 0:o.formatOptions)||{},i=d=>{var x;const l={...t.preferences,kpiVisualOptions:{...(x=t.preferences)==null?void 0:x.kpiVisualOptions,formatOptions:d}};n(l)};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 on(){var c;const t=s.useEditorStore(o=>{var d;return(d=o.card)==null?void 0:d.type}),n=s.useEditorStore(o=>{var d;return(d=o.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=o=>{const d={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,treemapColorMode:o}};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:o=>i(o??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(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 cn=Object.keys(s.HEATMAP_PRESET_PALETTES);function dn(){const t=s.useEditorStore(m=>m.card),n=s.useEditorStore(m=>{var N;return(N=m.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",i=(n==null?void 0:n.heatmapConfig)||{},c=i.colorPalette??"green",o=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]),l=m=>{const N={...i,...m};N.colorPalette!=="custom"?delete N.colorRange:(!N.colorRange||!N.colorRange[0]||!N.colorRange[1])&&(N.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),a({...n||{},heatmapConfig:N})},x=m=>{l({colorPalette:m,colorRange:m==="custom"?i.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},p=(m,N)=>{const y=[...d];y[m]=N,l({colorPalette:"custom",colorRange:y})},u=m=>{l({legendPosition:m})};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:m=>x(m??"blue"),className:"space-y-3",children:[cn.map(m=>{const N=s.HEATMAP_PRESET_PALETTES[m];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-${m}`,value:m}),e.jsxs(s.Label,{htmlFor:`heatmap-${m}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:N.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${N.start}, ${N.end})`}})]})]},m)}),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:m=>p(0,m),label:"Start color"}),e.jsx(Le,{value:d[1],onChange:m=>p(1,m),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:o,onValueChange:m=>u(m??"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(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:m[0].toUpperCase()+m.slice(1)},m))})]})]})]})]}):null}const Bs=["poor","satisfactory","good"];function Vs(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 un(){var D,B;const t=s.useEditorStore(C=>C.card.preferences),n=s.useEditorStore(C=>C.card),a=s.useEditorStore(C=>C.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,[l,x]=I.useState(c.showRanges??!1),[p,u]=I.useState(c.rangesArePercentages??!1),m=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d,[N,y]=I.useState(m);I.useEffect(()=>{x(c.showRanges??!1)},[c.showRanges]),I.useEffect(()=>{u(c.rangesArePercentages??!1)},[c.rangesArePercentages]);const h=c.targetValue===void 0?"":String(c.targetValue);I.useEffect(()=>{const C=c.disableAutoComparative?!1:c.comparativeMetricKey!==void 0||!d;y(C)},[c.disableAutoComparative,c.comparativeMetricKey,d]);const b=I.useMemo(()=>{var C,A;return((A=(C=n==null?void 0:n.config)==null?void 0:C.metricColumns)==null?void 0:A.map(v=>{const R=v.label||v.name||v.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 C={};let A=!1;const v=(V=b[1])==null?void 0:V.value;!c.targetMetricKey&&v&&(C.targetMetricKey=v,A=!0);const R=(U=b[2])==null?void 0:U.value;!c.comparativeMetricKey&&!c.disableAutoComparative&&R&&(C.comparativeMetricKey=R,A=!0);const F=b.slice(3),z={...c.rangeKeys||{}};let G=!1;if(Bs.forEach((W,J)=>{!z[W]&&F[J]&&(z[W]=F[J].value,G=!0)}),G&&(C.rangeKeys=z,A=!0,c.showRanges===void 0&&(C.showRanges=!0)),A){const W=Vs({...c,...C});r({...t,bulletConfig:W})}},[b,c,t,r]);const S=C=>{const A=Vs({...c,...C});r({...t,bulletConfig:A})},T=(C,A)=>{const v={...c.rangeKeys||{},[C]:A.trim()};A.trim()||delete v[C],S({rangeKeys:Object.keys(v).length>0?v:void 0})},P=(C,A)=>{const v=A===""?void 0:Number(A),R={...c.ranges||{}};v===void 0||Number.isNaN(v)?delete R[C]:R[C]=v,S({ranges:Object.keys(R).length?R:void 0})},O=C=>{if(C===""){S({targetValue:void 0});return}const A=Number(C);S({targetValue:Number.isNaN(A)?void 0:A})},L=(C,A)=>{const v=A.trim(),R={...c.rangeLabels||{}};v?R[C]=v:delete R[C],S({rangeLabels:Object.keys(R).length>0?R:void 0})},f=C=>{x(C),S({showRanges:C})},w=C=>{u(C),S({rangesArePercentages:C})},E=c.orientation||(((B=t==null?void 0:t.chartOptions)==null?void 0:B.indexAxis)==="y"?"horizontal":"vertical"),g=C=>{S({orientation:C}),i(C==="horizontal"?"y":"x")},M=[{value:"__none",label:"None"},...b.map(C=>({value:C.value,label:C.label}))],j=M,k=C=>{if(y(C),!C){S({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!d){S({disableAutoComparative:!1});return}if(c.comparativeMetricKey)S({disableAutoComparative:!1});else{const A=b.find(v=>v.value!==c.targetMetricKey);S({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:C=>g(C),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:C=>S({targetMetricKey:C==="__none"?void 0:C}),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(C=>e.jsx(s.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.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:C=>S({comparativeMetricKey:C==="__none"?void 0:C,disableAutoComparative:C==="__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(C=>e.jsx(s.SelectItem,{value:C.value,className:"text-xs",children:C.label},C.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:N,onCheckedChange:C=>k(C)})]}),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:l,onCheckedChange:f})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:p,disabled:!l,onChange:C=>w(C.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),l&&e.jsx("div",{className:"space-y-3",children:Bs.map(C=>{var A,v,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:[C," LABEL"]}),e.jsx(Se,{placeholder:`Display label (${C})`,value:((A=c.rangeLabels)==null?void 0:A[C])||"",onCommit:G=>L(C,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:[C," COLUMN"]}),e.jsxs(s.Select,{value:((v=c.rangeKeys)==null?void 0:v[C])||"__none",onValueChange:G=>{G==="__none"?T(C,""):T(C,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:[C," COLUMN KEY"]}),e.jsx(Se,{placeholder:"Column key",value:((R=c.rangeKeys)==null?void 0:R[C])||"",onCommit:G=>T(C,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:[C," VALUE"]}),e.jsx(Se,{type:"number",placeholder:p?"0.80":"Static value",value:((F=c.ranges)==null?void 0:F[C])===void 0?"":String((z=c.ranges)==null?void 0:z[C]),onCommit:G=>P(C,G),className:"h-8 text-xs"})]})]},C)})})]})]})]})}function zs(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 mn(){var L,f,w,E,g,M,j,k,D,B,C,A;const t=s.useEditorStore(v=>v.card.preferences),n=s.useEditorStore(v=>v.card),a=fe.useEffectiveEditorCardType(),r=s.useEditorStore(v=>v.isDevMode),{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions(),o=a==="bubble",d=a==="scatter",l=I.useMemo(()=>(t==null?void 0:t.bubbleScatterConfig)||{},[t==null?void 0:t.bubbleScatterConfig]),p=s.hasValidCardConfig(n==null?void 0:n.config)&&!r,u=I.useMemo(()=>{var v,R;return((R=(v=n==null?void 0:n.config)==null?void 0:v.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]),m=I.useMemo(()=>{var v,R;return((R=(v=n==null?void 0:n.config)==null?void 0:v.groupByColumns)==null?void 0:R.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(f=n==null?void 0:n.config)==null?void 0:f.groupByColumns]),N=I.useMemo(()=>l.enableGrouping!==void 0?l.enableGrouping:!r&&m.length>=2,[l.enableGrouping,r,m.length]),[y,h]=I.useState(N);I.useEffect(()=>{h(N)},[N]);const b=v=>{const R={...t||{},bubbleScatterConfig:v};i(R),n&&c({...n,preferences:R})},S=v=>{i(v),n&&c({...n,preferences:v})};I.useEffect(()=>{if(!t||u.length===0)return;const v={};let R=!1;if(!l.xMetricKey&&u[0]&&(v.xMetricKey=u[0].value,R=!0),!l.yMetricKey&&u[1]&&(v.yMetricKey=u[1].value,R=!0),o&&!l.radiusMetricKey&&u[2]&&(v.radiusMetricKey=u[2].value,R=!0),!l.labelKey&&m[0]&&(v.labelKey=m[0].value,R=!0),N&&!l.groupKey&&m[1]&&(v.groupKey=m[1].value,v.enableGrouping=!0,R=!0),R){const F=zs({...l,...v});b(F)}},[u,m,l,t,i,o,N]);const T=v=>{const R=zs({...l,...v});b(R)},P=v=>{h(v),T({enableGrouping:v,groupKey:v?l.groupKey:void 0})};if(!o&&!d)return null;const O=o?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:[o?"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:l.labelKey||"",onValueChange:v=>T({labelKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select label column"})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for labels",value:l.labelKey||"",onCommit:v=>T({labelKey:v})})]}),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:P})]}),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:l.groupKey||"",onValueChange:v=>T({groupKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select group column"})}),e.jsx(s.SelectContent,{children:m.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for grouping",value:l.groupKey||"",onCommit:v=>T({groupKey:v})})]})]}),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:l.xMetricKey||"",onValueChange:v=>T({xMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select X metric"})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for X axis",value:l.xMetricKey||"",onCommit:v=>T({xMetricKey:v})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Y Axis"}),p?e.jsxs(s.Select,{value:l.yMetricKey||"",onValueChange:v=>T({yMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select Y metric"})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for Y axis",value:l.yMetricKey||"",onCommit:v=>T({yMetricKey:v})})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Radius"}),p?e.jsxs(s.Select,{value:l.radiusMetricKey||"",onValueChange:v=>T({radiusMetricKey:v}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select radius metric"})}),e.jsx(s.SelectContent,{children:u.map(v=>e.jsx(s.SelectItem,{value:v.value,children:v.label},v.value))})]}):e.jsx(Se,{className:"h-8 text-xs",placeholder:"Column name for radius",value:l.radiusMetricKey||"",onCommit:v=>T({radiusMetricKey:v})})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Radius Settings"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs",children:"Scale Mode"}),e.jsxs(s.Select,{value:l.radiusScale||"sqrt",onValueChange:v=>T({radiusScale:v}),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"})]})]})]}),l.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=l.minRadius)==null?void 0:w.toString())||"",onCommit:v=>T({minRadius:v?Number(v):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=l.maxRadius)==null?void 0:E.toString())||"",onCommit:v=>T({maxRadius:v?Number(v):void 0})})]})]}),l.radiusScale==="fixed"&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs(s.Label,{className:"text-xs",children:["Fixed Radius: ",l.fixedRadius||10]}),e.jsx(s.Slider,{value:[l.fixedRadius||10],onValueChange:([v])=>T({fixedRadius:v}),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: ",l.fixedRadius||5]}),e.jsx(s.Slider,{value:[l.fixedRadius||5],onValueChange:([v])=>T({fixedRadius:v}),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=(g=t==null?void 0:t.xAxisConfig)==null?void 0:g.name)==null?void 0:M.enabled)??!1,onCheckedChange:v=>{var z,G,V,U;const R=l.xMetricKey||"X Axis",F=l.yMetricKey||"Y Axis";S({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{enabled:v,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:v,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:l.xMetricKey||"X Axis",value:((B=(D=t==null?void 0:t.xAxisConfig)==null?void 0:D.name)==null?void 0:B.text)||"",onCommit:v=>{var R;S({...t??{},xAxisConfig:{...t==null?void 0:t.xAxisConfig,name:{...(R=t==null?void 0:t.xAxisConfig)==null?void 0:R.name,enabled:!0,text:v||l.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:l.yMetricKey||"Y Axis",value:((A=(C=t==null?void 0:t.yAxisConfig)==null?void 0:C.name)==null?void 0:A.text)||"",onCommit:v=>{var R;S({...t??{},yAxisConfig:{...t==null?void 0:t.yAxisConfig,name:{...(R=t==null?void 0:t.yAxisConfig)==null?void 0:R.name,enabled:!0,text:v||l.yMetricKey||"Y Axis"}}})}})]})]})]})]})]})}const xn=[{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 hn(){const t=s.useEditorStore(m=>m.card),n=s.useEditorStore(m=>{var N;return(N=m.card)==null?void 0:N.preferences}),{setCardPreferences:a}=s.useEditorActions(),r=(t==null?void 0:t.type)==="funnel",i=(n==null?void 0:n.funnelConfig)||{},c=i.percentMode??"percentOfTotal",o=i.shrinkFraction??1,d=i.labelThreshold??0,l=m=>{const N={...i,...m};a({...n||{},funnelConfig:N})},x=m=>{l({percentMode:m})},p=m=>{l({shrinkFraction:m[0]})},u=m=>{l({labelThreshold:m[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:m=>x(m),className:"space-y-2",children:xn.map(m=>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-${m.value}`,value:m.value,className:"mt-0.5"}),e.jsxs(s.Label,{htmlFor:`funnel-${m.value}`,className:"flex flex-col gap-0.5 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.description})]})]},m.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:[o],onValueChange:p,min:0,max:1,step:.1,className:"flex-1"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"Full Shrink"})]}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Current: ",Math.round(o*100),"%"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:u,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:o}=s.getKeys(c);i=o.slice(1)}return{transformedMetricKeys:i,dimensionKeys:a.slice(0,1),keys:a,defaultMetricKeys:r}}const pn=[{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"}],gn=[{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)"}],fn=["center","start","end"],jn=["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,S,T,P;const o=i??(a?["auto","center","left","right","custom"]:["auto","center","top","bottom","custom"]),d=r?["auto","number","currency","percent","none"]:["number","currency","percent","none"],l=(O,L)=>{const f={...t,[O]:L};n(f)},x=(O,L)=>{const f={...t,font:{...(t==null?void 0:t.font)||{},[O]:L}};n(f)},p=(O,L)=>{const f={...t,formatOptions:{...(t==null?void 0:t.formatOptions)||{},[O]:L}};n(f)},u=()=>a?"Right":"Top",m=t||{},N=m.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:m.position||"auto",onValueChange:O=>l("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:o.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?u():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),m.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:m.anchor||"center",onValueChange:O=>l("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:fn.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(m.align||"center"),onValueChange:O=>l("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-24 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:jn.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:N,onValueChange:O=>l("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(N)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-border bg-background p-2",children:[["number","currency","percent"].includes(N)&&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=m.formatOptions)==null?void 0:y.decimalPlaces)??(N==="currency"?2:N==="percent"?1:0)),onSave:O=>p("decimalPlaces",Number(O)),className:""})})]}),N==="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=m.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:pn.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(N)&&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=m.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:((S=m.formatOptions)==null?void 0:S.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:gn.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(((T=m.font)==null?void 0:T.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:((P=m.font)==null?void 0:P.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:m.color==="auto"||!m.color?"auto":"custom",onValueChange:O=>{O==="auto"&&l("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(m.rotation||0),onSave:O=>l("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"°"})]})]})]})]})]})}const bn=[{type:"bar",icon:s.ChartColumnIncreasing,label:"Bar"},{type:"line",icon:s.ChartLine,label:"Line"}],yn=[0,1,2,3,4,5,6,8,10],vn=[{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 │"}],Nn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Cn(){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(Sn,{})})]})}function Sn(){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(wn,{metricKey:n,idx:a},n))})}function wn({metricKey:t,idx:n}){var S;const[a,r]=I.useState(!1),i=s.useEditorStore(T=>{var P;return(P=T.card)==null?void 0:P.preferences}),c=s.useEditorStore(T=>{var P,O;return(O=(P=T.card)==null?void 0:P.preferences)==null?void 0:O.datasetOptions}),o=c==null?void 0:c.find(T=>T.idx===n),{setCardPreferences:d}=s.useEditorStore(T=>T.actions),l=(o==null?void 0:o.type)||"bar",x=(o==null?void 0:o.yAxisId)||"y",p=((S=o==null?void 0:o.dataLabels)==null?void 0:S.enabled)??!1,u=l==="line"?s.ChartLine:s.ChartColumnIncreasing;function m(T){const P={idx:n,type:l,yAxisId:x,dataLabels:o==null?void 0:o.dataLabels,...T};if(!o)d({...i||{},datasetOptions:[...c||[],P]});else{const O=c==null?void 0:c.map(L=>L.idx===n?{...L,...P}:L);d({...i||{},datasetOptions:O})}}function N(T){m({type:T})}function y(T){m({yAxisId:T})}function h(T){m({dataLabels:{...o==null?void 0:o.dataLabels,enabled:T}})}function b(T){m({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.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(u,{className:"h-3 w-3"}),l==="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:bn.map(({type:T,icon:P,label:O})=>{const L=l===T;return e.jsxs("button",{onClick:()=>N(T),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(P,{className:"h-4 w-4"}),e.jsx("span",{children:O})]},T)})})]}),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:T=>y(T),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)"})]})]})]})]}),l==="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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:T=>m({lineStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Nn.map(({value:T,label:P})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:P},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((o==null?void 0:o.pointRadius)??3),onValueChange:T=>m({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:yn.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:(o==null?void 0:o.pointStyle)||"circle",onValueChange:T=>m({pointStyle:T}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:vn.map(({value:T,label:P})=>e.jsx(s.SelectItem,{value:T,className:"text-xs",children:P},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:p,onCheckedChange:h})]}),p&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:o==null?void 0:o.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"}],Tn=[0,1,2,3,4,5,6,8,10],En=[{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 │"}],In=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function kn(t){return t==null?"origin":t===!1?"false":t}function An(){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(Dn,{})})]})}function Dn(){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(Ln,{metricKey:n,idx:a},n))})}function Ln({metricKey:t,idx:n}){var h;const[a,r]=I.useState(!1),i=s.useEditorStore(b=>{var S;return(S=b.card)==null?void 0:S.preferences}),c=s.useEditorStore(b=>{var S,T;return(T=(S=b.card)==null?void 0:S.preferences)==null?void 0:T.datasetOptions}),o=c==null?void 0:c.find(b=>b.idx===n),{setCardPreferences:d}=s.useEditorStore(b=>b.actions),l=kn(o==null?void 0:o.fill),x=((h=o==null?void 0:o.dataLabels)==null?void 0:h.enabled)??!1,p=es.find(b=>b.value===l)||es[0];function u(b){const S={idx:n,fill:l,dataLabels:o==null?void 0:o.dataLabels,...b};if(!o)d({...i||{},datasetOptions:[...c||[],S]});else{const T=c==null?void 0:c.map(P=>P.idx===n?{...P,...S}:P);d({...i||{},datasetOptions:T})}}function m(b){u({fill:b==="false"?!1:b})}function N(b){u({dataLabels:{...o==null?void 0:o.dataLabels,enabled:b}})}function y(b){u({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:l,onValueChange:b=>m(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:(o==null?void 0:o.lineStyle)||"solid",onValueChange:b=>u({lineStyle:b}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:In.map(({value:b,label:S})=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:S},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((o==null?void 0:o.pointRadius)??3),onValueChange:b=>u({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:Tn.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:(o==null?void 0:o.pointStyle)||"circle",onValueChange:b=>u({pointStyle:b}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:En.map(({value:b,label:S})=>e.jsx(s.SelectItem,{value:b,className:"text-xs",children:S},b))})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Data Labels"}),e.jsx(s.SmallSwitch,{checked:x,onCheckedChange:N})]}),x&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:o==null?void 0:o.dataLabels,onChange:y,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Mn=[0,1,2,3,4,5,6,8,10],On=[{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 Fn(){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(Rn,{})})]})}function Rn(){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(Pn,{metricKey:n,idx:a},n))})}function Pn({metricKey:t,idx:n}){var b;const[a,r]=I.useState(!1),i=s.useEditorStore(S=>{var T;return(T=S.card)==null?void 0:T.preferences}),c=s.useEditorStore(S=>{var T,P;return(P=(T=S.card)==null?void 0:T.preferences)==null?void 0:P.datasetOptions}),o=c==null?void 0:c.find(S=>S.idx===n),{setCardPreferences:d}=s.useEditorStore(S=>S.actions),l=(o==null?void 0:o.lineStyle)||"solid",x=(o==null?void 0:o.pointRadius)??3,p=(o==null?void 0:o.pointStyle)||"circle",u=((b=o==null?void 0:o.dataLabels)==null?void 0:b.enabled)??!1,m=ss.find(S=>S.value===l)||ss[0];function N(S){const T={idx:n,lineStyle:l,pointRadius:x,pointStyle:p,dataLabels:o==null?void 0:o.dataLabels,...S};if(!o)d({...i||{},datasetOptions:[...c||[],T]});else{const P=c==null?void 0:c.map(O=>O.idx===n?{...O,...T}:O);d({...i||{},datasetOptions:P})}}function y(S){N({dataLabels:{...o==null?void 0:o.dataLabels,enabled:S}})}function h(S){N({dataLabels:S})}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"}),m.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:l,onValueChange:S=>N({lineStyle:S}),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:S,label:T})=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:T},S))})]})]}),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:S=>N({pointRadius:Number(S)}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Mn.map(S=>e.jsx(s.SelectItem,{value:String(S),className:"text-xs",children:S===0?"None":S},S))})]})]}),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:S=>N({pointStyle:S}),children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:On.map(({value:S,label:T})=>e.jsx(s.SelectItem,{value:S,className:"text-xs",children:T},S))})]})]})]})]}),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:u,onCheckedChange:y})]}),u&&e.jsx("div",{className:"rounded-md border border-border bg-background p-2",children:e.jsx(Ge,{config:o==null?void 0:o.dataLabels,onChange:h,isHorizontal:!1,showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const Bn=[0,2,4,6,8,10,12,16,20];function Vn(){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(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 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}),o=s.useEditorStore(h=>{var b,S;return(S=(b=h.card)==null?void 0:b.preferences)==null?void 0:S.datasetOptions}),d=o==null?void 0:o.find(h=>h.idx===n),{setCardPreferences:l}=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 u(h){const b={idx:n,borderRadius:x,dataLabels:d==null?void 0:d.dataLabels,...h};if(!d)l({...c||{},datasetOptions:[...o||[],b]});else{const S=o==null?void 0:o.map(T=>T.idx===n?{...T,...b}:T);l({...c||{},datasetOptions:S})}}function m(h){u({dataLabels:{...d==null?void 0:d.dataLabels,enabled:h}})}function N(h){u({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=>u({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:Bn.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:m})]}),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:N,isHorizontal:i==="horizontalBar",showAutoFormat:!0,showAppearance:!0})})]})]})})})]})})}const qn=[0,1,2,3,4,5,6,8,10],Kn=[{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 │"}],Gn=[{value:"solid",label:"Solid ───"},{value:"dashed",label:"Dashed - - -"},{value:"dotted",label:"Dotted ···"},{value:"dash-dot",label:"Dash-Dot -·-·"}];function Un(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=fe.useEffectiveEditorCardType(),r=n==null?void 0:n.lineStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["line","area","stackedArea"].includes(a))return null;const o=(d,l)=>{const x={...n||{},lineStyleConfig:{...r,[d]:l}};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(Yt,{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=>o("lineStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Gn.map(({value:d,label:l})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:l},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=>o("pointRadius",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},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=>o("pointStyle",d),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Kn.map(({value:d,label:l})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}const _n=[0,2,4,6,8,10,12,16,20],Hn=[{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%"}],Jn=[{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 Yn(){const t=s.useEditorStore(d=>d.card),n=s.useEditorStore(d=>{var l;return(l=d.card)==null?void 0:l.preferences}),a=fe.useEffectiveEditorCardType(),r=n==null?void 0:n.barStyleConfig,{setCardPreferences:i,updateCardInFrame:c}=s.useEditorActions();if(!t||!["bar","horizontalBar","stackedBar"].includes(a))return null;const o=(d,l)=>{const x={...n||{},barStyleConfig:{...r,[d]:l}};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=>o("borderRadius",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}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=>o("barPercentage",Number(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:l})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:l},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=>o("categoryPercentage",Number(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:l})=>e.jsx(s.SelectItem,{value:d,className:"text-xs",children:l},d))})]})]})]})})]})}function Qn(){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 Wn=["kpi"],$s={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 Xn(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 Zn(t){return{...t,role:"groupby"}}function er(){var T,P,O,L;const t=s.useEditorStore(f=>f.card),n=s.useEditorStore(f=>f.actions.updateCardConfig),a=fe.useEffectiveEditorCardType(),{scopedFields:r}=s.useScopedFields(),i=((T=t.config)==null?void 0:T.metricColumns)||[],c=((P=t.config)==null?void 0:P.summary)||{},o=c.breakdownDimensions||[],d=Wn.includes(a),l=i.length>0,x=c.enabled===!0,p=d&&l,u=((O=t.config)==null?void 0:O.comparisonType)||((L=i.find(f=>f.comparisonType&&f.comparisonType!=="none"))==null?void 0:L.comparisonType)||"none",m=$s[u]||$s.none,N=Array.from(new Map(r.filter(Xn).map(f=>[Re(f),Zn(f)])).values()),y=new Set(N.map(f=>Re(f))),h=new Set(o.map(f=>Re(f)).filter(f=>f&&y.has(f)));if(!d)return null;const b=f=>{n(t.id,{summary:{...c,...f}})},S=(f,w)=>{const E=Re(f),g=N.filter(j=>h.has(Re(j))),M=w?h.has(E)?g:[...g,f].slice(0,ts):g.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"}),!l&&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:f=>{if(!f){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: ",m]}),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:f=>b({showOnCard:f})})]}),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:f=>b({includeInDashboardSummary:f})})]}),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:[o.length,"/",ts]})]}),N.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:N.map(f=>{const w=Re(f),E=h.has(w),g=h.size>=ts,M=!x||!E&&g;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=>S(f,j===!0)}),e.jsx(s.Label,{htmlFor:`summary-breakdown-${w}`,className:"cursor-pointer text-xs",children:f.label||f.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:f=>b({anomalyEnabled:f})})]})]})]})}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(Cn,{}),(n==="area"||n==="stackedArea")&&e.jsx(An,{}),n==="line"&&e.jsx(Fn,{}),(n==="bar"||n==="horizontalBar"||n==="stackedBar")&&e.jsx(Vn,{}),e.jsx(Un,{}),e.jsx(Yn,{}),e.jsx(on,{}),t==="config"&&e.jsx(ln,{}),t==="config"&&e.jsx(rn,{}),t==="config"&&e.jsx(er,{}),e.jsx(dn,{}),n==="bullet"&&e.jsx(un,{}),n==="funnel"&&e.jsx(hn,{}),(n==="bubble"||n==="scatter")&&e.jsx(mn,{}),(n==="stackedBar"||n==="stackedLine")&&e.jsx(Qn,{}),e.jsx(sn,{}),e.jsx(tn,{}),e.jsx(an,{}),e.jsx(nn,{})]})}function sr(){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 tr(){const t=s.useEditorStore(a=>a.card.type);function n(){switch(t){case"kpi":return e.jsx(Fa,{});case"table":return e.jsx(Wa,{});case"map":return e.jsx(Va,{});case"custom":return e.jsx("div",{className:"px-6 py-2",children:e.jsx(rt,{})});case"text":return e.jsx(Za,{});default:return e.jsx(sr,{})}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[n(),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function ar(){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,o,d;r?((i=t.current)==null||i.resize(0),(c=n.current)==null||c.resize(0)):((o=t.current)==null||o.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(ca,{})}),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(tr,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ls,{})})]}):e.jsx(Ls,{})})]})}function nr(t){var he;s.useAIInteractionStore($=>$.currentAIContext);const[n,a]=I.useState(""),[r,i]=I.useState(null),{authToken:c,tokenProps:o}=s.useSemaphorContext(),d=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.sql}),l=s.useEditorStore($=>$.isDevMode),x=s.useEditorStore($=>{var H;return(H=$==null?void 0:$.card)==null?void 0:H.python}),{setCardPython:p,setCardSql:u,setRunSql:m,switchCardType:N,setQueryConfig:y}=s.useEditorActions(),h=s.useEditorStore($=>$.currentAssitantScope)||[],b=s.useEditorStore($=>$.userInputForAI),S=s.useEditorStore($=>$.triggerAIRun),T=s.useEditorStore($=>$.card),P=s.useEditorStore($=>$.selectedDatabaseName),O=s.useEditorStore($=>$.selectedTableName),L=s.useEditorStore($=>$.selectedConnectionId),f=s.useEditorStore($=>$.selectedSchemaName),w=s.useDashboardStore($=>$.dashboard.aiScopeTables),{errorMessage:E,refetch:g,data:M}=s.useDashboardCardQuery(T),{setTriggerAIRun:j,setCurrentAssitantScope:k,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:B,connectionType:C,selectedDatamodelId:A}=s.useEditorAside(),v=(he=s.useDashboardQuery().data)==null?void 0:he.assistantProfileId,{messages:R,setMessages:F,regenerate:z,error:G,sendMessage:V,status:U,addToolResult:W,stop:J,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${o.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:v,isDevMode:l,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(()=>{S&&b&&(V({role:"user",parts:[{type:"text",text:b}]}),j(!1))},[S,b,V,j]);async function q({toolCall:$}){var H,ae,ie,je,be,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)??((je=$.args)==null?void 0:je.python),pe=((be=$.input)==null?void 0:be.chartType)??((ve=$.args)==null?void 0:ve.chartType);N(pe),u(te),p(me),m(!0),W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if($.toolName==="getUserSql"){if(!d){W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"error",message:"No SQL found"}});return}W({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),N(te),D(me),u(void 0),p(void 0);const pe=await g();if((we=pe==null?void 0:pe.data)!=null&&we.error){W({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){W({tool:$.toolName,toolCallId:$.toolCallId,output:{status:"success",queryConfig:me,message:"The data has been visualized"}});return}W({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 Q($){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:P||"",schemaName:f||"",tableName:O||"",datamodelId:A||"",datamodelName:s.resolveDatamodelName(B),connectionId:L||"",connectionType:C||""},H=s.dedup([...h,$]);se(H)}function _(){const $={databaseName:P||"",schemaName:f||"",tableName:O||"",datamodelName:s.resolveDatamodelName(B),connectionId:L||"",connectionType:C||"",datamodelId:A||""};if(!s.isInAiScopeArray([...w||[],...h],$)||h.length===0){const ae=s.dedup([...w||[],...h,$]).filter(ie=>ie.connectionId===$.connectionId);se(ae)}}const Y=!["ready","error"].includes(U),le=s.getErrorMessage(G);return{messages:R,setMessages:F,sendMessage:V,regenerate:z,isLoading:Y,handleSetAIScope:_,handleAddCurrentTableToScope:ne,removeFromCurrentSelections:Q,currentAssitantScope:h,setCurrentAssitantScope:k,stop:J,status:U,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:le,clearError:Z}}const rr=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function qs({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=I.useRef(null),[i,c]=I.useState(!1),[o,d]=I.useState(s.isDevEnv),[l,x]=I.useState(!1),[p,u]=I.useState(!1),[m,N]=I.useState(!1),y=t??m,h=s.useCurrentAIContext(),{setCurrentAIContext:b}=s.useAIActions(),{clearQueue:S}=s.useQueueActions(),{clearFileAttachments:T}=s.useFileActions(),P=s.useFileAttachments("editor"),O=s.useDashboardStore(te=>te.dashboard.aiContext),L=s.useEditorStore(te=>te.card.dataSource),f=s.useEditorStore(te=>te.actions.setCardSql),w=s.useEditorStore(te=>te.actions.setRunSql),E=s.useEditorStore(te=>te.showAIDialog),g=s.useDashboardStore(te=>te.handleOpenAssistantProfile),{setShowAIDialog:M,setCardPython:j}=s.useEditorActions(),{setDataSource:k}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:B,setMessages:C,sendMessage:A,isLoading:v,stop:R,status:F,llmUsage:z,errorMessage:G,clearError:V}=nr(),[U,W]=I.useState(""),J=te=>{W(te.target.value)},Z=te=>{te.preventDefault();const me=U.trim();if(!me&&P.length===0)return;const pe=[];me&&pe.push({type:"text",text:me}),P.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}),W(""),T("editor"),H({force:!0})},{visibleMessages:q,hasMoreMessages:Q,totalMessageCount:se,loadMoreMessages:ne,resetMessageWindow:_}=s.useMessageWindow(B,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Y,isAtBottom:le,hasNewMessages:he,newMessageCount:$,scrollToBottom:H,handleScroll:ae,resetNewMessageCount:ie}=s.useAutoScroll(q,{threshold:50,behavior:"smooth",isStreaming:v});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:v,sendMessage:A});const{hasActiveTools:je}=s.useActiveToolStatus(B),be=I.useCallback(te=>{n==null||n(te),t===void 0&&N(te)},[t,n]);I.useEffect(()=>{if(!y)return;function te(me){me.key==="Escape"&&be(!1)}return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[y,be]);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(B??[],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")}},[B]),Ie=I.useCallback(()=>{be(!y)},[y,be]);function X(te,me){me==="sql"?(f(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:o,onCheckedChange:d,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:l,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&&(B==null?void 0:B.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(),g&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:g,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[we(),o&&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:()=>{C([]),S("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:Y,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:[Q&&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:o,handleRun:X,showSystemMessage:l,onQuickReply:ve,disableQuickReplies:v}),!je&&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:rr}),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:W,stop:R,input:U,handleInputChange:J,handleSubmit:te=>{oe(),Z(te),H({force:!0})},isLoading:v,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:u,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 lr(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(o=>{if(!(s.getDataType(o.dataType||"")==="date"))return!1;const l=s.getSelectedDateFilterColumn(o,a),x=l.split("."),p=x[x.length-1]||l,u=x.length>1?x.slice(0,-1).join("."):void 0,m=o.qualifiedTableName||u,N=m?`${m}.${p}`:void 0;return r?N?N===c||N.endsWith(`.${r}`):p===n.name:N?N===c:p===n.name})}const is=({dataType:t})=>s.getFieldIconComponent(t);function or({aliasTemplate:t,onAliasTemplateChange:n}){var l;const[a,r]=I.useState(t),[i,c]=I.useState(!1),o=(l=s.useEditorStore(x=>{var p;return(p=x.card.config)==null?void 0:p.pivotByColumns}))==null?void 0:l[0],d=o?`e.g. Min Sales in {{${o.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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 ir({valueAliases:t,onValueAliasesChange:n}){const[a,r]=I.useState(null),[i,c]=I.useState(""),[o,d]=I.useState(""),l=()=>{n({...t,"":""})},x=u=>{const m={...t};delete m[u],n(m)},p=u=>{const m={...t};delete m[u],m[i]=o,n(m),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(([u,m],N)=>e.jsx("div",{className:"flex items-center gap-2",children:a===u?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(u):y.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:o,onChange:y=>d(y.target.value),className:"h-8 w-24 text-xs",onPointerDown:y=>y.stopPropagation(),onKeyDown:y=>{y.key==="Enter"?p(u):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(u),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:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),c(u),d(m)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:m,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),c(u),d(m)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(u),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},u+N)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function cr({idx:t}){var d;const n=s.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),a=s.useEditorStore(l=>{var x;return(x=l.card.preferences)==null?void 0:x.datasetOptions}),r=s.useEditorStore(l=>l.actions.setCardPreferences),i=(d=n==null?void 0:n.chartOptions)==null?void 0:d.indexAxis,c=a==null?void 0:a.find(l=>l.idx===t);function o(l,x){(l==="end"||l==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const p={display:l!=="none",align:l,anchor:l,clamp:!0};if(!c)r({...n,datasetOptions:[...a||[],{idx:x,datalabels:p}]});else{const u={...c};u.datalabels=p;const m=a==null?void 0:a.map(N=>N.idx===x?u:N);r({...n,datasetOptions:m})}}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:()=>o("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>o("start",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"})})}),e.jsx("button",{onClick:()=>o("center",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:()=>o("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Kt,{className:s.cn("h-4 w-4",{"rotate-90":i==="y"})})})]})})]})}function cs({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 dr(t,n=30){return t.length>n?t.slice(0,n)+"...":t}function ur({col:t,idx:n,className:a,iconClassName:r,children:i}){const c=s.useEditorStore(p=>{var u;return(u=p.card)==null?void 0:u.preferences}),o=s.useEditorStore(p=>{var u,m;return(m=(u=p.card)==null?void 0:u.preferences)==null?void 0:m.datasetOptions}),d=o==null?void 0:o.find(p=>p.idx===n),{setCardPreferences:l}=s.useEditorStore(p=>p.actions);function x(p){if(!d)l({...c,datasetOptions:[...o||[],{idx:n,type:p==="area"?"line":p,fill:p==="area"?"origin":""}]});else{const u={...d};u.type=p==="area"?"line":p,u.fill=p==="area"?"origin":"";const m=o==null?void 0:o.map(N=>N.idx===n?u:N);l({...c,datasetOptions:m})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",a),children:[i||e.jsx(cs,{className:"max-w-[100px]",title:t,children:dr(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(cr,{idx:n})]})]})}function mr(){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 l={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,...l}}};r(x)}function c(){var d,l,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=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.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 o(){var d,l,x;return e.jsx("div",{children:e.jsxs(s.Select,{value:((x=(l=(d=a==null?void 0:a.chartOptions)==null?void 0:d.plugins)==null?void 0:l.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():o()})}function xr({column:t}){const n=s.useEditorStore(l=>l.card.type),a=s.useEditorStore(l=>{var x,p;return(p=(x=l.card)==null?void 0:x.config)==null?void 0:p.metricColumns}),r=(a==null?void 0:a.map(l=>l.label))||[],i=r==null?void 0:r.find(l=>l===t.label||l===t.name),c=i?r.indexOf(i):-1;function o(){return e.jsx("div",{className:"pr-1",children:i&&e.jsx(ur,{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(mr,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&o(),["pie","doughnut"].includes(n)&&d()]})}function hr({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:i}=s.useSemaphorContext(),c=s.useEditorStore(x=>x.card),o=c==null?void 0:c.dataSource,d=["attribute-values",t.entityName,t.name,n,a],l=s.useQuery({queryKey:d,queryFn:async()=>{if(!(o!=null&&o.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:o.connectionId,cardConfig:x,cardDataSource:o,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",p);const u=await s.postRequestRegular(`${i.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",p);if(u!=null&&u.error)return console.error("Error fetching attribute values:",u.error),[];const m=t.name;return((u==null?void 0:u.records)||[]).map(y=>{const h=y[m]||y[t.alias||m]||y[t.label];return{id:h||"",value:h||"",label:String(h||"(empty)")}})}catch(x){return console.error("Error fetching attribute values:",x),[]}},enabled:!!t&&!!(o!=null&&o.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:l.data||[],isLoading:l.isLoading,isFetching:l.isFetching,isError:l.isError,error:l.error,refetch:l.refetch}}function dt({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:i,onSave:c}){var P,O;const o=!!i,[d,l]=I.useState(o?"values":"fields"),[x,p]=I.useState(""),[u,m]=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]:[]}),N=a.filter(L=>{var w;return o?!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=>{m({...u,field:L}),l("values")},h=()=>{if(u.field&&u.selectedValues.length>0){const L={id:u.id,field:u.field,operator:"in",value:u.selectedValues};let f;if(o){const w=((r==null?void 0:r.conditions)||[]).map(E=>E.id===i.id?L:E);f={...r,conditions:w}}else{const w=(r==null?void 0:r.conditions)||[];f={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...w,L],groups:[]}}c(f),n(!1)}},b=()=>{if(!o||!i)return;const L=((r==null?void 0:r.conditions)||[]).filter(f=>f.id!==i.id);if(L.length>0){const f={...r,conditions:L};c(f)}else c(void 0);n(!1)},S=L=>{m({...u,selectedValues:L})},T=()=>{o&&i?(m({id:i.id,field:i.field,selectedValues:Array.isArray(i.value)?i.value:[i.value]}),l("values")):(m({id:s.v4(),field:null,selectedValues:[]}),l("fields")),p("")};return I.useEffect(()=>{t&&T()},[t,o,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:o?`Edit Filter: ${(P=u.field)==null?void 0:P.label}`:d==="fields"?"Select Field to Filter":`Select Values for ${(O=u.field)==null?void 0:O.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!o&&(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"&&!o?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:N.map(L=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>y(L),children:[e.jsx(is,{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))}),N.length===0&&x&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',x,'"']}),N.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(pr,{field:u.field,selectedValues:u.selectedValues,onValuesChange:S,onBack:o?void 0:()=>l("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:o?e.jsx(s.Button,{variant:"destructive",onClick:b,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:T,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:!u.field||u.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function pr({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[i,c]=I.useState(""),{values:o,isLoading:d,isFetching:l}=hr({field:t,searchQuery:i,limit:500}),x=i?o.filter(m=>String(m.value).toLowerCase().includes(i.toLowerCase())):o,p=m=>{const N=n.includes(m);a(N?n.filter(y=>y!==m):[...n,m])},u=()=>{n.length===x.length&&x.length>0?a([]):a(x.map(m=>m.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:m=>c(m.target.value),className:"pl-10"})]}),d||l?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:u}),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(m=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>p(m.value),children:[e.jsx(s.Checkbox,{checked:n.includes(m.value),onCheckedChange:()=>p(m.value)}),e.jsx(cs,{className:"text-sm",children:m.label})]},m.id))})]})]})}function gr({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:i,hasPivotColumns:c=!1,cardType:o}){var ys,vs,Ns,Cs,Ss,ws,Ts;const{attributes:d,listeners:l,setNodeRef:x,transform:p,transition:u,isDragging:m}=s.useSortable({id:t.id}),N=s.useEditorStore(K=>K.card),y=s.useEditorStore(K=>K.frame),{scopedFields:h}=s.useScopedFields(),{userContext:b}=s.useCurrentUserInfo(),S=(b==null?void 0:b.type)==="organization",T=(ys=N.dataSource)==null?void 0:ys.semanticDomainId,{promoteMetric:P}=s.usePromoteCalculatedMetricToDomain({domainId:T}),{updateLabel:O,handleAggregationChange:L,handleDateFormatChange:f,handleGranularityChange:w,handleAliasTemplateChange:E,handleValueAliasesChange:g,removeField:M,handleMetricComparisonChange:j,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:B,handleMetricTargetValueChange:C}=s.useFieldManagement(N),[A,v]=I.useState(!1),[R,F]=I.useState(!1),[z,G]=I.useState(!1),[V,U]=I.useState(null),[W,J]=I.useState(t.dateFormat||"YYYY-MM-DD"),[Z,q]=I.useState(t.customFormat||""),[Q,se]=I.useState(!!t.customFormat),[ne,_]=I.useState(t.granularity||"day"),[Y,le]=I.useState(t.aliasTemplate||""),[he,$]=I.useState(t.valueAliases||{}),[H,ae]=I.useState((vs=t.parameters)==null?void 0:vs.filters),ie=K=>{K==="custom"?se(!0):(se(!1),J(K),(n==="groupBy"||_e)&&f(a,K,"",n))},je=K=>{q(K),(n==="groupBy"||_e)&&f(a,"custom",K,n)},be=K=>{var re;_(K);const ee=(re=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:re.value;ee&&!Q&&(J(ee),n==="groupBy"&&f(a,ee,"",n)),n==="groupBy"&&w(a,K)},ve=K=>{le(K),n==="metrics"&&E(a,K)},Ne=K=>{$(K),n==="metrics"&&g(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)?(Ns=y==null?void 0:y.calculatedFields)==null?void 0:Ns.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=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.id,{metricColumns:re})}F(!1)},me=async K=>{await P(K),kt()},pe=()=>{M(n,a)},Fe={transform:s.CSS.Transform.toString(p),transition:u},us=s.getDataType(t.dataType),Ue=us==="date",ms=o==="kpi",_e=n==="detailColumns",xs=((Cs=N.config)==null?void 0:Cs.metricColumns)||[],Ve=((Ss=N.config)==null?void 0:Ss.groupByColumns)||[],hs=s.useDashboardStore(K=>{var ce;return(ce=K.dashboard)==null?void 0:ce.filters})??[],ps=s.useDashboardStore(K=>K.filterValues),mt=s.getDateFormatOptionsForGranularity(ne),xt=!!o&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(o),ht=o==="kpi"||o==="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=N.config)==null?void 0:re.filters;if(!K)return!1;const ce=de=>{const ge=de.field;return ge?ke.id&&ge.id===ke.id||ke.qualifiedFieldName&&ge.qualifiedFieldName===ke.qualifiedFieldName?!0:ge.name===ke.name:!1},ee=de=>de.conditions.some(ye=>s.getDataType(ye.field.dataType||"")==="date"&&ce(ye))?!0:de.groups.some(ye=>ee(ye));return ee(K)},[(ws=N.config)==null?void 0:ws.filters,ke]),gt=I.useMemo(()=>lr(hs,ke,ps),[hs,ps,ke]),fs=pt||gt,ft=I.useMemo(()=>xs.some(K=>K.comparisonType==="start_vs_end"),[xs]),jt=n!=="pivotBy",bt=Ue&&n==="groupBy"&&(!ms||ft),yt=!ms&&Ue&&(n==="groupBy"||_e),vt=o==="kpi"&&Ue&&n==="groupBy",Nt=n==="metrics",js=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,bs=()=>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:be,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:[bs(),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:Q?"custom":W,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))})]}),Q&&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(),je(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=N.config)==null?void 0:ce.showTrendline)||!1,onCheckedChange:k})]})}),((ee=N.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=N.config)==null?void 0:re.trendlineWindow)||30,onChange:ge=>{const ye=parseInt(ge.target.value)||30;D(ye)},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=N.config)==null?void 0:de.trendlineGranularity)||"day",onValueChange:B,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&&S&&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"})]})]})]})]}),js&&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||!fs,re=gs?fs?void 0:"Add a date filter to enable":"Add a date groupBy to enable",de=(ge,ye)=>e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.SelectItem,{value:ge,disabled:ee,title:re,children:ye})}),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"})]})]})]}),js&&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===""){C(a,void 0);return}const de=Number(re);C(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 ge;re.stopPropagation();const de=H.conditions.filter(ye=>ye.id!==ee.id);if(de.length>0){const ye={...H,conditions:de};te(ye)}else if(ae(void 0),n==="metrics"){const ye={...t,parameters:{...t.parameters,filters:void 0}},Ae=[...((ge=N.config)==null?void 0:ge.metricColumns)||[]];Ae[a]=ye,s.useEditorStore.getState().actions.updateCardConfig(N.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(xr,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(or,{aliasTemplate:Y,onAliasTemplateChange:ve}),e.jsx(ir,{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,...l,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 ${m?"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(is,{dataType:us}),e.jsx(cs,{className:s.cn("w-[140px] flex-1 text-sm",At&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Ts=H==null?void 0:H.conditions)==null?void 0:Ts.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(),v(!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(),o==="kpi"&&bs(),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=N.config)==null?void 0:ce.metricColumns)||[]];re[a]=ee,s.useEditorStore.getState().actions.updateCardConfig(N.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=N.config)==null?void 0:Ae.metricColumns)||[]];ce[a]=K;const{frame:ee,actions:re}=s.useEditorStore.getState();if(re.updateCardConfig(N.id,{metricColumns:ce}),!s.isCalculatedMetric(K))return;const de=ee.calculatedFields||[],ge=de.findIndex(Ee=>Ee.name===t.name&&Ee.role===t.role);if(ge<0)return;const ye=de.map((Ee,ze)=>ze===ge?{...K,id:Ee.id}:Ee);re.updateFrame({calculatedFields:ye})},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)),ge=de>=0&&re[de].id!==K.id?{...K,id:re[de].id}:K,ye=de>=0?re.map((He,Dt)=>Dt===de?ge:He):[...re,ge];ee.updateFrame({calculatedFields:ye});const Ae=[...((ze=N.config)==null?void 0:ze.metricColumns)||[]],Ee=t;Ae[a]={...ge,id:Ee.id,aliasTemplate:Ee.aliasTemplate,valueAliases:Ee.valueAliases,parameters:Ee.parameters,customFormat:Ee.customFormat},ee.updateCardConfig(N.id,{metricColumns:Ae})},onPromoteMetricToDomain:T&&S?me:void 0,domainId:T,cardId:N.id})]})}function fr({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 Be({zone:t,fields:n,label:a,placeholder:r,shouldShow:i,hasPivotColumns:c=!1,activeField:o=null}){const{isOver:d,setNodeRef:l}=s.useDroppable({id:t}),{updateSortByColumn:x}=s.useEditorActions(),p=s.useEditorStore(b=>b.card),u=s.useEditorStore(b=>b.card.type),m=n.length>0,N=I.useMemo(()=>!o||!d?!0:s.validateFieldForChartType(o,t,u).isValid,[o,d,t,u]),y=(b,S)=>{var P;!((P=p.config)!=null&&P.sortByColumns)||p.config.sortByColumns.findIndex(O=>O.id===b)===-1||x(p.id,b,{direction:S})};if(t==="sortBy"&&i===!1)return null;const h=t!=="sortBy"&&u!=="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(fr,{concept:t})]}),e.jsx("div",{ref:l,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&&N,"border-red-500 bg-red-50 dark:bg-red-950":d&&!N,"border-muted-foreground/30 bg-muted/40":!d&&m,"min-h-[60px] border-muted-foreground/20 bg-background":!d&&!m}),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,S)=>{const P=b.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(gr,{field:b,zone:t,index:S,sortDirection:P,onSortDirectionChange:O=>y(b.id,O),hasPivotColumns:c,cardType:u})})},b.id)})})})})]})}function jr({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,detailFields:i,activeField:c}){var W,J,Z,q;const[o,d]=I.useState(!1),l=s.useEditorStore(Q=>{var se;return!!((se=Q.card.customCardPreferences)!=null&&se.url)}),x=s.useEditorStore(Q=>Q.card),p=s.useEditorStore(Q=>Q.frame),u=s.findCustomVisualConfigCard(p,x),{manifest:m}=s.useCustomVisual(((W=u==null?void 0:u.customCardPreferences)==null?void 0:W.url)||""),N=(J=m==null?void 0:m.visuals)==null?void 0:J.find(Q=>{var se;return Q.name===((se=u==null?void 0:u.customCardPreferences)==null?void 0:se.componentName)}),y=s.resolveMultiInputType(u,N)==="multiple",h=y&&!!((Z=u==null?void 0:u.customCardPreferences)!=null&&Z.url),b=s.getConfigSlotExpectedType(N==null?void 0:N.slots),S=s.useEditorStore(Q=>Q.actions.updateCardConfig),T=s.useEditorStore(Q=>Q.actions.updateFrame),{scopedFields:P,refetch:O}=s.useScopedFields(),{userContext:L}=s.useCurrentUserInfo(),f=y&&(u==null?void 0:u.id)===x.id&&b?b:x==null?void 0:x.type,w=f==="detailTable",E=t.length>0||a.length>0||i.length>0,g=!w&&(f!=="kpi"||a.length<=2),M=!w,j=!w&&f!=="kpi",k=f!=="kpi"&&E,D=w,B=w?"Drop fields from Columns":"Drop fields from Rows or Metrics",C=(q=x.dataSource)==null?void 0:q.semanticDomainId,{promoteMetric:A}=s.usePromoteCalculatedMetricToDomain({domainId:C}),v=(L==null?void 0:L.type)==="organization",R=Q=>{const se=p.calculatedFields||[],ne=se.findIndex(H=>H.name===Q.name&&H.role===Q.role),_=ne>=0?{...Q,id:se[ne].id}:Q,Y=ne>=0?se.map((H,ae)=>ae===ne?_:H):[...se,_];T({calculatedFields:Y});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];S(x.id,{metricColumns:$})},F=async Q=>{await A(Q),O()},z=["pie","doughnut","polar","funnel","aggregateTable","bubble","scatter"].includes(f),G=j&&!z,V=()=>f==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},U=()=>f==="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:[g&&e.jsx(Be,{zone:"groupBy",fields:t,label:V().label,placeholder:V().placeholder,activeField:c}),G&&e.jsx(Be,{zone:"pivotBy",fields:n,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:c}),M&&e.jsx(Be,{zone:"metrics",fields:a,label:U().label,placeholder:U().placeholder,hasPivotColumns:n.length>0,activeField:c}),D&&e.jsx(Be,{zone:"detailColumns",fields:i,label:"Columns",placeholder:"Drag columns to display"}),a.length>=1&&v&&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(Be,{zone:"sortBy",fields:r,label:"Sort By",placeholder:B,activeField:c})]})]}),(!l||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"})})})]}),(l||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(Us,{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(rt,{})})]})]}),e.jsx(s.CalculatedFieldEditor,{open:o,onOpenChange:d,availableFields:P,initialFieldType:"metric",allowedFieldTypes:["metric"],onSave:Q=>{Q.role==="metric"&&S(x.id,{metricColumns:[...a,Q]})},onSaveToDashboard:Q=>{Q.role==="metric"&&R(Q)},onPromoteMetricToDomain:C&&v?F:void 0,domainId:C,cardId:x.id})]})}function br({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(l=>{var m,N,y,h;const x=`${(m=l.source)==null?void 0:m.entityName}.${(N=l.source)==null?void 0:N.name}`,p=`${(y=l.target)==null?void 0:y.entityName}.${(h=l.target)==null?void 0:h.name}`,u=l.operator||"=";return`${x} ${u} ${p}`}).join(" AND "),o=d=>!d.joinKeyGroups||d.joinKeyGroups.length===0?"No conditions defined":d.joinKeyGroups.length===1?c(d.joinKeyGroups[0].keys):d.joinKeyGroups.map((l,x)=>({id:x,operator:l.operator,condition:c(l.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(Zt,{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,l)=>{const x=o(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(u=>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:u.condition}),u.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",u.operator,")"]})]},u.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||l)})})})]})})]}),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 Ks={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 yr({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d}){var E,g;const[l,x]=I.useState(()=>Ks.getItem("chart-selector-expanded")==="true"),[p,u]=I.useState(!1),m=s.useEditorStore(M=>M.card),N=s.useEditorStore(M=>M.actions.updateCardConfig),y=a.length>0||r.length>0||i.length>0||o.length>0,{data:h,autoJoinMetadata:b}=s.useDashboardCardQuery(m),S=((E=m==null?void 0:m.config)==null?void 0:E.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),T=((g=m==null?void 0:m.dataSource)==null?void 0:g.selectedEntities)||[],P=M=>{N(m.id,{...m==null?void 0:m.config,joinPlan:M}),u(!1)},O=()=>{N(m.id,{...m==null?void 0:m.config,joinPlan:void 0}),u(!1)},L=()=>{u(!1)},f=()=>{u(!0)};I.useEffect(()=>{Ks.setItem("chart-selector-expanded",String(l))},[l]);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":l}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",l?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:l&&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:l,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(fe.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(br,{onEditJoins:f}),e.jsx(jr,{groupByFields:a,pivotByFields:r,metricsFields:i,sortByFields:c,detailFields:o,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Ws,{open:p,onOpenChange:u,joinPlan:S,availableDataSources:T,onSave:P,onCancel:L,onRemove:O,children:e.jsx("div",{})})]})}function vr({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||[],l={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=L=>{const f=w=>{if(w.id===L){const E=d[0]||l,g=s.getDataType(E.dataType)==="date";return{...w,conditions:[...w.conditions,{id:`condition-${Date.now()}`,field:E,operator:g?"between":"=",value:g?[]:""}]}}return{...w,groups:w.groups.map(f)}};r(f(a))},p=L=>{const f=w=>{if(w.id===L){const E=d[0]||l,g=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:g?"between":"=",value:g?[]:""}],groups:[]}]}}return{...w,groups:w.groups.map(f)}};r(f(a))},u=(L,f)=>{const w=E=>E.id===L?{...E,conditions:E.conditions.filter(g=>g.id!==f)}:{...E,groups:E.groups.map(w)};r(w(a))},m=(L,f)=>{const w=E=>E.id===L?{...E,groups:E.groups.filter(g=>g.id!==f)}:{...E,groups:E.groups.map(w)};r(w(a))},N=(L,f,w,E)=>{if(w==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const g=M=>M.id===L?{...M,conditions:M.conditions.map(j=>j.id===f?{...j,[w]:E}:j)}:{...M,groups:M.groups.map(g)};r(g(a))},y=(L,f,w)=>{const E=g=>g.id===L?{...g,conditions:g.conditions.map(M=>M.id===f?{...M,...w}:M)}:{...g,groups:g.groups.map(E)};r(E(a))},h=(L,f)=>{const w=E=>E.id===L?{...E,logicalOperator:f}:{...E,groups:E.groups.map(w)};r(w(a))},b=(L,f)=>{const w=E=>E.id===L?{...E,negate:f}:{...E,groups:E.groups.map(w)};r(w(a))},S=(L,f,w)=>{const E=g=>g.id===L?{...g,conditions:s.arrayMove(g.conditions,f,w)}:{...g,groups:g.groups.map(E)};r(E(a))},T=(L,f,w)=>{const E=g=>g.id===L?{...g,groups:s.arrayMove(g.groups,f,w)}:{...g,groups:g.groups.map(E)};r(E(a))},P=L=>{if(!L||L.conditions.length===0&&L.groups.length===0)return"-- No filters defined";const f=E=>{let g="";typeof E.field=="object"?g=E.field.entityName?`${E.field.entityName}.${E.field.name}`:E.field.name:g=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`${g} 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`${g} ${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 B=D.trim();return E.field.dataType==="string"?`'${B}'`:B}):typeof j=="number"&&(k=[String(j)]),j=`(${k.join(", ")})`}switch(M){case"contains":return typeof j=="string"?`${g} LIKE '%${j.replace(/'/g,"")}'`:`${g} LIKE '%${String(j)}'`;case"startsWith":return typeof j=="string"?`${g} LIKE '${j.replace(/'/g,"")}%'`:`${g} LIKE '${String(j)}%'`;case"endsWith":return typeof j=="string"?`${g} LIKE '%${j.replace(/'/g,"")}'`:`${g} LIKE '%${String(j)}'`;case"isNull":return`${g} IS NULL`;case"isNotNull":return`${g} IS NOT NULL`;default:return`${g} ${M} ${j}`}},w=E=>{const g=E.conditions.map(f),M=E.groups.map(B=>w(B)),j=[...g,...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:u,removeGroup:m,updateCondition:N,updateConditionFields:y,updateGroupOperator:h,updateGroupNegate:b,reorderConditions:S,reorderGroups:T,generateSQLPreview:P,hasAnyFilters:O}}function Nr({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 Cr=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function Sr({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:i="w-64"}){const[c,o]=I.useState(!1),d=I.useMemo(()=>{const l={};return a.forEach(x=>{const p=Cr(x);l[p]||(l[p]={}),l[p][x.entityId]||(l[p][x.entityId]=[]),l[p][x.entityId].push(x)}),l},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:o,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(Nr,{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(([l,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"}),l]}),children:Object.entries(x).map(([p,u])=>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(u[0].entityType,{size:"h-3 w-3"}),e.jsx("span",{children:u[0].entityName})]}),u.map((m,N)=>e.jsxs(s.CommandItem,{value:m.id,onSelect:()=>{n(m),o(!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)===m.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:m.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:m.description&&e.jsx("span",{children:m.description})})]})]},m.id+N))]},`${l}-${p}`))},l))})]})})]})}function ds(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,o={...t,alias:t.name,label:"value",role:"groupby"},d={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},l={...o,role:"sortby",direction:"asc"},x={joinPlan:c,groupByColumns:[o],metricColumns:[d],sortByColumns:[l]},p=((h=n.dataSource)==null?void 0:h.connectionId)||n.connectionId,{data:u,isPending:m,error:N}=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:((u==null?void 0:u.records)||[]).map(b=>({label:b.value||"BLANK",value:b.value||"BLANK",count:(b==null?void 0:b.count)||0})),isPending:m,error:N}}function wr({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:i}){const[c,o]=as.useState(!1),{filterValues:d}=ds(t),l=p=>{a(n.filter(u=>u!==p))},x=p=>{n.includes(p)?a(n.filter(u=>u!==p)):a([...n,p])};return e.jsx("div",{className:s.cn("w-full",i),children:e.jsxs(s.Popover,{open:c,onOpenChange:o,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 u=d.find(m=>m.value===p);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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:m=>{m.key==="Enter"&&l(p)},onMouseDown:m=>{m.preventDefault(),m.stopPropagation()},onClick:m=>{m.stopPropagation(),l(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,u)=>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+u))})]})]})})]})})}function Tr({field:t,value:n,onChange:a,placeholder:r="Select value...",className:i}){const{filterValues:c,isPending:o,error:d}=ds(t);return o?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((l,x)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+x))})]})}function Er({value:t,operator:n,onChange:a,className:r}){var l,x,p;const{tokenProps:i}=s.useSemaphorContext(),c=((x=(l=i==null?void 0:i.params)==null?void 0:l.calendarContext)==null?void 0:x.tz)||((p=i==null?void 0:i.params)==null?void 0:p.timezone),o=I.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const u=t[0]?new Date(t[0]):void 0,m=t[1]?new Date(t[1]):void 0;if(u&&m)return{from:u,to:m}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const u=new Date(t[0]),m=t.length>1?new Date(t[t.length-1]):u;if(!isNaN(u.getTime()))return{from:u,to:m}}}},[t,n]),d=u=>{if(!u){a(void 0);return}if(u.from&&u.to)a([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),a([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),a([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:o,onChange:d,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Ir=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Ar=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Dr=["=","!=","isNull","isNotNull"],Lr=["between","isNull","isNotNull"],Mr={"=":"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 Gs(t){return Mr[t]||s.titleCase(t)}function Or(t){switch(t){case"string":return kr;case"number":return Ar;case"boolean":return Dr;case"date":return Lr;default:return Ir}}function ut({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:i,onRemoveCondition:c,onUpdateGroupOperator:o,availableFields:d,updateConditionFields:l}){const{attributes:x,listeners:p,setNodeRef:u,transform:m,transition:N,isDragging:y}=s.useSortable({id:t.id}),{isPending:h,error:b}=ds(t.field),S={transform:s.CSS.Transform.toString(m),transition:N};return e.jsxs("div",{ref:u,style:S,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:T=>o(a,T),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(Sr,{value:t.field,onValueChange:T=>{const P=T,O=s.getDataType(P.dataType)==="date";l(a,t.id,{field:P,value:"",operator:O?"between":"="})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:T=>{T==="in"||T==="not in"?l(a,t.id,{operator:T,value:[]}):T==="isNull"||T==="isNotNull"?l(a,t.id,{operator:T,value:null}):l(a,t.id,{operator:T,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?Gs(t.operator):""})}),e.jsx(s.SelectContent,{children:Or(s.getDataType(t.field.dataType)).map(T=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:T,children:Gs(T)},T))})]}),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(wr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(T=>typeof T=="string")?t.value:[],onChange:T=>l(a,t.id,{value:T}),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:T=>l(a,t.id,{value:T.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Tr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:T=>l(a,t.id,{value:T}),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:T=>l(a,t.id,{value:T==="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(Er,{value:t.value,operator:t.operator,onChange:T=>l(a,t.id,{value:T}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:T=>i(a,t.id,"value",T.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 Fr({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:i,onRemoveGroup:c,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onReorderConditions:x,onReorderGroups:p,onAddCondition:u,onAddGroup:m,availableFields:N,renderFilterGroup:y,updateConditionFields:h}){const{attributes:b,listeners:S,setNodeRef:T,transform:P,transition:O,isDragging:L}=s.useSortable({id:t.id}),f={transform:s.CSS.Transform.toString(P),transition:O},w=g=>{const{active:M,over:j}=g;if(j&&M.id!==j.id){const k=t.conditions.findIndex(B=>B.id===M.id),D=t.conditions.findIndex(B=>B.id===j.id);k!==-1&&D!==-1&&x(t.id,k,D)}},E=g=>{const{active:M,over:j}=g;if(j&&M.id!==j.id&&a){const k=t.groups.findIndex(B=>B.id===M.id),D=t.groups.findIndex(B=>B.id===j.id);k!==-1&&D!==-1&&p(a,k,D)}};return e.jsxs("div",{ref:T,style:f,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,...S,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:g=>r(t.id,g),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(g=>g.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((g,M)=>e.jsx(ut,{condition:g,index:M,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:o,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:N,updateConditionFields:h},g.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(g=>g.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(g=>y(g,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:()=>u(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:()=>m(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Rr({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:i}){const{currentFilters:c,availableFields:o,isLoading:d,addCondition:l,addGroup:x,removeCondition:p,removeGroup:u,updateCondition:m,updateConditionFields:N,updateGroupOperator:y,updateGroupNegate:h,reorderConditions:b,reorderGroups:S,generateSQLPreview:T,hasAnyFilters:P,setCurrentFilters:O}=vr({initialFilters:t,availableFields:n}),L=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[f,w]=I.useState(!1),E=(j,k,D)=>{const B=C=>C.id===j?{...C,conditions:C.conditions.map(A=>A.id===k?{...A,field:D,dataType:D.dataType}:A)}:{...C,groups:C.groups.map(B)};O(B(c))},g=(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:B=>{const{active:C,over:A}=B;if(A&&C.id!==A.id){const v=j.conditions.findIndex(F=>F.id===C.id),R=j.conditions.findIndex(F=>F.id===A.id);v!==-1&&R!==-1&&b(j.id,v,R)}},children:e.jsx(s.SortableContext,{items:j.conditions.map(B=>B.id),strategy:s.verticalListSortingStrategy,children:j.conditions.map((B,C)=>e.jsx(ut,{condition:B,index:C,groupId:j.id,groupLogicalOperator:j.logicalOperator,onUpdateCondition:m,onUpdateField:E,onRemoveCondition:p,onUpdateGroupOperator:y,availableFields:o,updateConditionFields:N},B.id))})}),e.jsx(s.DndContext,{sensors:L,collisionDetection:s.closestCenter,onDragEnd:B=>{const{active:C,over:A}=B;if(A&&C.id!==A.id){const v=j.groups.findIndex(F=>F.id===C.id),R=j.groups.findIndex(F=>F.id===A.id);v!==-1&&R!==-1&&S(j.id,v,R)}},children:e.jsx(s.SortableContext,{items:j.groups.map(B=>B.id),strategy:s.verticalListSortingStrategy,children:j.groups.map(B=>g(B,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:()=>l(j.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),f&&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(Fr,{group:j,depth:k,parentGroupId:D,onUpdateGroupOperator:y,onUpdateGroupNegate:h,onRemoveGroup:u,onUpdateCondition:m,onUpdateField:E,onRemoveCondition:p,onReorderConditions:b,onReorderGroups:S,onAddCondition:l,onAddGroup:x,availableFields:o,renderFilterGroup:g,updateConditionFields:N},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..."})]}):g(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:f,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)"})]})}),P&&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:T(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(P?c:null),children:"Apply Filters"})]})]})}function Pr({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:i,isOpen:c,onOpenChange:o}){const d=x=>{a(t,x),o(!1)},l=()=>{r(t),o(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:o,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(Rr,{filters:n,availableFields:i,onSave:d,onCancel:()=>o(!1),onClearAll:l})]})]})}function Br({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var S,T;const[i,c]=I.useState(null),o=s.useEditorStore(P=>P.card),d=s.useEditorStore(P=>P.actions.updateCardConfig),l=(S=o==null?void 0:o.config)==null?void 0:S.joinPlan,x=I.useCallback(P=>P.entityName===s.CALCULATED_FIELD_ENTITY_MARKER||P.entityName==="calculated_fields"||P.qualifiedEntityName==="calculated_fields",[]),p=(T=o==null?void 0:o.dataSource)==null?void 0:T.semanticDomainId,{data:u}=s.useJoinabilityMap(p),m=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy"),...a("detailColumns")],N=I.useCallback(P=>P.startsWith("card-source-")?"source":P.startsWith("card-")?null:P.startsWith("source-")||n.find(O=>O.id===P)?"source":a("groupBy").find(O=>O.id===P)?"groupBy":a("metrics").find(O=>O.id===P)?"metrics":a("pivotBy").find(O=>O.id===P)?"pivotBy":a("sortBy").find(O=>O.id===P)?"sortBy":a("detailColumns").find(O=>O.id===P)?"detailColumns":null,[n,a]),y=I.useCallback(P=>{c(P.active.id)},[]),h=I.useCallback(P=>{var M;const{active:O,over:L}=P;if(!L||!t){c(null);return}const f=O.id,w=L.id,E=N(f),g=N(w)||w;if(g==="sortBy"){if(E==="source"){const j=n.find(D=>D.id===f);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"&&g==="sortBy"){const j=[...n].find(C=>C.id===f);if(!j){c(null);return}const k=a("sortBy");if(s.fieldAlreadyExists(j,k)){c(null);return}const D=s.validateFieldForChartType(j,"sortBy",o.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const B=s.getNewField(j,"sortBy",k);c(null),r("sortBy",[...k,B]);return}if(E==="source"&&g!=="source"&&g!=="sortBy"){const j=[...n].find(R=>R.id===f);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&&(u!=null&&u.joinabilityMap)){if(s.calculateFieldState(j,{joinabilityMap:u.joinabilityMap,selectedFields:k,baseEntityName:(M=l==null?void 0:l.baseEntity)==null?void 0:M.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!l){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(R,j.qualifiedEntityName,l)){s.showJoinRequiredNotification(),c(null);return}}}const B=a(g);if(s.fieldAlreadyExists(j,B)){c(null);return}const C=s.validateFieldForChartType(j,g,o.type);if(!C.isValid){s.ue.error("Invalid Field Type",{description:C.reason,position:"top-center",duration:3e3}),c(null);return}const A=s.getNewField(j,g,B),v=[...B,A];c(null),r(g,v),g==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(o.type,o.config,d,t,v);return}if(E&&g&&E!=="source"&&g!=="source"&&E!==g){const j=a(E),k=a(g),D=j.find(R=>R.id===f);if(!D){c(null);return}const B=s.validateFieldForChartType(D,g,o.type);if(!B.isValid){s.ue.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3}),c(null);return}const C=s.getNewField(D,g,k);if(c(null),g==="sortBy"){s.fieldAlreadyExists(D,k)||r(g,[...k,C]);return}const A=j.filter(R=>R.id!==f),v=[...k,C];r(E,A),r(g,v),g==="metrics"&&t&&s.cleanupKpiMetricComparisonMode(o.type,o.config,d,t,v);return}if(E&&g&&E===g&&E!=="source"){const j=a(E),k=j.findIndex(B=>B.id===f),D=j.findIndex(B=>B.id===w);if(k!==D){const B=s.arrayMove(j,k,D);r(E,B)}}c(null)},[t,n,a,r,N,l,p,u,x,o.type,d,o.config]),b=i?m.find(P=>P.id===i):null;return{activeId:i,activeField:b,handleDragStart:y,handleDragEnd:h}}function Vr({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,o=()=>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"}),o()&&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 zr=[{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 $r(){var l,x;const t=s.useEditorStore(p=>p.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=I.useState(!1),[i,c]=I.useState(""),o=p=>{if(p==="custom"){r(!0);return}r(!1),n(t.id,parseInt(p))},d=p=>{const u=p.target.value;c(u),u&&!isNaN(parseInt(u))&&n(t.id,parseInt(u))};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=(l=t.config)==null?void 0:l.rowLimit)==null?void 0:x.toString())||"100",onValueChange:o,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:zr.map(p=>e.jsx(s.SelectItem,{value:p.value,children:p.label},p.value))})]})})}function qr({card:t,queryData:n,isLoading:a,isFetching:r,pagination:i,onPaginationChange:c,onSortChange:o,sortState:d,splitViewEnabled:l}){const x=I.useMemo(()=>(n==null?void 0:n.records)||[],[n==null?void 0:n.records]);return!l||["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:o,sortState:d})]})})]})}const Kr="semaphor-split-view-enabled";function Gr(){return Xs(Kr,!0)}function Ur({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:i,activeCard:c,columns:o,columnsLoading:d,columnsError:l}){var se,ne,_;const x=s.useEditorStore(Y=>Y.card),p=s.useDashboardStore(Y=>Y.filterValues),u=s.useDashboardStore(Y=>Y.selectedSheetId),m=s.useDashboardStore(Y=>Y.inlineFilterValuesMap[(c==null?void 0:c.id)||""]),{updateCardConfig:N,setCard:y,updateCardInFrame:h,setShowAIDialog:b}=s.useEditorActions(),S=s.useEditorStore(Y=>Y.showAIDialog),T=s.useDashboardStore(Y=>Y.isVisualEditing),[P,O]=I.useState(!1),[L,f]=I.useState(!1),[w,E]=I.useState(null),{config:g}=I.useContext(s.SemaphorContext).tokenProps,M=(g==null?void 0:g.showInfoTab)!==!1,[j,k]=Gr();s.useEditorStore(Y=>{var le;return!!((le=Y.card.customCardPreferences)!=null&&le.url)});const{data:D,errorMessage:B,isLoading:C,isFetching:A,errorSql:v,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 W=()=>{const Y=!j;Y&&t==="table"&&n("chart"),k(Y)},J=(Y,le)=>{const he={...c,paginationConfig:{page:Y+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 (",o.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:d?"Loading...":l?"Error loading columns":JSON.stringify(o.slice(0,5),null,2)})]})]})]})}const q=Y=>{if(!x.config)return;const le=s.sortStateToSortByColumns(Y,x.config.metricColumns,x.config.groupByColumns,x.config.detailColumns);N(x.id,{...x.config,sortByColumns:le})},Q=I.useMemo(()=>{var Y;return s.sortByColumnsToSortState((Y=x.config)==null?void 0:Y.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":S&&T}),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"&&S&&e.jsx("div",{className:"w-[260px]",children:e.jsx(os,{variant:"outline"})}),e.jsx(Vr,{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:m,sheetId:u||""}),z&&x.type!=="table"&&e.jsx(s.ComparisonMetadataBadge,{metadata:z,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx($r,{})}),S&&e.jsx(fe.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:C||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:W,children:j?e.jsx(Bt,{className:"size-4"}):e.jsx(Wt,{className:"size-4"})}),t==="chart"&&e.jsx(e.Fragment,{children:e.jsx(nt,{})}),!S&&e.jsx(s.IconButton,{onClick:()=>b(!S),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(qr,{card:c,queryData:D,isLoading:C,isFetching:A,pagination:R,onPaginationChange:J,onSortChange:q,sortState:Q,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:[(C||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:C||A,onSortChange:q,sortState:Q})]}),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:B?e.jsx(ls,{error:B,errorSql:v,onSendFeedback:()=>{const Y=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:x.config,dataSource:c.dataSource,dashboardFilters:p,errorMessage:B,errorSql:v,generatedSql:D==null?void 0:D.sql});E(Y),f(!0)},onOpenInEditor:()=>{b(!0),setTimeout(()=>{const Y=s.useEditorStore.getState().actions;Y.setIsDevMode(!0),Y.setCardSql(v||""),setTimeout(()=>{Y.setRunSql(!0)},100)},100)}}):(D==null?void 0:D.sql)&&e.jsx(st,{sql:D.sql,showCardDetails:!0})})})]}),w&&e.jsx(s.FeedbackDialog,{open:L,onOpenChange:f,feedbackData:w})]})]})}function _r({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(is,{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 Hr=()=>{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 Jr({column:t,isSelected:n,onSelect:a,availableFields:r,width:i,onWidthChange:c}){var F,z,G;const o=s.useEditorStore(V=>V.card),{updateCardConfig:d,removeGroupByColumn:l,removeMetricColumn:x,updateFilters:p}=s.useEditorActions(),[u,m]=I.useState(!1),[N,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)},W=()=>{y(!1),h.current=null,document.removeEventListener("mousemove",U),document.removeEventListener("mouseup",W)};document.addEventListener("mousemove",U),document.addEventListener("mouseup",W)},[i,t.id,c]),S=(F=o==null?void 0:o.config)==null?void 0:F.filters,T=(z=S==null?void 0:S.conditions)==null?void 0:z.some(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName),P=V=>{V?p(o.id,V):d(o.id,{filters:void 0})},{attributes:O,listeners:L,setNodeRef:f,transform:w,transition:E,isDragging:g}=s.useSortable({id:t.id}),M={transform:s.CSS.Transform.toString(w),transition:E},j=s.getDataType(t.dataType),k=Yr(j),D=()=>{var W;const V=((W=o==null?void 0:o.config)==null?void 0:W.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"asc"},d(o.id,{sortByColumns:J})}else d(o.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"asc"}]})},B=()=>{var W;const V=((W=o==null?void 0:o.config)==null?void 0:W.sortByColumns)||[],U=V.findIndex(J=>J.name===t.name);if(U!==-1){const J=[...V];J[U]={...J[U],direction:"desc"},d(o.id,{sortByColumns:J})}else d(o.id,{sortByColumns:[...V,{...t,id:`sort-${t.id}`,role:"sortby",direction:"desc"}]})},C=()=>{var W;const V=((W=o==null?void 0:o.config)==null?void 0:W.groupByColumns)||[];if(!V.some(J=>J.name===t.name)){const J={...t,id:`groupby-${t.id}-${Date.now()}`,role:"groupby"};d(o.id,{groupByColumns:[...V,J]})}},A=V=>{var J;const U=((J=o==null?void 0:o.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(o.id,{metricColumns:[...U,Z]})}},v=()=>{t.role==="groupby"?l(o.id,t.id):t.role==="metric"&&x(o.id,t.id)},R={...M,width:i?`${i}px`:void 0,minWidth:i?`${i}px`:"120px"};return e.jsxs("th",{ref:f,style:R,className:s.cn("group relative border-r border-border bg-background px-1 py-0",g&&"opacity-50",n&&"bg-primary/10",N&&"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,")"]}),T&&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:()=>m(!0),children:[e.jsx(s.Filter,{className:s.cn("mr-2 h-4 w-4",T&&"text-primary")}),T?"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:B,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:C,children:[e.jsx(rs,{className:"mr-2 h-4 w-4"}),"Group by this column"]}),e.jsxs(s.DropdownMenuItem,{disabled:!0,children:[e.jsx(_s,{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:v,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",N&&"bg-primary")}),e.jsx(dt,{open:u,onOpenChange:m,availableFields:r.length>0?r:[t],existingFilters:S,editingCondition:T?(G=S==null?void 0:S.conditions)==null?void 0:G.find(V=>V.field.name===t.name&&V.field.qualifiedEntityName===t.qualifiedEntityName):void 0,onSave:P})]})}function Yr(t){switch(t){case"number":return s.Hash;case"date":return s.Calendar;case"string":default:return s.Type}}function Qr({selectedColumn:t,onColumnSelect:n,isLoading:a=!1,sourceFields:r=[]}){var E,g,M,j;const i=s.useEditorStore(k=>k.card),{updateCardConfig:c}=s.useEditorActions(),[o,d]=I.useState(null),[l,x]=I.useState({}),[p,u]=I.useState(!1),m=I.useMemo(()=>{var B,C;const k=((B=i==null?void 0:i.config)==null?void 0:B.groupByColumns)||[],D=((C=i==null?void 0:i.config)==null?void 0:C.metricColumns)||[];return[...k,...D]},[(E=i==null?void 0:i.config)==null?void 0:E.groupByColumns,(g=i==null?void 0:i.config)==null?void 0:g.metricColumns]),N=I.useMemo(()=>{const k=new Set(m.map(D=>`${D.qualifiedEntityName}.${D.name}`));return r.filter(D=>!k.has(`${D.qualifiedEntityName}.${D.name}`))},[r,m]),{data:y,isLoading:h}=s.useDashboardCardQuery(i),b=(y==null?void 0:y.records)||[],S=I.useCallback((k,D)=>{x(B=>({...B,[k]:D}))},[]),T=I.useCallback(k=>{var A,v;const D=s.getDataType(k.dataType),B=((A=i==null?void 0:i.config)==null?void 0:A.groupByColumns)||[],C=((v=i==null?void 0:i.config)==null?void 0:v.metricColumns)||[];if(D==="number"){const R={...k,id:`metric-${k.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};c(i.id,{metricColumns:[...C,R]})}else{const R={...k,id:`groupby-${k.id}-${Date.now()}`,role:"groupby"};c(i.id,{groupByColumns:[...B,R]})}u(!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]),P=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),O=k=>{d(k.active.id)},L=k=>{const{active:D,over:B}=k;if(d(null),!B||D.id===B.id)return;const C=m.findIndex(v=>v.id===D.id),A=m.findIndex(v=>v.id===B.id);if(C!==-1&&A!==-1){const v=s.arrayMove(m,C,A),R=v.filter(z=>z.role==="groupby"),F=v.filter(z=>z.role==="metric");c(i.id,{groupByColumns:R,metricColumns:F})}},f=o?m.find(k=>k.id===o):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"})}):m.length===0?e.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-4 p-8 text-center",children:e.jsxs("div",{className:"rounded-lg border-2 border-dashed border-muted-foreground/25 p-12",children:[e.jsx("h3",{className:"text-lg font-medium text-muted-foreground",children:"No columns selected"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground/75",children:"Select columns from the panel on the right to build your table"})]})}):e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(s.DndContext,{sensors:P,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:m.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:m.map((k,D)=>e.jsx("th",{style:{width:l[k.id]?`${l[k.id]}px`:void 0,minWidth:l[k.id]?`${l[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:m.map(k=>k.id),strategy:s.horizontalListSortingStrategy,children:m.map(k=>e.jsx(Jr,{column:k,isSelected:(t==null?void 0:t.id)===k.id,onSelect:()=>n(k),availableFields:r,width:l[k.id],onWidthChange:S},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:u,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:N.map(k=>{const D=s.getDataType(k.dataType),B=D==="number"?s.Hash:D==="date"?s.Calendar:s.Type;return e.jsxs(s.CommandItem,{value:k.label||k.name,onSelect:()=>T(k),children:[e.jsx(B,{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:m.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:m.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}),m.map(B=>{const C=k[B.name]??k[B.label??""];return e.jsx("td",{style:{width:l[B.id]?`${l[B.id]}px`:void 0,minWidth:l[B.id]?`${l[B.id]}px`:"120px"},className:s.cn("border-r border-border px-3 py-2 text-sm",(t==null?void 0:t.id)===B.id&&"bg-primary/5"),children:e.jsx("span",{className:"block truncate",children:Wr(C,B)})},`${D}-${B.id}`)}),e.jsx("td",{className:"w-10 border-r border-border"})]},D))})]}),e.jsx(s.DragOverlay,{children:f&&e.jsx("div",{className:"rounded border border-primary bg-background px-3 py-2 text-sm font-medium shadow-lg",children:f.label||f.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:[m.length," columns"]})]})]})}function Wr(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 Xr({entityGroups:t,isLoading:n=!1}){var P,O;const a=s.useEditorStore(L=>L.card),{updateCardConfig:r,removeGroupByColumn:i,removeMetricColumn:c}=s.useEditorActions(),[o,d]=I.useState(!0),[l,x]=I.useState(""),[p,u]=I.useState(new Set),m=((P=a==null?void 0:a.config)==null?void 0:P.groupByColumns)||[],N=((O=a==null?void 0:a.config)==null?void 0:O.metricColumns)||[],y=L=>{const f=new Set(p);f.has(L)?f.delete(L):f.add(L),u(f)},h=L=>m.some(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName)||N.some(f=>f.name===L.name&&f.qualifiedEntityName===L.qualifiedEntityName),b=(L,f)=>{if(f)if(s.getDataType(L.dataType)==="number"){const E={...L,id:`metric-${L.id}-${Date.now()}`,role:"metric",aggregate:"SUM"};r(a.id,{metricColumns:[...N,E]})}else{const E={...L,id:`groupby-${L.id}-${Date.now()}`,role:"groupby"};r(a.id,{groupByColumns:[...m,E]})}else{const w=m.findIndex(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName),E=N.findIndex(g=>g.name===L.name&&g.qualifiedEntityName===L.qualifiedEntityName);w!==-1&&i(a.id,m[w].id),E!==-1&&c(a.id,N[E].id)}},S=L=>{if(!l)return L;const f=l.toLowerCase();return L.filter(w=>w.name.toLowerCase().includes(f)||w.label&&w.label.toLowerCase().includes(f))},T=L=>{switch(s.getDataType(L)){case"number":return s.Hash;case"date":return s.Calendar;default:return s.Type}};return o?e.jsxs("div",{className:"flex h-full w-72 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Columns"}),e.jsx(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(_t,{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:l,onChange:L=>x(L.target.value),className:"h-8 pl-8 text-sm"})]})}),(m.length>0||N.length>0)&&e.jsxs("div",{className:"border-b border-border",children:[m.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:m.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:m.map(L=>{const f=T(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(f,{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)})})})]}),N.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:N.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"space-y-0.5 px-3 pb-2",children:N.map(L=>{const f=T(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(f,{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 f=S(L.columns);if(f.length===0)return null;const w=p.has(L.entityId)||l.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:f.length})]}),e.jsx(s.CollapsibleContent,{children:e.jsx("div",{className:"ml-4 space-y-0.5 border-l border-border pl-2",children:f.map(E=>{const g=T(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(g,{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(Ht,{className:"h-4 w-4"})})})}const Zr=[{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 el({value:t,onChange:n,onSubmit:a,onCancel:r,selectedColumn:i,availableColumns:c}){const[o,d]=I.useState(!1),[l,x]=I.useState("column"),p=I.useRef(null);I.useEffect(()=>{const y=h=>{h.key==="Escape"&&t?r():h.key==="Enter"&&t&&!o&&a(t)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t,r,a,o]);const u=y=>{const h=`[${y.label||y.name}]`,b=p.current;if(b){const S=b.selectionStart||0,T=b.selectionEnd||0,P=t.slice(0,S)+h+t.slice(T);n(P),setTimeout(()=>{b.setSelectionRange(S+h.length,S+h.length),b.focus()},0)}else n(t+h);d(!1)},m=y=>{const h=p.current;if(h){const b=h.selectionStart||0,S=h.selectionEnd||0,T=t.slice(0,b)+y.syntax+t.slice(S);n(T),setTimeout(()=>{h.setSelectionRange(b+y.name.length+1,b+y.syntax.length-1),h.focus()},0)}else n(t+y.syntax);d(!1)},N=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:o&&l==="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(Qt,{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:Zr.map(y=>e.jsx(s.CommandItem,{value:y.name,onSelect:()=>m(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:o&&l==="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=N(y.dataType);return e.jsxs(s.CommandItem,{value:y.label||y.name,onSelect:()=>u(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 sl({className:t}){var m,N,y,h;const n=s.useEditorStore(b=>b.card),[a,r]=I.useState(null),[i,c]=I.useState(""),{columns:o=[],columnGroups:d=[],isLoading:l}=s.useColumns();(m=n==null?void 0:n.config)!=null&&m.groupByColumns,(N=n==null?void 0:n.config)!=null&&N.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)},u=()=>{c(""),r(null)};return e.jsxs("div",{className:s.cn("flex h-full w-full flex-col",t),children:[e.jsx(el,{value:i,onChange:c,onSubmit:p,onCancel:u,selectedColumn:a,availableColumns:o}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(Qr,{selectedColumn:a,onColumnSelect:x,isLoading:l,sourceFields:o})}),e.jsx(Xr,{entityGroups:d,isLoading:l})]})]})}function tl(){var z,G;const[t,n]=I.useState("chart"),[a,r]=I.useState(!1),[i,c]=I.useState(!1),[o,d]=I.useState(!0),l=s.useEditorStore(V=>V.showAIDialog),x=s.useDashboardStore(V=>V.isVisualEditing),{setCardType:p}=s.useEditorActions(),u=s.useEditorStore(V=>V.card.type);I.useEffect(()=>Hr(),[]);const m=V=>{p(V)},N=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:S,setActiveCard:T,updateFilters:P}=s.useEditorActions(),{columnFields:O=[],scopedFields:L=[],isLoading:f,error:w}=s.useScopedFields(),E=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),g=y,{getFieldsForContainer:M,setFieldsForContainer:j}=s.useFieldManagement(g),{activeField:k,handleDragStart:D,handleDragEnd:B}=Br({activeCardId:N.activeCardId,sourceFields:L,getFieldsForContainer:M,setFieldsForContainer:j}),C=(V,U)=>{U&&P(V,U)},A=V=>{var U;S(V,{config:{...(U=N.cards.find(W=>W.id===V))==null?void 0:U.config,filters:void 0}})},v=O,R=V=>{if(!V)return 0;let U=V.conditions.length;return V.groups.forEach(W=>{U+=R(W)}),U},F=R(((z=g==null?void 0:g.config)==null?void 0:z.filters)||null);return e.jsxs(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragStart:D,onDragEnd:B,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Zs,{isVisible:o,onToggleVisibility:()=>d(!o)}),e.jsx("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:u==="tableBuilder"?e.jsx(sl,{className:"flex-1"}):e.jsxs(e.Fragment,{children:[!l&&e.jsx(yr,{selectedChart:u,onChartChange:m,groupByFields:M("groupBy"),pivotByFields:M("pivotBy"),metricsFields:M("metrics"),sortByFields:M("sortBy"),detailFields:M("detailColumns"),activeField:k}),e.jsx(Ur,{selectedChart:u,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:F,activeCard:g,dataSourceState:y.dataSource||s.EMPTY_DATA_SOURCE,columns:O,columnsLoading:f,columnsError:w,getFieldsForContainer:M,cards:N.cards,activeCardId:N.activeCardId,addCard:h,setActiveCard:T})]})}),!o&&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"})})})]}),g&&e.jsx(Pr,{cardId:g.id,filters:((G=g.config)==null?void 0:G.filters)||null,onFiltersChange:C,onClearFilters:A,availableFields:v,isOpen:i,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(_r,{activeField:k||null})})]})}function al({authToken:t,onSave:n,onClose:a}){const r=I.useRef(null),i=s.useEditorStore(f=>f.showAIDialog),c=s.useEditorStore(f=>f.isDevMode),o=s.useAssistantLayoutStore(f=>f.setFullscreen),d=s.useAssistantLayoutStore(f=>f.setPanelOpen),l=s.useAssistantLayoutStore(f=>f.setContainer),x=s.useAssistantPanel("editor"),p=s.useFullscreenAssistant(),u=s.useAssistantContainer("editor"),m=p==="editor",N=I.useCallback(f=>{l("editor",f)},[l]),{setAuthToken:y}=s.useDashboardActions(),{setShowAIDialog:h,setOnSave:b,setOnClose:S}=s.useEditorActions(),{setActiveAssistantType:T}=s.useAIActions();I.useEffect(()=>{n&&b(n),a&&S(a)},[n,b,a,S]),I.useEffect(()=>{t&&t.accessToken&&y(t)},[t,y]),I.useEffect(()=>{var f,w;i?((f=r.current)==null||f.resize(40),d("editor",!0),T("editor")):((w=r.current)==null||w.resize(0),d("editor",!1),p==="editor"&&o(null),T(null))},[i,d,T,o,p]);function P(f){var w;f<1?(h(!1),d("editor",!1),p==="editor"&&o(null),T(null),(w=r.current)==null||w.resize(0)):(i||(h(!0),T("editor")),x.isOpen||d("editor",!0))}function O(){return e.jsxs(e.Fragment,{children:[e.jsx(Zs,{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",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(ar,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(qs,{isFullscreen:m,onFullscreenChange:f=>o(f?"editor":null),fullscreenContainer:u})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!m&&"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",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(tl,{})}),e.jsx(s.ResizableHandle,{disabled:!i}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:P,defaultSize:x.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(qs,{isFullscreen:m,onFullscreenChange:f=>o(f?"editor":null),fullscreenContainer:u})})})]}),e.jsx("div",{ref:N,className:s.cn("absolute inset-0",!m&&"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 nl(){s.useDashboardStore(l=>l.selectedCardId);const t=s.useDashboardStore(l=>l.selectedSheetId),n=s.useDashboardStore(l=>l.dashboard),{setIsVisualEditing:a,setSelectedSheetId:r}=s.useDashboardStore(l=>l.actions),i=s.useDashboardStore(l=>l.isVisualEditing),c=s.useDashboardStore(l=>l.actions.updateFrame);function o(l){var m,N,y;const x=t?(m=n==null?void 0:n.sheets)==null?void 0:m.some(h=>{var b;return h.id===t&&((b=h.frames)==null?void 0:b.some(S=>S.id===l.id))}):!1,p=(y=(N=n==null?void 0:n.sheets)==null?void 0:N.find(h=>{var b;return(b=h.frames)==null?void 0:b.some(S=>S.id===l.id)}))==null?void 0:y.id,u=x?t:p||null;u&&(c(u,l),t!==u&&r(u),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(al,{onSave:o,onClose:d})})}exports.default=nl;