react-semaphor 0.1.73 → 0.1.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-DwsEdhKP.js → dashboard-plus-A8a3pEVQ.js} +2 -2
- package/dist/chunks/{dashboard-plus-B9WlHlCu.js → dashboard-plus-CC3NzmwJ.js} +4 -4
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -236,5 +236,5 @@ ${v.joinType} JOIN ${D.name}
|
|
|
236
236
|
${u?`Python:
|
|
237
237
|
${u}`:""}
|
|
238
238
|
`;B(R)}function $(){return e.jsxs(e.Fragment,{children:[l&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Ja,{jsonString:JSON.stringify(m,null,2)})})}),m&&m.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>i(!l),className:"absolute bottom-0 right-6 size-7 p-1",children:l?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function O(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.ResizablePanel,{id:"1",order:1,defaultSize:n?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(_a,{})}),n&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),n&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(Ha,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function G(){return e.jsx("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(s.Button,{title:"Shift + Enter",disabled:N||A,onClick:()=>{M()},className:"h-8 shrink-0",size:"sm",children:[N||A?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Ua,{errorSql:T,sql:b==null?void 0:b.sql,error:F,onDebugWithAssistant:z}),e.jsx(Ze,{}),e.jsxs(s.Toggle,{pressed:n,onPressedChange:R=>r(R),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Ka,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!o&&e.jsxs("button",{disabled:o,onClick:()=>{L(!0)},className:"flex h-9 w-full cursor-text items-center justify-start px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-3 size-4 text-foreground/70"}),"Type your question..."]})]})})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[O(),$()]}),G()]})}const Wa=[{value:"table",label:"Table",icon:s.Table2},{value:"aggregateTable",label:"Aggregate",icon:s.Layers},{value:"pivotTable",label:"Pivot",icon:s.Grid3x3}];function Ya({className:t}){const a=s.useEditorStore(d=>d.card),{setCardType:n,setCard:r,updateCardInFrame:l}=s.useEditorActions(),i=["table","aggregateTable","pivotTable"].includes(a.type),c=s.hasValidCardConfig(a.config);if(!i||!c)return null;const o=d=>{var m;const u=d;if(u==="aggregateTable"&&((m=a.config)!=null&&m.pivotByColumns)&&a.config.pivotByColumns.length>0){const x={...a,type:u,config:{...a.config,pivotByColumns:[]}};r(x),l(x)}else{n(u);const x={...a,type:u};l(x)}};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsx(s.RadioGroup,{value:a.type,onValueChange:o,className:"flex flex-row items-center justify-between gap-1 rounded-lg border p-1",children:Wa.map(d=>{const u=d.icon,m=a.type===d.value;return e.jsxs("div",{className:"flex items-center",children:[e.jsx(s.RadioGroupItem,{value:d.value,id:`table-type-${d.value}`,className:"peer sr-only"}),e.jsxs(s.Label,{htmlFor:`table-type-${d.value}`,className:s.cn("flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-sm font-medium transition-all",m?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:bg-muted/50"),children:[e.jsx(u,{className:"h-3.5 w-3.5"}),d.label]})]},d.value)})})})}function Xa({card:t}){var B,L,E,C,f,b,N,A,w,P,I;const[a,n]=S.useState(!1),[r,l]=S.useState([]),{authToken:i}=s.useSemaphorContext(),{theme:c}=s.useTheme(),o=s.getTokenParams(i==null?void 0:i.accessToken),d=s.useDashboardStore(T=>T.themeStyle),u={mode:c||"system",colors:((L=(B=d==null?void 0:d.chart)==null?void 0:B.dataset)==null?void 0:L.backgroundColor)||[]};(E=t.customCardPreferences)!=null&&E.inputData;const{getCard:m}=s.useCustomVisual(((C=t.customCardPreferences)==null?void 0:C.url)||""),x=((f=t.customCardPreferences)==null?void 0:f.visualType)||"single",h=s.useEditorStore(T=>T.frame),{setCustomCardPreferences:p}=s.useEditorActions(),{data:j}=s.useDashboardCardQuery(t),g=S.useCallback((T,y)=>{l(M=>({...M,[T]:y}))},[]);if(!((b=t.customCardPreferences)!=null&&b.componentName))return null;const v=m((N=t.customCardPreferences)==null?void 0:N.componentName);function D(T){n(T)}const k=Object.keys(((A=t.customCardPreferences)==null?void 0:A.dataInputCardIds)||{}).map(T=>{var F,z,$;const y=(z=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:z[T].cardId,M=($=h==null?void 0:h.cards)==null?void 0:$.find(O=>O.id===y);return M||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(S.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[v&&x==="single"&&e.jsx(v,{editing:!0,params:o,theme:u,settings:(w=t.customCardPreferences)==null?void 0:w.settings,onDataChange:g,data:(j==null?void 0:j.records)||[]}),v&&x==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((P=t.customCardPreferences)==null?void 0:P.dataInputCardIds)||{}).map(T=>{var F,z,$;const y=(z=(F=t.customCardPreferences)==null?void 0:F.dataInputCardIds)==null?void 0:z[T].cardId,M=($=h==null?void 0:h.cards)==null?void 0:$.find(O=>O.id===y);if(M)return e.jsx(s.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:g,dataInputIndex:T,card:M},M.id+T)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(v,{theme:u,onDataChange:g,settings:k.map(T=>{var y;return(y=T==null?void 0:T.customCardPreferences)==null?void 0:y.settings}),data:k.map(T=>T!=null&&T.id?r==null?void 0:r[T.id]:[])})})]})]},(I=t.customCardPreferences)==null?void 0:I.componentName)})}function Za({type:t,isLinked:a,className:n}){const r=s.useDashboardStore(h=>h.selectedFrameId),l=s.useManagementStore(h=>h.selectedVisual),i=s.useEditorStore(h=>h.frame);let c;if(t)c=t;else if(a!==void 0)c=a?"linked":"library";else if(!!!(i!=null&&i.visualId||l!=null&&l.id)&&r)c="local";else if(l&&!r)c="library";else if(i!=null&&i.visualId&&r)c="linked";else if(l!=null&&l.id&&r)c="library";else return null;if(c==="local")return null;const o={linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},d={linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},u={linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},m={linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},x={linked:e.jsx(Ot,{className:"h-3.5 w-3.5"}),library:e.jsx(Pt,{className:"h-3.5 w-3.5"})};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",o[c],n),children:x[c]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",u[c]),children:[e.jsx(s.TooltipArrow,{className:m[c]}),e.jsx("p",{children:d[c]})]})]})})}function Hs({className:t,...a}){var $;const n=s.useEditorStore(O=>O.card),r=(($=n.customCardPreferences)==null?void 0:$.showCardHeader)??!0,l=s.useEditorStore(O=>O.frame),i=s.useDashboardStore(O=>O.dashboard.filters),[c,o]=S.useState(!1),{currentUser:d}=s.useCurrentUserInfo(),{tokenProps:u}=S.useContext(s.SemaphorContext),m=s.useEditorStore(O=>O.actions.setRunSql),{updateFilter:x}=s.useDashboardActions(),h=i==null?void 0:i.find(O=>O.id===l.filterId),{data:p,isLoading:j,isFetching:g,errorMessage:v,errorSql:D,pagination:k}=s.useDashboardCardQuery(n),B=S.useMemo(()=>(p==null?void 0:p.records)||[],[p==null?void 0:p.records]),{setCard:L,updateCardInFrame:E,setIsDevMode:C,setCardSql:f}=s.useEditorActions(),{data:b}=s.useTopoJson(n),N=S.useMemo(()=>{var O;return n.type!=="pivotTable"||!((O=p==null?void 0:p.records)!=null&&O.length)?null:{records:p.records,columnSubtotalMeta:p.columnSubtotalMeta,subtotalColumns:p.subtotalColumns||[],pivotSchema:p.pivotSchema||[],groupByColumns:p.groupByColumns}},[n.type,p==null?void 0:p.records,p==null?void 0:p.columnSubtotalMeta,p==null?void 0:p.subtotalColumns,p==null?void 0:p.pivotSchema,p==null?void 0:p.groupByColumns]),A=s.usePivotTableConfig(n,N),w=O=>{C(!0),f(O||D||n.sql||n.python||""),setTimeout(()=>{m(!0)},100)},P=()=>{o(!0)},I=S.useMemo(()=>{const O=typeof window<"u"?window.location.href:"",G=typeof navigator<"u"?navigator.userAgent:"",R=typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"";return{category:s.FeedbackCategory.QUERY_GENERATION,user:d,tokenContext:u,systemState:{cardConfig:n.config,dataSource:n.dataSource,dashboardFilters:i,errorMessage:v||void 0,errorSql:D||n.sql||n.python,generatedSql:D||n.sql},metadata:{url:O,userAgent:G,timestamp:new Date().toISOString(),viewport:R}}},[d,u,n,i,v,D]),T=(O,G)=>{var _,J;const R={...n,paginationConfig:{page:O+1,pageSize:G}};L(R),E(R),n.sql&&((J=(_=n.preferences)==null?void 0:_.tablePrefs)!=null&&J.enableDevModePagination)&&m(!0)},y=O=>{var _,J,se,Z;const G=s.sortStateToSortByColumns(O,(_=n.config)==null?void 0:_.metricColumns,(J=n.config)==null?void 0:J.groupByColumns),R={...n,config:{...n.config||{},sortByColumns:G}};L(R),E(R),n.sql&&((Z=(se=n.preferences)==null?void 0:se.tablePrefs)!=null&&Z.enableDevModePagination)&&m(!0)},M=S.useMemo(()=>!n.id||!(p!=null&&p.records)?null:s.createChartConfig({card:n,data:p==null?void 0:p.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:b}),[n.id,p==null?void 0:p.records,n.type,n.customCfg,n.preferences,b]);function F(O){return e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Xa,{card:O})})}function z(){if(p!=null&&p.records&&(p==null?void 0:p.records.length)===0&&!j&&!g)return v?e.jsx("div",{className:"flex h-full flex-col items-start justify-start overflow-auto p-4",children:e.jsx(as,{error:v,errorSql:D||n.sql||n.python,onOpenInEditor:w,onSendFeedback:P,showFeedbackButton:!0,errorTitle:"Unable to Create Visual"})}):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((j||g)&&n.type!=="table")return 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(!n.id)return null;if(n.type==="custom")return F(n);if(!["table","pivotTable","aggregateTable","custom"].includes(n.type)&&M)return e.jsx("div",{className:"relative h-full min-h-0 w-full flex-1 grow basis-0",children:j||g?e.jsx(e.Fragment,{}):e.jsx(s.ChartJsVisual,{cfg:M})});if(n.type==="table")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:n,data:B,paginationMetadata:k,onPaginationChange:T,onSortChange:y,isLoading:j||g})});if(n.type==="pivotTable"&&A)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:n,data:A.data,options:A.options,onAggregationChange:O=>{const G=s.handleAggregationChange(O,n.config),R={...n,config:G};L(R),E(R)},onAggregationLabelChange:O=>{const G=s.handleAggregationLabelChange(O,n.config),R={...n,config:G};L(R),E(R)}})});if(n.type==="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:n,data:(p==null?void 0:p.records)||[],groupByColumns:p==null?void 0:p.groupByColumns,pivotSchema:p==null?void 0:p.pivotSchema,paginationMetadata:k,onPaginationChange:T,onAggregationChange:O=>{const G=s.handleAggregationChange(O,n.config),R={...n,config:G};L(R),E(R)},isLoading:j||g})})}return e.jsxs(s.Card,{role:"editor-visual-card",className:s.cn("relative flex h-full flex-col rounded-none",t),...a,children:[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:n.title,onSave:O=>L({...n,title:O}),isEditable:!0,placeholder:"Add title",displayClassName:"text-base font-semibold",inputClassName:"text-base font-semibold"})}),e.jsx(Za,{}),e.jsx("div",{className:"ml-auto",children:e.jsx(Ya,{})})]}),e.jsx("div",{className:"w-1/2",children:e.jsx(s.EditableText,{value:n.description||"",onSave:O=>L({...n,description:O}),isEditable:!0,placeholder:"Add description",displayClassName:"text-sm text-muted-foreground",inputClassName:"text-sm"})})]}),h&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Label,{className:"my-1",children:e.jsx(s.EditableText,{value:h.title||h.column,onSave:O=>x({...h,title:O}),isEditable:!0,placeholder:"Filter",displayClassName:"text-sm",inputClassName:"text-sm"})}),e.jsx(s.FilterComponent,{filter:h})]})]}),e.jsx(s.CardContent,{className:"flex grow flex-col",children:z()}),e.jsx(s.FeedbackDialog,{open:c,onOpenChange:o,feedbackData:I,showDebugInfo:!0})]})}const Ke=({language:t,value:a,onChange:n,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:a,onChange:n}),en=()=>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."})]})]}),sn=({customCode:t,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:l})=>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(Ke,{language:"json",value:n,onChange:r})}),e.jsx(s.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(s.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Ke,{language:"javascript",value:t,onChange:l})})]}),tn=({error:t,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:l})=>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:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(s.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(s.Button,{onClick:l,variant:"outline",children:"Close"})]});function an(){const[t,a]=S.useState(!1),[n,r]=S.useState(""),[l,i]=S.useState(""),[c,o]=S.useState(""),[d,u]=S.useState(""),m=s.useEditorStore(E=>E.card),x=s.useEditorStore(E=>E.card.customCfg),h=x?JSON.stringify(x,null,2):"",{data:p}=s.useDashboardCardQuery(m),{data:j}=s.useTopoJson(m),{setCardCustomCfg:g,setCustomVisualCode:v}=s.useEditorActions(),D=E=>{var C,f;return JSON.stringify({...E,data:{...E.data,datasets:(f=(C=E.data)==null?void 0:C.datasets)==null?void 0:f.map(b=>({...b,data:[]}))}},null,2)},k=()=>{var C,f;if(!((C=p==null?void 0:p.records)!=null&&C.length))return;const E=s.createChartConfig({card:m,data:p.records,cardType:m.type,queryConfig:m.queryConfig,preferences:m.preferences,topoJson:j});if(E){r(D(E)),o(((f=m.preferences)==null?void 0:f.customVisualCode)||"");const b=s.merge(E,x);i(D(b))}},B=()=>{try{if(c&&v(c),l){const E=JSON.parse(l),C=s.getObjectDiff(JSON.parse(n),E);g(C),u("")}}catch{u("Invalid JSON configuration")}},L=Object.keys(x||{}).length===0;return e.jsxs(s.Dialog,{open:t,onOpenChange:a,children:[e.jsx(s.DialogTrigger,{asChild:!0,children:e.jsx(s.IconButton,{tooltip:"Customize Visual",onClick:k,className:L?"":"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(en,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Hs,{className:"w-1/2 rounded shadow-none"})}),e.jsx(sn,{customCode:c,cardCustomCfgString:h,mergedConfig:l,onConfigChange:E=>i(E??""),onCodeChange:E=>o(E??"")})]}),e.jsx(tn,{error:d,hasCardCustomConfig:!!x,onReset:()=>{i(n),g(null)},onApply:B,onClose:()=>a(!1)})]})]})}function Ge(t){const[a,n]=S.useState(null);return a}function Js(){const{authToken:t,tokenProps:a}=s.useSemaphorContext(),{data:n,isLoading:r,isFetching:l,isError:i}=s.useQuery({queryKey:["plugins",t==null?void 0:t.accessToken],queryFn:()=>s.getPlugins(a.apiServiceUrl,t==null?void 0:t.accessToken)});return{data:n,isLoading:r,isFetching:l,isError:i}}function Qs(){const{data:t,isLoading:a,isError:n}=Js(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(o=>({queryKey:["manifest",o.value],queryFn:()=>s.loadManifest(o.value),enabled:!!o.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:d=>Math.min(1e3*2**d,3e4)}))}),l=[];let i=a,c=n;return r.forEach((o,d)=>{var u;if(o.isLoading&&(i=!0),o.isError&&(c=!0),o.data&&((u=t==null?void 0:t.plugins)!=null&&u[d])){const m=t.plugins[d],x=o.data.visuals.map(h=>({name:h.name,pluginName:m.label,componentType:h.componentType,pluginType:m.type,icon:h.icon,chartType:h.chartType,url:m.value}));l.push(...x)}}),{data:l,isLoading:i,isError:c}}function nn({onChartTypeChange:t}){const{setCardCustomCfg:a,setCardPreferences:n,setCardType:r,setCustomCardPreferences:l}=s.useEditorActions(),{data:i,isLoading:c,isError:o}=Qs(),d=S.useCallback((u,m)=>{a(null),n({}),r(u),m&&l({type:"component",visualType:"single",url:m.url,componentName:m.name,icon:m.icon}),t==null||t()},[a,n,r,l,t]);return c?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 visuals..."})]}):o?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!i||i.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:i.map((u,m)=>e.jsx(rn,{text:u.name,onClick:()=>d("custom",u),icon:u.icon},`${u.url}-${u.name}-${m}`))})]})}const rn=({text:t,icon:a,onClick:n})=>{const r=Ge();return e.jsxs("button",{onClick:n,className:"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:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(Ae,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function ln({onChartTypeChange:t,iconClassName:a,searchQuery:n=""}){const{setCardType:r,setCardPreferences:l,setIsDevMode:i}=s.useEditorStore(h=>h.actions),{setCardCustomCfg:c,setCustomCardPreferences:o,setQueryConfig:d}=s.useEditorActions();function u(h,p){c(null),l({}),r(h),["custom","text","map"].includes(h)&&(i(!0),d(void 0)),t==null||t()}const x=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"bullet",name:"Bullet Chart",icon:s.BulletChartIcon},{type:"treemap",name:"Treemap",icon:s.TbChartTreemap},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:Ae}].filter(h=>h.name.toLowerCase().includes(n.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:x.map(h=>{const p=h.icon;return e.jsxs("button",{onClick:()=>u(h.type),className:"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:[e.jsx(p,{className:s.cn("h-6 w-6",a),strokeWidth:h.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:h.name})]},h.type)})})}function on({chartType:t,className:a,customIcon:n,componentName:r}){const l=Ge();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:a});case"line":return e.jsx(s.ChartLine,{className:a});case"pie":return e.jsx(s.ChartPie,{className:a});case"radar":return e.jsx(s.Radar,{className:a});case"scatter":return e.jsx(s.ChartScatter,{className:a});case"bubble":return e.jsx(s.TbChartBubble,{className:a});case"doughnut":return e.jsx(s.Donut,{className:a});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:a});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:a});case"polarArea":return e.jsx(s.PiChartPolar,{className:a});case"treemap":return e.jsx(s.TbChartTreemap,{className:a});case"bullet":return e.jsx(s.BulletChartIcon,{className:a});case"funnel":return e.jsx(s.TbChartFunnel,{className:a});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:a});case"range":return e.jsx(s.ChartNoAxesGantt,{className:a});case"kpi":return e.jsx(s.TiSortNumerically,{className:a});case"text":return e.jsx(s.Type,{className:a});case"map":return e.jsx(s.Map,{className:a});case"custom":return n&&l?e.jsx(l,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Ae,{className:a});default:return e.jsx(s.Table2,{className:a})}}function Ws({variant:t="ghost"}){var o,d;const[a,n]=S.useState(!1),[r,l]=S.useState(""),i=s.useEditorStore(u=>u.card),c=i.type;return e.jsxs(s.Popover,{open:a,onOpenChange:u=>{n(u),u||l("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx(on,{className:"size-4",chartType:c,customIcon:(o=i.customCardPreferences)==null?void 0:o.icon,componentName:(d=i.customCardPreferences)==null?void 0:d.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:u=>u.preventDefault(),className:"z-[70] w-[360px] p-3",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:r,onChange:u=>l(u.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:[e.jsx(ln,{onChartTypeChange:()=>n(!1),searchQuery:r}),e.jsx(nn,{onChartTypeChange:()=>n(!1)})]})]})]})}function cn({error:t,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[l,i]=S.useState(!1),c=S.useRef(null),o=S.useRef(!1);function d(){t&&!o.current&&navigator.clipboard.writeText(t)}function u(h){(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d())}function m(){const h=window.getSelection();if(h&&h.toString().trim()!==""){const p=h.toString();navigator.clipboard.writeText(p),i(!0),o.current=!0,setTimeout(()=>{i(!1),o.current=!1},1e3)}else o.current=!1}function x(){i(!1),o.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:d,onKeyDown:u,onMouseUp:m,onMouseDown:x,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),l&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function dn(){const t=s.useEditorStore(d=>{var u,m;return(m=(u=d.card.preferences)==null?void 0:u.chartOptions)==null?void 0:m.indexAxis}),a=s.useEditorStore(d=>d.card.type),{setChartOrientation:n,setCardPreferences:r}=s.useEditorStore(d=>d.actions),l=d=>{if(n(d),a!=="bullet")return;const u=d==="y"?"horizontal":"vertical",m=s.useEditorStore.getState().card.preferences,x={...m||{},bulletConfig:{...(m==null?void 0:m.bulletConfig)||{},orientation:u}};r(x)};function i(){const d=t??"x",u=()=>{l(d==="x"?"y":"x")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="x"?e.jsx(Ue,{className:"size-4"}):e.jsx(qe,{className:"size-4"})})}function c(){const d=()=>{l(t==="y"||t===void 0?"x":"y")};return e.jsx(s.IconButton,{onClick:d,tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(Ue,{className:"size-4"}):e.jsx(qe,{className:"size-4"})})}function o(){const d=t??"y",u=()=>{l(d==="y"?"x":"y")};return e.jsx(s.IconButton,{onClick:u,tooltip:"Chart Orientation",children:d==="y"?e.jsx(qe,{className:"size-4"}):e.jsx(Ue,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?c():a==="bullet"?o():i()})}function un({className:t}){var h,p,j,g,v,D,k,B;const a=s.useEditorStore(L=>L.card),{setCardPreferences:n,updateCardInFrame:r,setCard:l}=s.useEditorActions(),[i,c]=S.useState(!1),o=((p=(h=a.preferences)==null?void 0:h.displayOptions)==null?void 0:p.showFilterInfo)??!0,d=((g=(j=a.preferences)==null?void 0:j.displayOptions)==null?void 0:g.showCardToolbar)??!0,u=((D=(v=a.preferences)==null?void 0:v.displayOptions)==null?void 0:D.showChrome)??!0,m=((B=(k=a.preferences)==null?void 0:k.displayOptions)==null?void 0:B.allowScroll)??!0,x=(L,E)=>{var b;const C={...a.preferences,displayOptions:{...(b=a.preferences)==null?void 0:b.displayOptions,[L]:E}};n(C);const f={...a,preferences:C};l(f),r(f)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:i,onOpenChange:c,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(As,{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:o,onCheckedChange:L=>{x("showFilterInfo",L)},onSelect:L=>L.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:d,onCheckedChange:L=>{x("showCardToolbar",L)},onSelect:L=>L.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:u,onCheckedChange:L=>{x("showChrome",L)},onSelect:L=>L.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:m,onCheckedChange:L=>{x("allowScroll",L)},onSelect:L=>L.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"})]})]})]})})}function Ys(){const t=s.useEditorStore(i=>i.card),a=s.useEditorStore(i=>{var c,o;return(o=(c=i.card)==null?void 0:c.preferences)==null?void 0:o.chartOptions}),n=s.getChartGridStyle(a),{setChartGrid:r}=s.useEditorActions();function l(){const i=["xy","none","x","y"],o=(i.indexOf(n)+1)%i.length;r(i[o])}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(dn,{})}),!["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:l,children:[(n==="xy"||!n)&&e.jsx(s.Grid3x3,{className:"size-4"}),n==="x"&&e.jsx(Ct,{className:"size-4"}),n==="y"&&e.jsx(Ut,{className:"size-4"}),n==="none"&&e.jsx(Ht,{className:"size-4"})]}),e.jsx(un,{})]})}function mn(){const t=s.useEditorStore(j=>j.frame),a=s.useEditorStore(j=>j.card),{setFrame:n,setActiveTabCardId:r,setCard:l,updateCardInFrame:i}=s.useEditorActions(),c=(j,g)=>{j.dataTransfer.setData("tabIndex",g.toString())},o=j=>{j.preventDefault()},d=(j,g)=>{const v=j.dataTransfer.getData("tabIndex");if(v===g.toString())return;const D=Array.from(t.cards),[k]=D.splice(parseInt(v),1);D.splice(g,0,k),n({...t,cards:D})};function u(j){const g=t.cards.filter(k=>k.id!==j),v=g[0],D={...t,cards:g,activeCardId:v.id};n(D),r(v.id),l(v)}function m(j,g){const v={...t,cards:[...t.cards,g],activeCardId:j.id};n(v),r(g.id)}function x(){const j={...a,id:s.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`};m(a,j)}function h(j){const g={dataSource:j.dataSource,connectionId:j.connectionId,lastSelectedDatabase:j.lastSelectedDatabase,lastSelectedSchema:j.lastSelectedSchema,lastSelectedTable:j.lastSelectedTable,lastSelectedDatamodelId:j.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};m(j,g)}function p(j,g){return j.cards.length===1&&(g.displayTab===!0||g.displayTab===void 0)||j.activeCardId!==g.id&&(g.displayTab===!0||g.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const v=g.displayTab===void 0?!1:!g.displayTab;l({...g,displayTab:v}),i({...g,displayTab:v})},children:g.displayTab===!0||g.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Tt,{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:[t.cards.map((j,g)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:v=>c(v,g),onDragOver:o,onDrop:v=>d(v,g),className:"",value:j.id,children:[p(t,j),e.jsx(s.Editable,{enabled:t.activeCardId===j.id,text:j.tabTitle||j.title,onSave:v=>{l({...a,tabTitle:v}),i({...a,tabTitle:v})},children:j.tabTitle||j.title},j.id),t.activeCardId===j.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:v=>{v.stopPropagation(),x()}}),t.activeCardId===j.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>u(j.id)})]},j.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>h(a),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function Ye(){const t=s.useEditorStore(v=>v.frame),a=s.useEditorStore(v=>v.card),n=s.useEditorStore(v=>v.isSqlRunning),r=s.useEditorStore(v=>v.isDevMode),{setFrame:l,setActiveTabCardId:i,setCard:c,setIsDevMode:o,setRunSql:d}=s.useEditorActions(),{data:u,isLoading:m,isFetching:x,isError:h}=s.useDashboardCardQuery(a);function p(v){const D=t.cards.find(k=>k.id===v);if(D!=null&&D.sql){r||o(!0),i(v);return}if(D!=null&&D.queryConfig){r&&o(!1),j(v),i(v);return}r||j(v),i(v)}function j(v){const D={...t,cards:t.cards.map(B=>B.id===a.id?a:B),activeCardId:v};l(D);const k=D.cards.find(B=>B.id===v);k.sql&&d(!0),c(k)}function g(){return a.type==="kpi"?m||x?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 border-border",children:e.jsx(s.KPICard,{card:a,data:u==null?void 0:u.records,isPending:m||x,isError:h})})}):a.type==="text"?m||x?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:n,card:a,data:u==null?void 0:u.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(Hs,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:p,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(v=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:v.id,children:g()},v.id)),e.jsx(mn,{})]})}function fs({children:t}){var f,b;s.useEditorStore(N=>N.frame);const a=s.useEditorStore(N=>N.card),n=s.useEditorStore(N=>N.isDevMode),r=s.useEditorStore(N=>N.isShowingVisual),l=s.useDashboardStore(N=>N.isVisualEditing),i=s.useEditorStore(N=>N.pythonStdOut);s.useEditorStore(N=>N.actions.setRunSql);const{setFrame:c,setCard:o,setActiveTabCardId:d,runAssistant:u,setIsDevMode:m,setCardPreferences:x}=s.useEditorActions(),{data:h,isLoading:p,isFetching:j,errorMessage:g,refetch:v}=s.useDashboardCardQuery(a),D=S.useMemo(()=>(h==null?void 0:h.records)||[],[h==null?void 0:h.records]),[k,B]=S.useState(!1);S.useEffect(()=>{j||B(!1)},[j]);function L(){const N=JSON.stringify(h==null?void 0:h.records,null,2),A=new Blob([N],{type:"application/json"}),w=URL.createObjectURL(A),P=document.createElement("a");P.href=w,P.download=`${a.title}.json`,P.click()}function E(){const A=[Object.keys(h==null?void 0:h.records.reduce((T,y)=>({...T,...y}),{})).join(","),...((h==null?void 0:h.records)||[]).map(T=>Object.values(T).join(","))].join(`
|
|
239
|
-
`),w=new Blob([A],{type:"text/csv"}),P=URL.createObjectURL(w),I=document.createElement("a");I.href=P,I.download=`${a.title}.csv`,I.click()}function C(){const N=`Can you get the documentation for ${a.type} chart?`;u(N)}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:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ws,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:C,children:e.jsx(vt,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(an,{})]}),!r&&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:E,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:L,children:e.jsx(kt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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:p||j,onClick:()=>{B(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":k})})}),e.jsx(Ys,{})]}),a.type==="table"&&a.sql&&n&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((b=(f=a.preferences)==null?void 0:f.tablePrefs)==null?void 0:b.enableDevModePagination)??!1,onCheckedChange:N=>{var A;x({...a.preferences,tablePrefs:{...(A=a.preferences)==null?void 0:A.tablePrefs,enableDevModePagination:N}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xn,{})]}),r?e.jsx(Ye,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(hn,{})}),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":i}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:D}),g&&e.jsx(cn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function hn(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=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:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xn(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:i,icon:c,showPlaceholderLabel:o=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),o&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function pn(){var g,v;const t=s.useEditorStore(D=>D.card.customCardPreferences),{data:a}=Js(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(D=>D.card),l=s.useEditorStore(D=>D.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:o,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(g=d==null?void 0:d.visuals)==null?void 0:g.find(D=>D.name===(t==null?void 0:t.componentName));function m(D,k){if(!t)return;const L={...(t==null?void 0:t.dataInputCardIds)||{},[D]:{cardId:k,hookRef:null}};c({...t,dataInputCardIds:L})}function x(D){var B,L;const k=(B=l==null?void 0:l.cards)==null?void 0:B.filter(E=>{var C;return((C=E==null?void 0:E.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(L=D==null?void 0:D.dataInputs)==null?void 0:L.map((E,C)=>{var f,b;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((b=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[C])==null?void 0:b.cardId)||"",onValueChange:N=>m(C,N)})]},C+Math.random())})})}function h(D,k,B=[],L=""){var E,C;return t?D==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[k])||L,onChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f.target.value}})}},k):D==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:B,value:((C=t==null?void 0:t.settings)==null?void 0:C[k])||L,onValueChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f}})}}):null:null}function p(D){const k=Object.entries((D==null?void 0:D.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([B,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),h(L.ui,B,L.options,L.defaultValue)]},B))})}function j(D){t&&c({...t,visualType:D,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",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:[e.jsx(ye,{icon:e.jsx(bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:D=>c({...t||{url:"",componentName:""},url:D})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:o&&e.jsx(ye,{icon:e.jsx(St,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(D=>D.type===i).map(D=>({value:D.name,label:D.name})))||[],value:t.componentName,onValueChange:D=>{console.log("changing value",D),c({...t,componentName:D})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:x(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function ke(){const[t,a]=S.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),i=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),S.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(u,m){var x,h;m?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),a(p=>{const j=[...p];return j[u]=!1,j}))}function o(u,m){var h;const x=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...n,onClickFilter:x})}function d(u){var m,x,h,p;if(t!=null&&t[u]||(x=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===u))!=null&&x.expression)return e.jsx(s.Input,{value:(p=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===u))==null?void 0:p.expression,onChange:j=>o(u,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:i==null?void 0:i.map((u,m)=>{var x,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((x=n==null?void 0:n.onClickFilter)!=null&&x.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const j=[...p];return j[m]=!p[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function fn({idx:t}){var o;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=a==null?void 0:a.chartOptions)==null?void 0:o.indexAxis,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const x={...i};x.datalabels=m;const h=n==null?void 0:n.map(p=>p.idx===u?x:p);r({...a,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ms,{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:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Bt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Rt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function gn(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ns({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Xs(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,x;return(x=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:o}=gn();return o.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Zs(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(et,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Zs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function et({col:t,idx:a,className:n,iconClassName:r,children:l}){const i=s.useEditorStore(m=>{var x;return(x=m.card)==null?void 0:x.preferences}),c=s.useEditorStore(m=>{var x,h;return(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),o=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!o)d({...i,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const x={...o};x.type=m==="area"?"line":m,x.fill=m==="area"?"origin":"";const h=c==null?void 0:c.map(p=>p.idx===a?x:p);d({...i,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(ns,{className:"max-w-[100px]",title:t,children:Zs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fn,{idx:a})]})]})}function Me(){const t=s.useDashboardStore(o=>o.dashboard.filters),a=s.useEditorStore(o=>o.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Gs();function i(o){const d=l(o,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(o=>o.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(jn,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jn({columns:t,onSelect:a}){var c;const[n,r]=He.useState(!1),[l,i]=He.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(o=>o.column_name===l))==null?void 0:c.column_name:"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 framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const u=d===l?"":d;i(u),r(!1),u&&a(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function bn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Xs,{})})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function vn({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function st(){const t=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>o.isDevMode),n=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var m;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function i(){var o,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,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 c(){var o,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,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:a?i():c()})}const yn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Nn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Cn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Sn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(st,{}),e.jsx(ke,{}),e.jsx(Me,{})]})]})}function Sn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(yn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Nn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function wn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,o,d){const u=[...t];u[c]={...u[c],[o]:d},a(u)}function l(c){const o=[...t];o.splice(c,1),a(o)}function i(){a([...t,n])}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:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(o,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(o,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(o,"color",d.target.value),value:c.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:()=>l(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function Dn(){var m,x,h,p,j;const t=s.useEditorStore(g=>g.card.preferences),a=s.useEditorStore(g=>g.actions.setCardPreferences),n=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.decimalPlaces});const i=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.locale}),c=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const o=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.colorRanges})||[],d=s.useEditorStore(g=>g.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(g=>g.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:g=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:i||"none",onValueChange:g=>{var v,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.currency)||"",g,((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g.locale,children:g.locale},g.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:g=>{var v,D,k;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((D=t==null?void 0:t.formatNumber)==null?void 0:D.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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"),u.map(g=>e.jsx(s.SelectItem,{value:g,children:g},g))]})})]})]})]}),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:((p=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:g=>{var v,D,k;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((D=t==null?void 0:t.formatNumber)==null?void 0:D.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.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:g=>{var v,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.currency)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.locale)||"",g.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(wn,{colorRanges:o,setColorRanges:d})]})]})}function Tn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Dn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const kn=[{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"}],En=["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"],In=En.map(t=>({label:t,value:t}));function An(){var d,u,m,x,h,p,j,g,v,D,k,B,L,E,C,f,b,N;const t=s.useEditorStore(A=>A.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=S.useState(((x=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(A=>({label:A,value:A}))||[],o=[{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:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ye,{className:"h-9",options:o,onValueChange:A=>{console.log("value",A),l({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ye,{className:"h-9",options:c,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:kn,value:((g=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:In,value:((D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(E=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:C[0])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(A.target.value),((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(b=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:b.projectionOffset)==null?void 0:N[1])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ke,{})]})}function Mn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(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 Be({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Mn,{})})]}),!["range","text"].includes(t)&&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(ke,{}),e.jsx(Me,{})]})]})]})})}function Ln(){const t=s.useEditorStore(r=>{var l,i;return(i=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ye,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Xs,{})]})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function Fn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var i;return(i=l.card)==null?void 0:i.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children: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(ke,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,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 tt({color:t,onColorChange:a,onClose:n}){const[r,l]=S.useState(0),[i,c]=S.useState(100),[o,d]=S.useState(50),[u,m]=S.useState(t);S.useEffect(()=>{const v=gs(t);if(v){const D=js(v.r,v.g,v.b);l(D.h),c(D.s),d(D.l),m(t)}},[t]);const x=v=>{l(v),p(v,i,o)},h=v=>{const D=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-D.left)/D.width)),B=Math.max(0,Math.min(1,(v.clientY-D.top)/D.height)),L=k*100,E=(1-B)*100;c(L),d(E),p(r,L,E)},p=(v,D,k)=>{const B=On(v,D,k),L=Pn(B.r,B.g,B.b);m(L)},j=v=>{if(m(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const D=gs(v);if(D){const k=js(D.r,D.g,D.b);l(k.h),c(k.s),d(k.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:h,onMouseMove:v=>{v.buttons===1&&h(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>x(Number(v.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:u,onChange:v=>j(v.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:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function gs(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Pn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function js(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let i=0,c=0;const o=(r+l)/2;if(r!==l){const d=r-l;switch(c=o>.5?d/(2-r-l):d/(r+l),r){case t:i=((a-n)/d+(a<n?6:0))/6;break;case a:i=((n-t)/d+2)/6;break;case n:i=((t-a)/d+4)/6;break}}return{h:Math.round(i*360),s:Math.round(c*100),l:Math.round(o*100)}}function On(t,a,n){t/=360,a/=100,n/=100;let r,l,i;if(a===0)r=l=i=n;else{const c=(u,m,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(m-u)*6*x:x<.5?m:x<.6666666666666666?u+(m-u)*(.6666666666666666-x)*6:u),o=n<.5?n*(1+a):n+a-n*a,d=2*n-o;r=c(d,o,t+1/3),l=c(d,o,t),i=c(d,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(i*255)}}const Bn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function at(){var B,L,E,C,f,b,N,A,w,P;const t=s.useEditorStore(I=>I.card),a=s.useEditorStore(I=>{var T;return(T=I.card)==null?void 0:T.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[i,c]=S.useState({}),[o,d]=S.useState(null),[u,m]=S.useState(null),x=S.useMemo(()=>{var M,F,z,$,O,G,R;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",y=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||T)&&y){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(J=>{J.alias&&_.add(J.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],J=Object.keys(_),se=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(Y=>{se.add(Y.label||Y.name),se.add(Y.alias||Y.name)});const Z=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(Y=>{const U=Y.alias||Y.name;Z.add(U),Z.add(`${U}_count`),Z.add(`${U}_sum`),Z.add(`${U}_avg`),Z.add(`${U}_min`),Z.add(`${U}_max`);const te=Y.entityName||Y.qualifiedEntityName;te&&(Z.add(`${te}_${U}`),Z.add(`${te}_${U}_count`))}),J.filter(Y=>!se.has(Y)&&!Z.has(Y))}}if((T||I)&&!y&&((O=($=t==null?void 0:t.config)==null?void 0:$.metricColumns)!=null&&O.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((R=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&R.length){const _=t.config.groupByColumns[0],J=_.label||_.name,se=new Set;return l.records.forEach(Z=>{const ae=Z[J];ae!=null&&se.add(String(ae))}),Array.from(se)}return[]},[l,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),h=S.useMemo(()=>s.getDefaultChartColors(),[]);S.useEffect(()=>{const I={};x.forEach((T,y)=>{I[T]=s.getColorForValue(T,y,a==null?void 0:a.colorConfig)}),c(I)},[x,a==null?void 0:a.colorConfig,h]);const p=(I,T)=>{const y={...i,[I]:T};c(y);const M={...a||{},colorConfig:{segments:y}};n(M);const F={...t,preferences:M};r(F)},j=(I,T)=>{var O;const y=h[T%h.length],{[I]:M,...F}=((O=a==null?void 0:a.colorConfig)==null?void 0:O.segments)||{},z={...a||{},colorConfig:{segments:F}};n(z);const $={...t,preferences:z};r($),c(G=>({...G,[I]:y}))};if(!x.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:f.length)||((N=(b=t==null?void 0:t.config)==null?void 0:b.pivotByColumns)==null?void 0:N.length):(w=(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const D=()=>{const I={...a||{},colorConfig:{segments:{}}};n(I);const T={...t,preferences:I};r(T);const y={};x.forEach((M,F)=>{y[M]=s.getColorForValue(M,F,void 0)}),c(y)},k=Object.keys(((P=a==null?void 0:a.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{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:k&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:D,children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:x.map((I,T)=>{const y=s.isDefaultColor(i[I],T),M=!y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===I,onOpenChange:F=>d(F?I: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:i[I]}})}),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:h.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",i[I]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:[z===T%h.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:Bn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",i[I]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(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:I,color:i[I]}),d(null)},children:"Custom color"}),!y&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(I,T),d(null)},children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),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(tt,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ne({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[i,c]=S.useState(t??""),[o,d]=S.useState(!1);S.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(i),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:o?i:t??"",onChange:x=>{c(x.target.value),d(!0)},onFocus:()=>d(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&o&&i!==t?u():x.key==="Escape"&&m()},"aria-label":n||"Edit field"}),o&&i!==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: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 edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Rn=["auto","number","currency","percent","scientific","date"],Vn=[{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"}],zn=[{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"}],Gn=t=>t.charAt(0).toUpperCase()+t.slice(1);function rs({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",i=(o,d)=>{a({...t,[o]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:o=>i("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rn.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Gn(o)},o))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&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??c(),onChange:o=>i("decimalPlaces",parseInt(o.target.value)||0),className:"h-8 text-xs"})})]}),l==="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:o=>i("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Vn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.value))})]})]}),["number","currency"].includes(l)&&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:o=>i("useSuffix",o)})]}),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:o=>i("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.value))})]})]}),l==="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:o=>i("prefix",o.target.value),className:"h-8 text-xs"})})]}),l==="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:o=>i("suffix",o.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&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:o=>i("negativeInParentheses",o)})]}),l==="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:o=>i("multiplyBy",o.target.value?parseFloat(o.target.value):void 0),className:"h-8 text-xs"})})]}),l==="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:o=>i("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function bs({axis:t,label:a,type:n,config:r,onChange:l}){var x,h,p,j,g,v,D,k,B,L,E,C;const i=(f,b)=>{l({...r,[f]:b})},c=(f,b)=>{var N,A;l({...r,name:{enabled:f==="enabled"?b:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?b:(A=r==null?void 0:r.name)==null?void 0:A.text}})},o=(f,b)=>{var N,A;l({...r,labels:{enabled:f==="enabled"?b:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?b:(A=r==null?void 0:r.labels)==null?void 0:A.rotation}})},d=(f,b)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:b===""?"auto":Number(b)}})},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:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>i("enabled",f),onClick:f=>f.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 justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((x=r==null?void 0:r.name)==null?void 0:x.enabled)??!1,onCheckedChange:f=>c("enabled",f)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(Ne,{placeholder:`${a} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>c("text",f),className:""})]}),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:f=>i("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},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",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:f=>o("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.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(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:f=>o("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),n==="value"&&e.jsx(rs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),n==="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(Ne,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.min)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.min)===void 0?"":String(r.scale.min),onSave:f=>d("min",f),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(Ne,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:f=>d("max",f),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(Ne,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function nt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const i=(c,o)=>{const u={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:o};n(u);const m={...t,preferences:u};r(m)};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(As,{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:[l.hasXAxis&&e.jsx(bs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:c=>i("x",c)}),l.hasYAxis&&e.jsx(bs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:c=>i("y",c)})]})})]})}function rt(){const t=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var x,h,p,j;return(j=(p=(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:j.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,i=(r==null?void 0:r.position)??"top",c=(r==null?void 0:r.align)??"center",o=(m,x)=>{const h={...a,[m]:x};n(h)},d=["top","bottom","left","right"],u=["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(Ft,{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)??l,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??l)&&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)||i,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||c,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function lt(){var w,P,I,T,y,M,F,z,$;const t=s.useEditorStore(O=>O.card),a=s.useEditorStore(O=>{var G,R;return(R=(G=O.card)==null?void 0:G.preferences)==null?void 0:R.dataLabelsConfig}),n=s.useEditorStore(O=>{var G;return(G=O.card)==null?void 0:G.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const i=((w=n==null?void 0:n.chartOptions)==null?void 0:w.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!o,u=(I=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),x=t.type==="treemap"?!0:m,h=(a==null?void 0:a.enabled)!==void 0?a.enabled:x,p=(O,G)=>{const R={...a,[O]:G},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},j=(O,G)=>{const R={...a,font:{...a==null?void 0:a.font,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},g=(O,G)=>{const R={...a,formatOptions:{...a==null?void 0:a.formatOptions,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},v=()=>{const O=t.type;return O==="stackedBar"||O==="stackedLine"||O==="pie"||O==="doughnut"?"center":i?"right":"top"},D=t.type!=="treemap"&&t.type!=="heatmap",k=t.type!=="treemap",B=v();let L=[];D&&(c||o?L=["center"]:L=["auto",...(i?["center","left","right"]:["center","top","bottom"]).filter(G=>G!==B),"custom"]);const E=()=>s.titleCase(B),C=["center","start","end"],f=["center","start","end","top","bottom"],b=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],N=[{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"}],A=[{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(Qt,{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:h,onCheckedChange:O=>p("enabled",O)})]}),h&&e.jsxs(e.Fragment,{children:[D&&!c&&!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:(a==null?void 0:a.position)||"auto",onValueChange:O=>p("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?E():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),c&&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:O=>p("showTotal",O)})]}),(a==null?void 0:a.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:(a==null?void 0:a.anchor)||"center",onValueChange:O=>p("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),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((a==null?void 0:a.align)||"center"),onValueChange:O=>p("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:O=>p("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&d?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.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(Ne,{type:"number",placeholder:"0",value:String(((T=a==null?void 0:a.formatOptions)==null?void 0:T.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:O=>g("decimalPlaces",Number(O)),className:""})})]}),a.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:((y=a==null?void 0:a.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:O=>g("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(a.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:((M=a==null?void 0:a.formatOptions)==null?void 0:M.useSuffix)??!1,onCheckedChange:O=>g("useSuffix",O)})]}),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:((F=a==null?void 0:a.formatOptions)==null?void 0:F.locale)||"en-US",onValueChange:O=>g("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),k&&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(Ne,{type:"number",placeholder:"12",value:String(((z=a==null?void 0:a.font)==null?void 0:z.size)||12),onSave:O=>j("size",Number(O)),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:(($=a==null?void 0:a.font)==null?void 0:$.weight)||"normal",onValueChange:O=>j("weight",O),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:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:O=>{O==="auto"&&p("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(Ne,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:O=>p("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Re({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[i,c]=S.useState(t),o=S.useRef(!1);S.useEffect(()=>{c(t)},[t]);const d=()=>{if(o.current){o.current=!1;return}i!==t&&a(i)},u=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(o.current=!0,c(t),m.currentTarget.blur())};return e.jsx(s.Input,{type:n,placeholder:r,value:i,onChange:m=>c(m.target.value),onBlur:d,onKeyDown:u,className:l})}const vs=["poor","satisfactory","good"];function ys(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function ot(){var I,T;const t=s.useEditorStore(y=>y.card.preferences),a=s.useEditorStore(y=>y.card),n=s.useEditorStore(y=>y.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),i=S.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),o=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[d,u]=S.useState(i.showRanges??!1),[m,x]=S.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o,[p,j]=S.useState(h);S.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),S.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const g=i.targetValue===void 0?"":String(i.targetValue);S.useEffect(()=>{const y=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o;j(y)},[i.disableAutoComparative,i.comparativeMetricKey,o]);const v=S.useMemo(()=>{var y,M;return((M=(y=a==null?void 0:a.config)==null?void 0:y.metricColumns)==null?void 0:M.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.metricColumns]);S.useEffect(()=>{var R,_;if(!t||v.length===0)return;const y={};let M=!1;const F=(R=v[1])==null?void 0:R.value;!i.targetMetricKey&&F&&(y.targetMetricKey=F,M=!0);const z=(_=v[2])==null?void 0:_.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&z&&(y.comparativeMetricKey=z,M=!0);const $=v.slice(3),O={...i.rangeKeys||{}};let G=!1;if(vs.forEach((J,se)=>{!O[J]&&$[se]&&(O[J]=$[se].value,G=!0)}),G&&(y.rangeKeys=O,M=!0,i.showRanges===void 0&&(y.showRanges=!0)),M){const J=ys({...i,...y});r({...t,bulletConfig:J})}},[v,i,t,r]);const D=y=>{const M=ys({...i,...y});r({...t,bulletConfig:M})},k=(y,M)=>{const F={...i.rangeKeys||{},[y]:M.trim()};M.trim()||delete F[y],D({rangeKeys:Object.keys(F).length>0?F:void 0})},B=(y,M)=>{const F=M===""?void 0:Number(M),z={...i.ranges||{}};F===void 0||Number.isNaN(F)?delete z[y]:z[y]=F,D({ranges:Object.keys(z).length?z:void 0})},L=y=>{if(y===""){D({targetValue:void 0});return}const M=Number(y);D({targetValue:Number.isNaN(M)?void 0:M})},E=(y,M)=>{const F=M.trim(),z={...i.rangeLabels||{}};F?z[y]=F:delete z[y],D({rangeLabels:Object.keys(z).length>0?z:void 0})},C=y=>{u(y),D({showRanges:y})},f=y=>{x(y),D({rangesArePercentages:y})},b=i.orientation||(((T=t==null?void 0:t.chartOptions)==null?void 0:T.indexAxis)==="y"?"horizontal":"vertical"),N=y=>{D({orientation:y}),l(y==="horizontal"?"y":"x")},A=[{value:"__none",label:"None"},...v.map(y=>({value:y.value,label:y.label}))],w=A,P=y=>{if(j(y),!y){D({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!o){D({disableAutoComparative:!1});return}if(i.comparativeMetricKey)D({disableAutoComparative:!1});else{const M=v.find(F=>F.value!==i.targetMetricKey);D({comparativeMetricKey:M==null?void 0:M.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:b,onValueChange:y=>N(y),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"})]})]})]}),o&&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:i.targetMetricKey||"__none",onValueChange:y=>D({targetMetricKey:y==="__none"?void 0:y}),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"}),v.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),o?e.jsxs(s.Select,{value:i.comparativeMetricKey||"__none",onValueChange:y=>D({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:A.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:y=>P(y)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Re,{type:"number",className:"h-8 text-xs",value:g,onCommit:L,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:d,onCheckedChange:C})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!d,onChange:y=>f(y.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),d&&e.jsx("div",{className:"space-y-3",children:vs.map(y=>{var M,F,z,$,O;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:[y," LABEL"]}),e.jsx(Re,{placeholder:`Display label (${y})`,value:((M=i.rangeLabels)==null?void 0:M[y])||"",onCommit:G=>E(y,G),className:"h-8 text-xs"})]}),o?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(s.Select,{value:((F=i.rangeKeys)==null?void 0:F[y])||"__none",onValueChange:G=>{G==="__none"?k(y,""):k(y,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:w.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:[y," COLUMN KEY"]}),e.jsx(Re,{placeholder:"Column key",value:((z=i.rangeKeys)==null?void 0:z[y])||"",onCommit:G=>k(y,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:[y," VALUE"]}),e.jsx(Re,{type:"number",placeholder:m?"0.80":"Static value",value:(($=i.ranges)==null?void 0:$[y])===void 0?"":String((O=i.ranges)==null?void 0:O[y]),onCommit:G=>B(y,G),className:"h-8 text-xs"})]})]},y)})})]})]})]})}const Ns=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$n=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Pe({value:t,onChange:a,label:n}){const[r,l]=S.useState(!1),[i,c]=S.useState(!1),o=()=>{const d=Ns.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Ns[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:l,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:o()},"aria-label":`Change color for ${n}`})}),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:$n.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),i&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(tt,{color:o(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const qn=Object.keys(s.HEATMAP_PRESET_PALETTES);function it(){const t=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},i=l.colorPalette??"green",c=l.legendPosition??"bottom",o=S.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),d=h=>{const p={...l,...h};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:p})},u=h=>{d({colorPalette:h,colorRange:h==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(h,p)=>{const j=[...o];j[h]=p,d({colorPalette:"custom",colorRange:j})},x=h=>{d({legendPosition:h})};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:i,onValueChange:h=>u(h??"blue"),className:"space-y-3",children:[qn.map(h=>{const p=s.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(s.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Pe,{value:o[0],onChange:h=>m(0,h),label:"Start color"}),e.jsx(Pe,{value:o[1],onChange:h=>m(1,h),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:c,onValueChange:h=>x(h??"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(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}function Un(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="heatmap"&&e.jsx(it,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(ot,{}),e.jsx(at,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})]})}const Kn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),_n=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Hn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Jn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=i=>r.includes(n)?i:e.jsxs(e.Fragment,{children:[i,e.jsx(Un,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Ln,{}));case"tornado":case"pyramid":return l(e.jsx(Be,{docContent:Kn,cardType:n}));case"kpi":return e.jsx(Tn,{});case"line":case"bar":return l(e.jsx(bn,{cardType:n}));case"range":return l(e.jsx(Be,{docContent:_n,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Be,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(vn,{cardType:n}));case"table":return e.jsx(Fn,{cardType:n});case"text":return e.jsx(Be,{docContent:Hn,cardType:n,suffix:"Visual"});case"map":return e.jsx(An,{});case"custom":return e.jsx(pn,{});default:return l(e.jsx(Cn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Qn(){const t=S.useRef(null),a=S.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return S.useEffect(()=>{var l,i,c,o;r?((l=t.current)==null||l.resize(0),(i=a.current)==null||i.resize(0)):((c=t.current)==null||c.resize(25),(o=a.current)==null||o.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(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Jn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(fs,{})})]}):e.jsx(fs,{})})]})}function Wn(t){var me;s.useAIInteractionStore(q=>q.currentAIContext);const[a,n]=S.useState(""),[r,l]=S.useState(null),{authToken:i,tokenProps:c}=s.useSemaphorContext(),o=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.sql}),d=s.useEditorStore(q=>q.isDevMode),u=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.python}),{setCardPython:m,setCardSql:x,setRunSql:h,switchCardType:p,setQueryConfig:j}=s.useEditorActions(),g=s.useEditorStore(q=>q.currentAssitantScope)||[],v=s.useEditorStore(q=>q.userInputForAI),D=s.useEditorStore(q=>q.triggerAIRun),k=s.useEditorStore(q=>q.card),B=s.useEditorStore(q=>q.selectedDatabaseName),L=s.useEditorStore(q=>q.selectedTableName),E=s.useEditorStore(q=>q.selectedConnectionId),C=s.useEditorStore(q=>q.selectedSchemaName),f=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:b,refetch:N,data:A}=s.useDashboardCardQuery(k),{setTriggerAIRun:w,setCurrentAssitantScope:P,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:y,selectedDatamodelId:M}=s.useEditorAside(),F=(me=s.useDashboardQuery().data)==null?void 0:me.assistantProfileId,{messages:z,setMessages:$,regenerate:O,error:G,sendMessage:R,status:_,addToolResult:J,stop:se,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:F,isDevMode:d,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:W})=>({body:{...W,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var W;if(q.name==="AbortError"||(W=q.message)!=null&&W.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:ae,onFinish({isAbort:q,isDisconnect:W,isError:de}){n(""),console.log(q?"[Editor Assistant] Stream aborted by user":W?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});S.useEffect(()=>{D&&v&&(R({role:"user",parts:[{type:"text",text:v}]}),w(!1))},[D,v,R,w]);async function ae({toolCall:q}){var W,de,pe,fe,ce,V,ee,X,je,ge,be,ve,he,Ee,Se,we;if(["createChartFromSql","createForecast"].includes(q.toolName)){const Q=((W=q.input)==null?void 0:W.sql)??((de=q.args)==null?void 0:de.sql),ne=((pe=q.input)==null?void 0:pe.python)??((fe=q.args)==null?void 0:fe.python),le=((ce=q.input)==null?void 0:ce.chartType)??((V=q.args)==null?void 0:V.chartType);p(le),x(Q),m(ne),h(!0),J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!o){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((ee=q.input)==null?void 0:ee.chartType)??((X=q.args)==null?void 0:X.chartType),ne=((je=q.input)==null?void 0:je.queryConfig)??((ge=q.args)==null?void 0:ge.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),p(Q),I(ne),x(void 0),m(void 0);const le=await N();if((he=le==null?void 0:le.data)!=null&&he.error){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:ne,message:(Ee=le==null?void 0:le.data)==null?void 0:Ee.error.message}});return}if((Se=le==null?void 0:le.data)!=null&&Se.records){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(we=le==null?void 0:le.data)==null?void 0:we.records}})}else n("Analyzing...")}function Y(q){const W=s.removeFromScopeArray(g,q);U(W)}function U(q){const W=s.sanitizeAIScope(q);P(W),$(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(W)}`}]}])}function te(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||""},W=s.dedup([...g,q]);U(W)}function H(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||"",datamodelId:M||""};if(!s.isInAiScopeArray([...f||[],...g],q)||g.length===0){const de=s.dedup([...f||[],...g,q]).filter(pe=>pe.connectionId===q.connectionId);U(de)}}const re=!["ready","error"].includes(_),ue=s.getErrorMessage(G);return{messages:z,setMessages:$,sendMessage:R,regenerate:O,isLoading:re,handleSetAIScope:H,handleAddCurrentTableToScope:te,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:P,stop:se,status:_,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:ue,clearError:Z}}const Yn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Cs({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=S.useRef(null),[l,i]=S.useState(!1),[c,o]=S.useState(s.isDevEnv),[d,u]=S.useState(!1),[m,x]=S.useState(!1),[h,p]=S.useState(!1),j=t??h,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:D}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),B=s.useFileAttachments("editor"),L=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),C=s.useEditorStore(Q=>Q.actions.setCardSql),f=s.useEditorStore(Q=>Q.actions.setRunSql),b=s.useEditorStore(Q=>Q.showAIDialog),N=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:A,setCardPython:w}=s.useEditorActions(),{setDataSource:P}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:T,setMessages:y,sendMessage:M,isLoading:F,stop:z,status:$,llmUsage:O,errorMessage:G,clearError:R}=Wn(),[_,J]=S.useState(""),se=Q=>{J(Q.target.value)},Z=Q=>{Q.preventDefault();const ne=_.trim();if(!ne&&B.length===0)return;const le=[];ne&&le.push({type:"text",text:ne}),B.forEach(De=>{De.data&&le.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),M({role:"user",parts:le}),J(""),k("editor"),W({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:U,loadMoreMessages:te,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:ue,hasNewMessages:me,newMessageCount:q,scrollToBottom:W,handleScroll:de,resetNewMessageCount:pe}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:F});S.useEffect(()=>{var Q;b&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[b,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:F,sendMessage:M});const{hasActiveTools:fe}=s.useActiveToolStatus(T),ce=S.useCallback(Q=>{a==null||a(Q),t===void 0&&p(Q)},[t,a]);S.useEffect(()=>{if(!j)return;function Q(ne){ne.key==="Escape"&&ce(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[j,ce]);const V=S.useCallback(Q=>{M({role:"user",parts:[{type:"text",text:Q}]}),W({force:!0})},[M,W]),ee=S.useCallback(async()=>{const Q=JSON.stringify(T??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ne){console.error("Failed to copy conversation",ne),s.ue.error("Unable to copy conversation")}},[T]),X=S.useCallback(()=>{ce(!j)},[j,ce]);function je(Q,ne){ne==="sql"?(C(Q),f(!0)):ne==="python"&&(w(Q),f(!0))}function ge(){g.selectedEntities.length===0&&v({selectedEntities:(L==null?void 0:L.selectedEntities)||[]})}function be(Q){ge();const ne={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};M(ne)}function ve(Q){ge(),M({role:"user",parts:[{type:"text",text:Q}]})}function he(){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:l,onCheckedChange:i,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Ee(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Se=(_==null?void 0:_.length)===0&&(T==null?void 0:T.filter(Q=>Q.role==="user").length)===0,we=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",j&&"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:[Ee(),N&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:N,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ee,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:j?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:X,children:j?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:()=>{y([]),D("editor"),R(),H()},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:()=>{A(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:te,className:"text-xs",children:["Load ",Math.min(5,U-ae.length)," ","more messages (",U-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:c,handleRun:je,showSystemMessage:d,onQuickReply:V,disableQuickReplies:F}),!fe&&e.jsx(s.AssistantStatus,{status:$,errorMessage:G})]})}),b&&!ue&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),pe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),me&&q>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:q>9?"9+":q})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!I&&e.jsx(s.Placeholders,{onClick:be,placeholders:Yn}),e.jsx("div",{children:Se&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:J,stop:z,input:_,handleInputChange:se,handleSubmit:Q=>{ge(),Z(Q),W({force:!0})},isLoading:F,status:$,assistantType:"editor",onFocus:()=>{}})]}),O&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",O.inputTokens," prompt tokens, ",O.outputTokens," ","completion tokens, ",O.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:m,onOpenChange:x,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return j&&n?gt.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:we})}),n):we}function $e(t,a){const[n,r]=S.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return S.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}const Xn="chart-selector-standard-first";function Zn(){const[t,a]=$e(Xn,!0);return{standardFirst:t,updatePreference:a}}const Ss=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ge(t.icon||""),l=t.name.charAt(0).toUpperCase(),i=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):i||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ws=["default","standardPlugin","customPlugin"];function er({selectedChart:t,onChartChange:a}){var E;const[n,r]=S.useState(!1),{data:l}=Qs();Zn();const c=((E=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:E.url)||"";Xe(c);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:h}=s.useEditorActions(),[p,j]=$e("chart-section-active",null),g=S.useMemo(()=>p?[p,...ws.filter(C=>C!==p)]:ws,[p]);function v(C){m(null),d({}),o(C),["custom","map"].includes(C)&&(u(!0),h(void 0)),a(C),r(!1)}function D(C){m(null),d({}),o("custom"),x({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),h(void 0),a("custom"),r(!1)}const k=S.useMemo(()=>s.chartTypes.some(f=>f.id==="bullet")?s.chartTypes:[...s.chartTypes,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}],[]),B=()=>{var f;if(t==="custom"){const b=s.useEditorStore.getState().card;return((f=b==null?void 0:b.customCardPreferences)==null?void 0:f.componentName)||"Custom Visual"}const C=k.find(b=>b.id===t);return(C==null?void 0:C.label)||"Select chart type"},L=()=>{var f,b;if(t==="custom"){const N=s.useEditorStore.getState().card,A=(f=N==null?void 0:N.customCardPreferences)==null?void 0:f.icon,w=(b=N==null?void 0:N.customCardPreferences)==null?void 0:b.componentName;if(A&&w)return e.jsx(sr,{icon:A,componentName:w});if(w){const P=s.getAutoDetectedChartIcon(w);if(P)return P}return e.jsx(Ae,{className:"h-4 w-4"})}const C=k.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L(),e.jsx("span",{children:B()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="default",onCheckedChange:f=>j(f?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map(f=>{const b=f.icon;return e.jsx(s.CommandItem,{value:`${f.label} ${f.id} chart graph visualization`,onSelect:()=>v(f.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:f.label})]})},f.id)})},"default");if(C==="standardPlugin"){const f=l.filter(b=>b.pluginType==="standard");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="standardPlugin",onCheckedChange:b=>j(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.filter(b=>b.componentType==="chart").map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const f=l.filter(b=>b.pluginType==="custom");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="customPlugin",onCheckedChange:b=>j(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const sr=({icon:t,componentName:a})=>{const n=Ge(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},tr=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function ar({selectedChart:t,onChartChange:a,isDropdownExpanded:n,onToggleDropdown:r}){var o;const l=s.useEditorStore(d=>d.card),i=((o=l==null?void 0:l.config)==null?void 0:o.pivotByColumns)&&l.config.pivotByColumns.length>0,c=tr.filter(d=>!(d.requiresPivot&&!i));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[c.map(d=>{const u=d.icon,m=t===d.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(d.id),className:s.cn("h-8 w-8 p-0",m&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:d.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:d.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},d.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":n?"Hide all charts":"Show all charts",children:n?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:n?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}const ls=({dataType:t})=>s.getFieldIconComponent(t);function nr({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=S.useState(t),[l,i]=S.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],o=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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:o,value:l?n:t,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),i(!1)):u.key==="Escape"&&(r(t),i(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function rr({valueAliases:t,onValueAliasesChange:a}){const[n,r]=S.useState(null),[l,i]=S.useState(""),[c,o]=S.useState(""),d=()=>{a({...t,"":""})},u=x=>{const h={...t};delete h[x],a(h)},m=x=>{const h={...t};delete h[x],h[l]=c,a(h),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(([x,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.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:()=>m(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 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:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function lr({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),i=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(et,{idx:i,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(st,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&o()]})}function or({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),i=s.useEditorStore(u=>u.card),c=i==null?void 0:i.dataSource,o=["attribute-values",t.entityName,t.name,a,n],d=s.useQuery({queryKey:o,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:i})};console.log("requestBody",m);const x=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=t.name;return((x==null?void 0:x.records)||[]).map(j=>{const g=j[h]||j[t.alias||h]||j[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function ir({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:i}){var B,L;const c=!!l,[o,d]=S.useState(c?"values":"fields"),[u,m]=S.useState(""),[x,h]=S.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),p=n.filter(E=>{var f;return c?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(b=>b.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),j=E=>{h({...x,field:E}),d("values")},g=()=>{if(x.field&&x.selectedValues.length>0){const E={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let C;if(c){const f=((r==null?void 0:r.conditions)||[]).map(b=>b.id===l.id?E:b);C={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];C={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,E],groups:[]}}i(C),a(!1)}},v=()=>{if(!c||!l)return;const E=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==l.id);if(E.length>0){const C={...r,conditions:E};i(C)}else i(void 0);a(!1)},D=E=>{h({...x,selectedValues:E})},k=()=>{c&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(h({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return S.useEffect(()=>{t&&k()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(L=x.field)==null?void 0:L.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(E=>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:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),o==="fields"&&!c?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:u,onChange:E=>m(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(E),children:[e.jsx(ls,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(cr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:D,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function cr({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,i]=S.useState(""),{values:c,isLoading:o,isFetching:d}=or({field:t,searchQuery:l,limit:500}),u=l?c.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):c,m=h=>{const p=a.includes(h);n(p?a.filter(j=>j!==h):[...a,h])},x=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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:l,onChange:h=>i(h.target.value),className:"pl-10"})]}),o||d?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:a.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(s.Checkbox,{checked:a.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(ns,{className:"text-sm",children:h.label})]},h.id))})]})]})}function dr({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:i=!1,cardType:c}){var is,cs,ds,us;const{attributes:o,listeners:d,setNodeRef:u,transform:m,transition:x,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(K=>K.card),{updateLabel:j,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:D,handleAliasTemplateChange:k,handleValueAliasesChange:B,removeField:L,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:N}=ss(p),[A,w]=S.useState(!1),[P,I]=S.useState(!1),[T,y]=S.useState(null),[M,F]=S.useState(t.dateFormat||"YYYY-MM-DD"),[z,$]=S.useState(t.customFormat||""),[O,G]=S.useState(!!t.customFormat),[R,_]=S.useState(t.granularity||"day"),[J,se]=S.useState(t.aliasTemplate||""),[Z,ae]=S.useState(t.valueAliases||{}),[Y,U]=S.useState((is=t.parameters)==null?void 0:is.filters),te=K=>{K==="custom"?G(!0):(G(!1),F(K),a==="groupBy"&&v(n,K,""))},H=K=>{$(K),a==="groupBy"&&v(n,"custom",K)},re=K=>{var xe;_(K);const ie=(xe=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:xe.value;ie&&!O&&(F(ie),a==="groupBy"&&v(n,ie,"")),a==="groupBy"&&D(n,K)},ue=K=>{se(K),a==="metrics"&&k(n,K)},me=K=>{ae(K),a==="metrics"&&B(n,K)},q=K=>{j(a,n,K)},W=K=>{var oe;if(U(K),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:K}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}I(!1)},de=()=>{L(a,n)},pe={transform:s.CSS.Transform.toString(m),transition:x},fe=s.getDataType(t.dataType),ce=fe==="date",V=c==="kpi",ee=s.getDateFormatOptionsForGranularity(R),X=a!=="pivotBy",je=ce&&a==="groupBy"&&(!V||((cs=p.config)==null?void 0:cs.comparisonType)==="start_vs_end"),ge=!V&&ce&&a==="groupBy",be=c&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(c)&&ce&&a==="groupBy",ve=c==="kpi"&&ce&&a==="groupBy",he=c&&c!=="pivotTable"&&a==="metrics"&&((ds=p.config)==null?void 0:ds.comparisonType)==="target",Ee=a==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.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}`}),we=()=>X?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:q,placeholder:"Display label...",type:"text"})]}):null,Q=()=>je?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:R,onValueChange:re,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,ne=()=>ge?e.jsxs(e.Fragment,{children:[Q(),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:O?"custom":M,onValueChange:te,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:ee.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),O&&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(),H(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,le=()=>{var ie,xe,Ce,Le,ms;const K=be,oe=ve;return!K&&!oe?null:e.jsxs(e.Fragment,{children:[K&&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:((ie=p.config)==null?void 0:ie.comparisonType)||"none",onValueChange:E,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"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),oe&&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:((xe=p.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:C})]})}),((Ce=p.config)==null?void 0:Ce.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:((Le=p.config)==null?void 0:Le.trendlineWindow)||30,onChange:pt=>{const ft=parseInt(pt.target.value)||30;f(ft)},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:((ms=p.config)==null?void 0:ms.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"})]})]})]})]})]})]})},De=()=>{var K,oe;return he?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(Ne,{value:((K=p.config)==null?void 0:K.targetValue)!==void 0&&((oe=p.config)==null?void 0:oe.targetValue)!==null?String(p.config.targetValue):"",onSave:ie=>{!isNaN(Number(ie))&&ie!==null?N(Number(ie)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},mt=()=>Ee?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:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:K=>{g(n,K)},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"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Y==null?void 0:Y.conditions)&&Y.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Y.conditions.map(K=>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:()=>{y(K),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.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(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.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 (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((oe,ie)=>e.jsx("div",{children:String(oe)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var xe;oe.stopPropagation();const ie=Y.conditions.filter(Ce=>Ce.id!==K.id);if(ie.length>0){const Ce={...Y,conditions:ie};W(Ce)}else if(U(void 0),a==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Le=[...((xe=p.config)==null?void 0:xe.metricColumns)||[]];Le[n]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Le})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{y(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(lr,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(nr,{aliasTemplate:J,onAliasTemplateChange:ue}),e.jsx(rr,{valueAliases:Z,onValueAliasesChange:me})]})]}):null,{columns:ht=[]}=s.useColumns(),xt=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:pe,...o,...d,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 ${h?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ls,{dataType:fe}),e.jsx(ns,{className:s.cn("w-[140px] flex-1 text-sm",xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((us=Y==null?void 0:Y.conditions)==null?void 0:us.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:Y.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Y.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),w(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const oe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",oe),l(oe)},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(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),c==="kpi"&&Q(),ne(),le(),De(),mt()]})]}),P&&e.jsx(ir,{open:P,onOpenChange:K=>{I(K),K||y(null)},availableFields:ht,existingFilters:Y,editingCondition:T,onSave:K=>{var oe;if(K)W(K);else if(U(void 0),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}y(null)}})]})}function ur({concept:t}){const a=()=>{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:"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:"Metrics = 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"})]})]})]});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:a()})]})})}function Ve({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:i=!1,activeField:c=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(v=>v.card),x=s.useEditorStore(v=>v.card.type),h=a.length>0,p=S.useMemo(()=>!c||!o?!0:Fe(c,t,x).isValid,[c,o,t,x]),j=(v,D)=>{var B;!((B=m.config)!=null&&B.sortByColumns)||m.config.sortByColumns.findIndex(L=>L.id===v)===-1||u(m.id,v,{direction:D})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&x!=="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:n}),g&&e.jsx(ur,{concept:t})]}),e.jsx("div",{ref:d,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-muted-foreground/30 bg-muted/40":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),children:a.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,{items:a.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((v,D)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(dr,{field:v,zone:t,index:D,sortDirection:B,onSortDirectionChange:L=>j(v.id,L),hasPivotColumns:i,cardType:x})})},v.id)})})})})]})}const Ds={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%
|
|
240
|
-
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 mr(){var h,p,j,g,v,D,k,B,L,E,C;const t=s.useEditorStore(f=>f.card),{setCardPreferences:a}=s.useEditorActions(),n=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=n.length===2&&r.length===0,i=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||i)))return null;const o=((g=(j=t.preferences)==null?void 0:j.kpiVisualOptions)==null?void 0:g.metricComparison)||{},d=f=>{var N;const b={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...o,...f}}};a(b)},u=i||o.enabled,m=((v=t.config)==null?void 0:v.comparisonType)||"none",x=m==="previous_period"||m==="same_period_last_year"||m==="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(At,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),u&&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=o.calculationType||"difference",b=Ds[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:b==null?void 0:b.label}),e.jsx("p",{children:b==null?void 0:b.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:b==null?void 0:b.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",b==null?void 0:b.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>d({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(Ds).map(([f,b])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:b.label},f))})]})]}),e.jsx(rs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||l)&&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"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"right",onValueChange:f=>d({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:o.showArrow!==!1,onCheckedChange:f=>d({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:o.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Pe,{value:((D=o.colorConfig)==null?void 0:D.increase)||"green",onChange:f=>d({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Pe,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:f=>d({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Pe,{value:((B=o.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:f=>d({colorConfig:{...o.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:o.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.increase)??"Increase",onChange:f=>d({conditionalLabels:{...o.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:((E=o.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...o.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:((C=o.conditionalLabels)==null?void 0:C.noChange)??"No change",onChange:f=>d({conditionalLabels:{...o.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:o.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function hr(){var l,i;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((i=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:i.formatOptions)||{},r=c=>{var d;const o={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(o)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(rs,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function xr(){var i;const t=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.type}),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",l=c=>{const o={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:c}};n(o)};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:c=>l(c??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(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."})]})]})]})})]})}function pr({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const i=s.useEditorStore(v=>{var D;return((D=v.card.customCardPreferences)==null?void 0:D.url)&&v.card.type==="custom"}),c=s.useEditorStore(v=>v.card),o=c==null?void 0:c.type,d=t.length>0||n.length>0,u=o!=="kpi"||n.length<=2,m=o!=="kpi",x=o!=="kpi"&&d,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=m&&!h,j=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return 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:[u&&e.jsx(Ve,{zone:"groupBy",fields:t,label:j().label,placeholder:j().placeholder,activeField:l}),p&&e.jsx(Ve,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Ve,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0,activeField:l}),x&&e.jsx(Ve,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!i&&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:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(hr,{}),e.jsx(mr,{}),e.jsx(at,{}),e.jsx(xr,{}),e.jsx(it,{}),o==="bullet"&&e.jsx(ot,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})})]})]})}function fr({onEditJoins:t}){const a=s.useEditorStore(o=>o.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const i=o=>!o||o.length===0?"No conditions":o.map(d=>{var h,p,j,g;const u=`${(h=d.source)==null?void 0:h.entityName}.${(p=d.source)==null?void 0:p.name}`,m=`${(j=d.target)==null?void 0:j.entityName}.${(g=d.target)==null?void 0:g.name}`,x=d.operator||"=";return`${u} ${x} ${m}`}).join(" AND "),c=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?i(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:i(d.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(Xt,{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:"Auto-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:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((o,d)=>{const u=c(o),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.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:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:m?u.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},o.id||d)})})})]})})]}),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 Ts={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function gr({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c}){var f,b;const[o,d]=S.useState(()=>Ts.getItem("chart-selector-expanded")==="true"),[u,m]=S.useState(!1),x=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.actions.updateCardConfig),p=n.length>0||r.length>0||l.length>0,{data:j,autoJoinMetadata:g}=s.useDashboardCardQuery(x),v=((f=x==null?void 0:x.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),D=((b=x==null?void 0:x.dataSource)==null?void 0:b.selectedEntities)||[],k=N=>{h(x.id,{...x==null?void 0:x.config,joinPlan:N}),m(!1)},B=()=>{h(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},E=()=>{m(!0)};S.useEffect(()=>{Ts.setItem("chart-selector-expanded",String(o))},[o]);const C=()=>{d(N=>!N)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(er,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(ar,{selectedChart:t,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:C})})]}),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:p||j}),children:e.jsx(Ze,{})})}),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(fr,{onEditJoins:E}),e.jsx(pr,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(We,{open:u,onOpenChange:m,joinPlan:v,availableDataSources:D,onSave:k,onCancel:L,onRemove:B,children:e.jsx("div",{})})]})}function jr({initialFilters:t,availableFields:a}={}){const[n,r]=S.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:l,isLoading:i}=s.useColumns(),o=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},m=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},x=(E,C)=>{const f=b=>b.id===E?{...b,conditions:b.conditions.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},h=(E,C)=>{const f=b=>b.id===E?{...b,groups:b.groups.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},p=(E,C,f,b)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=A=>A.id===E?{...A,conditions:A.conditions.map(w=>w.id===C?{...w,[f]:b}:w)}:{...A,groups:A.groups.map(N)};r(N(n))},j=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:N.conditions.map(A=>A.id===C?{...A,...f}:A)}:{...N,groups:N.groups.map(b)};r(b(n))},g=(E,C)=>{const f=b=>b.id===E?{...b,logicalOperator:C}:{...b,groups:b.groups.map(f)};r(f(n))},v=(E,C)=>{const f=b=>b.id===E?{...b,negate:C}:{...b,groups:b.groups.map(f)};r(f(n))},D=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:s.arrayMove(N.conditions,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},k=(E,C,f)=>{const b=N=>N.id===E?{...N,groups:s.arrayMove(N.groups,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const C=b=>{let N="";typeof b.field=="object"?N=b.field.entityName?`${b.field.entityName}.${b.field.name}`:b.field.name:N=String(b.field);const A=b.operator;let w=b.value;if(b.field.dataType==="string"&&!["in","not in"].includes(b.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(b.field.dataType==="date"||b.field.dataType==="datetime"||b.field.dataType==="timestamp")if(b.operator==="between"&&Array.isArray(w)&&w.length===2){const P=w[0]?`'${w[0]}'`:"NULL",I=w[1]?`'${w[1]}'`:"NULL";return`${N} BETWEEN ${P} AND ${I}`}else if((b.operator==="in"||b.operator==="not in")&&Array.isArray(w)){const P=w.map(I=>I?`'${I}'`:"NULL").join(", ");return`${N} ${A} (${P})`}else typeof w=="string"||w instanceof Date?w=`'${w}'`:Array.isArray(w)&&w.length>0&&(w=`'${w[0]}'`);else if(["in","not in"].includes(b.operator)){let P=[];Array.isArray(w)?P=w.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof w=="string"?P=w.split(",").map(I=>{const T=I.trim();return b.field.dataType==="string"?`'${T}'`:T}):typeof w=="number"&&(P=[String(w)]),w=`(${P.join(", ")})`}switch(A){case"contains":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${N} LIKE '${w.replace(/'/g,"")}%'`:`${N} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${A} ${w}`}},f=b=>{const N=b.conditions.map(C),A=b.groups.map(T=>f(T)),w=[...N,...A].filter(Boolean);if(w.length===0)return"";const P=w.join(` ${b.logicalOperator} `),I=w.length>1?`(${P})`:P;return b.negate?`NOT ${I}`:I};return f(E)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:u,addGroup:m,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:j,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:D,reorderGroups:k,generateSQLPreview:B,hasAnyFilters:L}}function br({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const vr=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},yr=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Nr({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[i,c]=S.useState(!1),o=S.useMemo(()=>{const d={};return n.forEach(u=>{const m=yr(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(br,{children:[t.entityName,".",t.name]})}):r,e.jsx(yt,{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(o).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,x])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[vr(x[0].entityType),e.jsx("span",{children:x[0].entityName})]}),x.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{a(h),c(!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)===h.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${d}-${m}`))},d))})]})})]})}function os(t){var g;const a=s.useEditorStore(v=>v.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),i=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[c],metricColumns:[o],sortByColumns:[d]},m=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:x,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:a.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:h,error:p}}function Cr({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[i,c]=He.useState(!1),{filterValues:o}=os(t),d=m=>{n(a.filter(x=>x!==m))},u=m=>{a.includes(m)?n(a.filter(x=>x!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const x=o.find(h=>h.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:h=>{h.key==="Enter"&&d(m)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):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:o.map((m,x)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+x))})]})]})})]})})}function Sr({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:i,isPending:c,error:o}=os(t);return c?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..."]}):o?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:i.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function wr({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),i=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=S.useMemo(()=>{if(t){if(a==="between"||a==="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(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="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,a]),o=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:o,timezone:i,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Dr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Tr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Er=["=","!=","isNull","isNotNull"],Ir=["between","isNull","isNotNull"],Ar={"=":"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 ks(t){return Ar[t]||s.titleCase(t)}function Mr(t){switch(t){case"string":return Tr;case"number":return kr;case"boolean":return Er;case"date":return Ir;default:return Dr}}function ct({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:j}=s.useSortable({id:t.id}),{isPending:g,error:v}=os(t.field),D={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:x,style:D,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>c(n,k),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Nr,{value:t.field,onValueChange:k=>{const B=k,L=s.getDataType(B.dataType)==="date";d(n,t.id,{field:B,value:"",operator:L?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?d(n,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?d(n,t.id,{operator:k,value:null}):d(n,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ks(t.operator):""})}),e.jsx(s.SelectContent,{children:Mr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:ks(k)},k))})]}),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"?g?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..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Cr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>d(n,t.id,{value:k}),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:k=>d(n,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Sr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>d(n,t.id,{value:k}),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:k=>d(n,t.id,{value:k==="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(wr,{value:t.value,operator:t.operator,onChange:k=>d(n,t.id,{value:k}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:k=>l(n,t.id,"value",k.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:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Lr({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:x,onAddGroup:h,availableFields:p,renderFilterGroup:j,updateConditionFields:g}){const{attributes:v,listeners:D,setNodeRef:k,transform:B,transition:L,isDragging:E}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(B),transition:L},f=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id){const P=t.conditions.findIndex(T=>T.id===A.id),I=t.conditions.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&u(t.id,P,I)}},b=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id&&n){const P=t.groups.findIndex(T=>T.id===A.id),I=t.groups.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&m(n,P,I)}};return e.jsxs("div",{ref:k,style:C,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...D,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:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:N=>r(t.id,N),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:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,A)=>e.jsx(ct,{condition:N,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:g},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:b,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>j(N,a+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:()=>x(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fr({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:i,availableFields:c,isLoading:o,addCondition:d,addGroup:u,removeCondition:m,removeGroup:x,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:g,reorderConditions:v,reorderGroups:D,generateSQLPreview:k,hasAnyFilters:B,setCurrentFilters:L}=jr({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,f]=S.useState(!1),b=(w,P,I)=>{const T=y=>y.id===w?{...y,conditions:y.conditions.map(M=>M.id===P?{...M,field:I,dataType:I.dataType}:M)}:{...y,groups:y.groups.map(T)};L(T(i))},N=(w,P=0,I)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.conditions.findIndex($=>$.id===y.id),z=w.conditions.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&v(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((T,y)=>e.jsx(ct,{condition:T,index:y,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:p},T.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.groups.findIndex($=>$.id===y.id),z=w.groups.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&D(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(T=>N(T,P+1,w.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:()=>d(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Lr,{group:w,depth:P,parentGroupId:I,onUpdateGroupOperator:j,onUpdateGroupNegate:g,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:D,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:p},w.id),A=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:[o?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..."})]}):N(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:C,onCheckedChange:w=>f(w)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:k(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(B?i:null),children:"Apply Filters"})]})]})}function Pr({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:i,onOpenChange:c}){const o=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&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:u=>{u.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(Fr,{filters:a,availableFields:l,onSave:o,onCancel:()=>c(!1),onClearAll:d})]})]})}function Or({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v,D;const[l,i]=S.useState(null),c=s.useEditorStore(k=>k.card),o=s.useEditorStore(k=>k.actions.updateCardConfig),d=(v=c==null?void 0:c.config)==null?void 0:v.joinPlan,u=(D=c==null?void 0:c.dataSource)==null?void 0:D.semanticDomainId,{data:m}=es(u),x=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=S.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||a.find(B=>B.id===k)?"source":n("groupBy").find(B=>B.id===k)?"groupBy":n("metrics").find(B=>B.id===k)?"metrics":n("pivotBy").find(B=>B.id===k)?"pivotBy":n("sortBy").find(B=>B.id===k)?"sortBy":null,[a,n]),p=S.useCallback(k=>{i(k.active.id)},[]),j=S.useCallback(k=>{var N;const{active:B,over:L}=k;if(!L||!t){i(null);return}const E=B.id,C=L.id,f=h(E),b=h(C)||C;if(b==="sortBy"){if(f==="source"){const A=a.find(P=>P.id===E);if(!A){i(null);return}if(!(n("groupBy").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName)||n("metrics").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName))){i(null);return}}else if(f==="pivotBy"){i(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){i(null);return}}if(f==="source"&&b==="sortBy"){const A=[...a].find(T=>T.id===E);if(!A){i(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(A,w)){i(null);return}const P=Fe(A,"sortBy",c.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),i(null);return}const I=s.getNewField(A,"sortBy",w);i(null),r("sortBy",[...w,I]);return}if(f==="source"&&b!=="source"&&b!=="sortBy"){const A=[...a].find(M=>M.id===E);if(!A){i(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const M=w[0].qualifiedEntityName;if(!M){i(null);return}if(M!==A.qualifiedEntityName&&A.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(A,{joinabilityMap:m.joinabilityMap,selectedFields:w,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),i(null);return}}else{if(!d){s.showJoinRequiredNotification(),i(null);return}if(!s.areEntitiesJoined(M,A.qualifiedEntityName,d)){s.showJoinRequiredNotification(),i(null);return}}}const P=n(b);if(s.fieldAlreadyExists(A,P)){i(null);return}const I=Fe(A,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(A,b,P),y=[...P,T];i(null),r(b,y),b==="metrics"&&t&&Qe(c.type,c.config,o,t,y);return}if(f&&b&&f!=="source"&&b!=="source"&&f!==b){const A=n(f),w=n(b),P=A.find(F=>F.id===E);if(!P){i(null);return}const I=Fe(P,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(P,b,w);if(i(null),b==="sortBy"){s.fieldAlreadyExists(P,w)||r(b,[...w,T]);return}const y=A.filter(F=>F.id!==E),M=[...w,T];r(f,y),r(b,M),b==="metrics"&&t&&Qe(c.type,c.config,o,t,M);return}if(f&&b&&f===b&&f!=="source"){const A=n(f),w=A.findIndex(I=>I.id===E),P=A.findIndex(I=>I.id===C);if(w!==P){const I=s.arrayMove(A,w,P);r(f,I)}}i(null)},[t,a,n,r,h,d,u,m,c.type,o,c.config]),g=l?x.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:p,handleDragEnd:j}}function Br({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(d=>d.card),{config:l}=S.useContext(s.SemaphorContext).tokenProps,i=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(r),o=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>a(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"&&i&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Rr=[{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 Vr(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=S.useState(!1),[l,i]=S.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},o=m=>{const x=m.target.value;i(x),x&&!isNaN(parseInt(x))&&a(t.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:o,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,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:Rr.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function zr({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:i,onSortChange:c,sortState:o,splitViewEnabled:d}){const u=S.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!d||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ye,{}):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(Ye,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:i,isLoading:n||r,onSortChange:c,sortState:o})})})]})}const Gr="semaphor-split-view-enabled";function $r(){return $e(Gr,!0)}function qr({isOpen:t,onClose:a}){const n=Ls(a,{enabled:t}),r=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.url)||""}),l=s.useEditorStore(m=>m.card),i=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.pluginChartType)||""}),c=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=S.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(S.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:i,settings:c})})})]})})}function Ur({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:i,columns:c,columnsLoading:o,columnsError:d}){var Y,U,te;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues),{updateCardConfig:x,setCard:h,updateCardInFrame:p,setShowAIDialog:j}=s.useEditorActions(),g=s.useEditorStore(H=>H.showAIDialog),v=s.useDashboardStore(H=>H.isVisualEditing),[D,k]=S.useState(!1),[B,L]=S.useState(!1),[E,C]=S.useState(null),{config:f}=S.useContext(s.SemaphorContext).tokenProps,b=(f==null?void 0:f.showInfoTab)!==!1,[N,A]=$r(),w=s.useEditorStore(H=>{var re;return((re=H.card.customCardPreferences)==null?void 0:re.url)&&H.card.type==="custom"}),{data:P,errorMessage:I,isLoading:T,isFetching:y,errorSql:M,pagination:F,refetch:z,comparisonMetadata:$}=s.useDashboardCardQuery(i),O=S.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[G,R]=S.useState(!1);S.useEffect(()=>{y||R(!1)},[y]);const _=()=>{const H=!N;H&&t==="table"&&a("chart"),A(H)},J=(H,re)=>{const ue={...i,paginationConfig:{page:H+1,pageSize:re}};h(ue),p(ue)};function se(){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(u.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(m||{},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(i.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",c.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":d?"Error loading columns":JSON.stringify(c.slice(0,5),null,2)})]})]})]})}const Z=H=>{if(!u.config)return;const re=s.sortStateToSortByColumns(H,u.config.metricColumns,u.config.groupByColumns);x(u.id,{...u.config,sortByColumns:re})},ae=S.useMemo(()=>{var H;return s.sortByColumnsToSortState((H=u.config)==null?void 0:H.sortByColumns)},[(Y=u.config)==null?void 0:Y.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:[n&&se(),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"&&g&&e.jsx(Ws,{variant:"outline"}),e.jsx(Br,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:i.id,cardFilters:(U=i.config)==null?void 0:U.filters,cardFilterCount:s.getFilterCount(((te=i.config)==null?void 0:te.filters)||null),onFiltersClick:l}),$&&e.jsx(s.ComparisonMetadataBadge,{metadata:$,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Vr,{})}),g&&e.jsx(Ze,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:T||y,onClick:()=>{R(!0),z()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:_,children:N?e.jsx(It,{className:"size-4"}):e.jsx(_t,{className:"size-4"})}),t==="chart"&&e.jsx(Ys,{}),!g&&e.jsx(s.IconButton,{onClick:()=>j(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!D&&w&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),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":N&&!["table","pivotTable","aggregateTable"].includes(i.type)}),children:e.jsx(zr,{card:i,queryData:P,isLoading:T,isFetching:y,pagination:F,onPaginationChange:J,onSortChange:Z,sortState:ae,splitViewEnabled:N})}),t==="table"&&(P==null?void 0:P.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:i,data:O,paginationMetadata:F,onPaginationChange:J,isLoading:T||y,onSortChange:Z,sortState:ae})}),t==="info"&&b&&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:I?e.jsx(as,{error:I,errorSql:M,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:i.dataSource,dashboardFilters:m,errorMessage:I,errorSql:M,generatedSql:P==null?void 0:P.sql});C(H),L(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(M||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):e.jsx(Ks,{sql:P==null?void 0:P.sql,error:I,errorSql:M})})})]}),e.jsx(qr,{isOpen:D,onClose:()=>k(!1)}),E&&e.jsx(s.FeedbackDialog,{open:B,onOpenChange:L,feedbackData:E})]})]})}function Kr({activeField:t}){const[a,n]=S.useState(!0);return S.useEffect(()=>{t&&n(!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 ${a?"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(ls,{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 _r=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hr(){var $,O;const[t,a]=S.useState("chart"),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),x=s.useEditorStore(G=>G.card.type);S.useEffect(()=>_r(),[]);const h=G=>{m(G)},p=s.useEditorStore(G=>G.frame),j=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:D,setActiveCard:k,updateFilters:B}=s.useEditorActions(),{columns:L=[],isLoading:E,error:C}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),b=j,{getFieldsForContainer:N,setFieldsForContainer:A}=ss(b),{activeField:w,handleDragStart:P,handleDragEnd:I}=Or({activeCardId:p.activeCardId,sourceFields:L,getFieldsForContainer:N,setFieldsForContainer:A}),T=(G,R)=>{R&&B(G,R)},y=G=>{var R;D(G,{config:{...(R=p.cards.find(_=>_.id===G))==null?void 0:R.config,filters:void 0}})},M=L,F=G=>{if(!G)return 0;let R=G.conditions.length;return G.groups.forEach(_=>{R+=F(_)}),R},z=F((($=b==null?void 0:b.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:P,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Us,{isVisible:c,onToggleVisibility:()=>o(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(gr,{selectedChart:x,onChartChange:h,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:w}),e.jsx(Ur,{selectedChart:x,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>i(!0),filterCount:z,activeCard:b,dataSourceState:j.dataSource||s.EMPTY_DATA_SOURCE,columns:L,columnsLoading:E,columnsError:C,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:g,setActiveCard:k})]}),!c&&u&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),b&&e.jsx(Pr,{cardId:b.id,filters:((O=b.config)==null?void 0:O.filters)||null,onFiltersChange:T,onClearFilters:y,availableFields:M,isOpen:l,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Kr,{activeField:w||null})})]})}function Jr({authToken:t,onSave:a,onClose:n}){const r=S.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),i=s.useEditorStore(C=>C.isDevMode),c=s.useAssistantLayoutStore(C=>C.setFullscreen),o=s.useAssistantLayoutStore(C=>C.setPanelOpen),d=s.useAssistantLayoutStore(C=>C.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),h=m==="editor",p=S.useCallback(C=>{d("editor",C)},[d]),{setAuthToken:j}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:D}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();S.useEffect(()=>{a&&v(a),n&&D(n)},[a,v,n,D]),S.useEffect(()=>{t&&t.accessToken&&j(t)},[t,j]),S.useEffect(()=>{var C,f;l?((C=r.current)==null||C.resize(40),o("editor",!0),k("editor")):((f=r.current)==null||f.resize(0),o("editor",!1),m==="editor"&&c(null),k(null))},[l,o,k,c,m]);function B(C){C<1?(g(!1),o("editor",!1),m==="editor"&&c(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function L(){return e.jsxs(e.Fragment,{children:[e.jsx(Us,{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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Qn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function E(){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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:L()}):E()})}function Qr(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Jr,{onSave:l,onClose:i})})}function Wr(){qs();const t=s.useDashboardStore(d=>d.selectedSheetId),a=s.useDashboardStore(d=>d.selectedFrameId),n=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:i}=s.useEditorActions(),c=s.useEditorStore(d=>d.card.dataSource);return S.useEffect(()=>{var u,m;let d=r();if(!d){const x=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===t),h=(m=x==null?void 0:x.frames)==null?void 0:m[0];h&&(l(h.id),d=h)}if(d){const x=d.cards.find(h=>h.id===d.activeCardId);x&&i(x)}},[r,t,a,n,l,i]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Yr(){const t=s.useDashboardStore(n=>n.actions.setShowFilters),{hasEntities:a}=Wr();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!a&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),a&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx($s,{context:"filter"})})})})]})}function Xr(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zr(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Yr,{})})]})}function el(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4 py-2",children:[e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"space-y-3 pt-2",children:[...Array(3)].map((t,a)=>e.jsxs("div",{className:"flex gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-2/3 rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},a))})]})})}const sl=t=>{const a=s.useDashboardStore(l=>l.isVisualEditing),n=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(a&&n&&(r==null?void 0:r.visualId)===t)};function tl({visual:t,isDeleting:a,isDuplicating:n,onAddVisual:r,onOpenVisual:l,onEditDetails:i,onDeleteClick:c,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var E,C,f,b;const{selectVisual:m}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),h=sl(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),j=S.useRef(null),[g,v]=S.useState(!1),[D,k]=S.useState(!1);S.useEffect(()=>{n?(v(!0),k(!0)):D&&(v(!1),k(!1))},[n,D]),S.useEffect(()=>{h&&j.current&&j.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const B=()=>e.jsx(s.Grid3x3,{className:"h-4 w-4"}),L=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:j,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h?"border-purple-500":x&&"border-primary"),onClick:L,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:B()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(E=t.description)!=null&&E.trim()?t.description:"No description"}),e.jsxs("div",{className:s.cn("invisible flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",x&&"visible"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),i==null||i(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:v,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),l==null||l(t)},children:[e.jsx(Et,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),o(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),i==null||i(t)},children:[e.jsx(s.PenLine,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((f=t.ownership.createdBy)==null?void 0:f.type)==="organization"&&p)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((b=t.ownership.createdBy)==null?void 0:b.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})]})]})]})},t.id)}function al({open:t,onOpenChange:a,onSubmit:n,isCreating:r}){const[l,i]=S.useState(""),[c,o]=S.useState("");S.useEffect(()=>{t||(i(""),o(""))},[t]);const d=()=>{l.trim()&&n({title:l,description:c})},u=m=>{a(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>i(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:m=>o(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function nl(){const[t,a]=S.useState(""),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(null),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(null),[j,g]=S.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:D,handleAddLibraryVisual:k}=Te(),{resources:B,isLoading:L,isError:E,createResource:C,updateResource:f,deleteResource:b,duplicateResource:N,isCreating:A,isDeleting:w}=s.useVisualManagement(()=>{u(!1),x(null)},U=>{r(!1),U&&(v(U),D(U))});s.useCurrentUserInfo();const P=B.filter(U=>{var te,H;return((te=U==null?void 0:U.title)==null?void 0:te.toLowerCase().includes(t.toLowerCase()))||((H=U==null?void 0:U.description)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))}),I=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),T=U=>{C({title:U.title,description:U.description,isPrivate:!1})},y=U=>{x(U),u(!0)},M=()=>{m&&b(m.id)},{startUpdating:F,stopUpdating:z,isUpdating:$}=s.useResourceUpdateState(),O=(U,te,H)=>{var q;const re=Object.fromEntries(Object.entries(te).filter(([,W])=>W!==void 0));if(Object.keys(re).length===0){(q=H==null?void 0:H.onSuccess)==null||q.call(H);return}const ue=Object.keys(re),me=ue.length===1?ue[0]:void 0;F(U,me),f({resourceId:U,data:re},{onSuccess:()=>{var W;z(U,me),(W=H==null?void 0:H.onSuccess)==null||W.call(H)},onError:()=>{var W;z(U,me),(W=H==null?void 0:H.onError)==null||W.call(H)}})},G=U=>{p(U),N(U,{onSettled:()=>p(null)})},R=U=>{D(U)},_=U=>{k(U)},J=U=>{const te=B.find(H=>H.id===U);te&&f({resourceId:U,data:{isPrivate:!te.isPrivate}})},se=U=>{o(U),i(!0)},Z=U=>{g(U)},ae=()=>{g(null)},Y=({title:U,description:te})=>{if(!j)return;const H={};U!==j.title&&(H.title=U),(j.description||"")!==te&&(H.description=te),O(j.id,H,{onSuccess:()=>{g(null)}})};return L?e.jsx(dt,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[B&&B.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>a(U.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:P.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.Grid3x3,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):P.map(U=>e.jsx(tl,{visual:U,onAddVisual:_,onOpenVisual:R,onEditDetails:Z,onDeleteClick:y,onDuplicateVisual:G,onTogglePrivacy:J,onShareVisual:se,isDeleting:w,isDuplicating:h===U.id,formatDate:I},U.id))})}),l&&c&&e.jsx(s.ShareDialog,{resource:c,resourceType:s.ResourceType.VISUAL,onClose:()=>{i(!1),o(null)}}),j&&e.jsx(s.ResourceEditDialog,{open:!!j,resourceLabel:"Visual",initialTitle:j.title||"",initialDescription:j.description||"",onClose:ae,onSave:Y,isSaving:$(j.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:U=>{!U&&w||(u(U),U||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:w,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:w,children:[w?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),w?"Deleting...":"Delete"]})]})]})}),e.jsx(al,{open:n,onOpenChange:r,onSubmit:T,isCreating:A}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function rl({dashboard:t,isDeleting:a,isDuplicating:n,onLoadDashboard:r,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,B;const{selectDashboard:m}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),{userContext:h,isLoading:p}=s.useCurrentUserInfo(),j=((k=h==null?void 0:h.permissions)==null?void 0:k.canEdit)??!1,g=p||!j,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),D=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x&&"border-primary"),onClick:D,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:v()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(B=t.description)!=null&&B.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:a,isDuplicating:n,shouldHideActions:g,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function ll({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function ol(t){var ce;const{onLoadDashboard:a,onEditDashboard:n,onDashboardItemClick:r}=t,[l,i]=S.useState(""),[c,o]=S.useState(!1),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(!1),[j,g]=S.useState(null),[v,D]=S.useState(null),[k,B]=S.useState(null),L=s.useManagementStore(V=>V.lastSelectedDashboard),E=s.useManagementStore(V=>V.selectedDashboard),C=s.useManagementStore(V=>V.actions.selectDashboard),f=s.useManagementStore(V=>V.actions.clearSelectedDashboard),{tokenProps:b,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:A}=s.useDashboardCreation({onDashboardSelect:r}),{resources:w,isLoading:P,isError:I,createResource:T,updateResource:y,deleteResource:M,duplicateResource:F,isCreating:z,isDeleting:$,refetch:O}=s.useDashboardManagement(()=>{p(!1);const V=j==null?void 0:j.id;g(null),(E==null?void 0:E.id)===V&&(!(b!=null&&b.dashboard_id)&&!N?f():L&&L.id!==V&&C(L))},V=>{o(!1),A(V,O)}),{currentUser:G,userContext:R}=s.useCurrentUserInfo(),_=((ce=R==null?void 0:R.permissions)==null?void 0:ce.canCreateDashboard)??!1,J=w.filter(V=>{var ee,X;return((ee=V==null?void 0:V.title)==null?void 0:ee.toLowerCase().includes(l.toLowerCase()))||((X=V==null?void 0:V.description)==null?void 0:X.toLowerCase().includes(l.toLowerCase()))}),se=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Z=V=>{T({title:V.title,description:V.description,isPrivate:!1})},ae=V=>{a==null||a(V)},Y=V=>{g(V),p(!0)},U=()=>{j&&M(j.id)},te=V=>{D(V),F(V,{onSettled:()=>D(null)})},{startUpdating:H,stopUpdating:re,isUpdating:ue}=s.useResourceUpdateState(),me=(V,ee,X)=>{var ve;const je=Object.fromEntries(Object.entries(ee).filter(([,he])=>he!==void 0));if(Object.keys(je).length===0){(ve=X==null?void 0:X.onSuccess)==null||ve.call(X);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;H(V,be),y({resourceId:V,data:je},{onSuccess:()=>{var he;re(V,be),(he=X==null?void 0:X.onSuccess)==null||he.call(X)},onError:()=>{var he;re(V,be),(he=X==null?void 0:X.onError)==null||he.call(X)}})},q=V=>{const ee=w.find(X=>X.id===V);ee&&y({resourceId:V,data:{isPrivate:!ee.isPrivate}})},W=V=>{x(V),G==null||G.type,u(!0)},de=V=>{n==null||n(V.id),B(V)},pe=()=>{B(null)},fe=({title:V,description:ee})=>{if(!k)return;const X={};V!==k.title&&(X.title=V),(k.description||"")!==ee&&(X.description=ee),me(k.id,X,{onSuccess:()=>{B(null)}})};return P?e.jsx(dt,{}):I?e.jsx(ll,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[w&&w.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:V=>i(V.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:J.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":_?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),_&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):J.map(V=>e.jsx(rl,{dashboard:V,isDeleting:$,isDuplicating:v===V.id,onLoadDashboard:ae,onEditDetails:de,onDeleteClick:Y,onDuplicateDashboard:te,onTogglePrivacy:q,onShareDashboard:W,formatDate:se,onDashboardItemClick:r},V.id))})}),d&&m&&e.jsx(s.ShareDialog,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),x(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:V=>{!V&&$||(p(V),V||g(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:$,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:$,children:[$?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),$?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:pe,onSave:fe,isSaving:ue(k.id)}),e.jsx(s.CreateDashboardDialog,{open:c,onOpenChange:o,onSubmit:Z,isCreating:z}),_&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function ut({isOpen:t,onClose:a,className:n,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(C=>C.dashboard);const i=s.useDashboardStore(C=>C.isDashboardEditing),{setDashboard:c,addSheet:o}=s.useDashboardStore(C=>C.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:m}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&m.canAccessVisuals&&i,p="dashboards",[j,g]=$e("resource-management-active-tab",p),v=h?j:"dashboards",D=l==="overlay",k=Ls(a,{enabled:t&&D}),B=s.cn("flex h-full flex-col border-r bg-background",D?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",n),L=C=>{},E=C=>{console.log("Editing dashboard:",C)};return e.jsx(s.TooltipProvider,{children:(!D||t)&&e.jsxs("div",{ref:k,className:B,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:u&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:u.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email}),u.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(u.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",u.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:u.name})})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Close Sidebar",children:e.jsx(qt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:h?g:void 0,className:"flex h-9 grow flex-col",children:[h&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(ol,{onLoadDashboard:L,onEditDashboard:E,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(nl,{})})]})})]})})}function il({showControls:t=!1,showFooter:a=!0,...n}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),i=20,c=20,o=30,d=r,u=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(i),m.current.resize(100-i)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:x}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:x,children:[e.jsx(el,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Aa,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?i:0,minSize:d?c:0,maxSize:d?o:0,children:e.jsx(ut,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-i:100,minSize:d?40:100,children:e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(Qr,{}),e.jsx(Zr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Rs;exports.DashboardPlus=il;exports.ResourceManagementPanel=ut;exports.ScheduleDashboard=Ps;exports.VisualEditingControls=Bs;exports.cleanCard=Fs;exports.getDashbaordStateWithoutData=ze;
|
|
239
|
+
`),w=new Blob([A],{type:"text/csv"}),P=URL.createObjectURL(w),I=document.createElement("a");I.href=P,I.download=`${a.title}.csv`,I.click()}function C(){const N=`Can you get the documentation for ${a.type} chart?`;u(N)}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:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(Ws,{}),l&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:C,children:e.jsx(vt,{className:"size-4"})}),!["table","custom"].includes(a.type)&&l&&e.jsx(an,{})]}),!r&&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:E,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:L,children:e.jsx(kt,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(h==null?void 0:h.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:p||j,onClick:()=>{B(!0),v()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":k})})}),e.jsx(Ys,{})]}),a.type==="table"&&a.sql&&n&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((b=(f=a.preferences)==null?void 0:f.tablePrefs)==null?void 0:b.enableDevModePagination)??!1,onCheckedChange:N=>{var A;x({...a.preferences,tablePrefs:{...(A=a.preferences)==null?void 0:A.tablePrefs,enableDevModePagination:N}}),v()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),n&&e.jsx(xn,{})]}),r?e.jsx(Ye,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&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:i&&e.jsx(hn,{})}),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":i}),children:[(h==null?void 0:h.records)&&(h==null?void 0:h.records.length)>0&&e.jsx(s.TableVisual,{card:a,data:D}),g&&e.jsx(cn,{error:g})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function hn(){const t=s.useEditorStore(n=>n.pythonStdOut);if(!t)return null;const a=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:a}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function xn(){const t=s.useEditorStore(n=>n.isShowingVisual),a=s.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>a(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ye({defaultValue:t,label:a,options:n,value:r,onValueChange:l,className:i,icon:c,showPlaceholderLabel:o=!0}){return e.jsxs(s.Select,{defaultValue:t,value:r,onValueChange:l,children:[e.jsx(s.SelectTrigger,{className:s.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),o&&e.jsx(s.SelectValue,{placeholder:a})]})}),e.jsx(s.SelectContent,{children:e.jsxs(s.SelectGroup,{children:[e.jsx(s.SelectLabel,{children:a}),n.map(d=>e.jsx(s.SelectItem,{value:d.value,children:d.label},d.value))]})})]})}function pn(){var g,v;const t=s.useEditorStore(D=>D.card.customCardPreferences),{data:a}=Js(),n=(a==null?void 0:a.plugins)||[],r=s.useEditorStore(D=>D.card),l=s.useEditorStore(D=>D.frame),i=(t==null?void 0:t.visualType)||"single",{setCustomCardPreferences:c}=s.useEditorActions(),{components:o,manifest:d}=s.useCustomVisual((t==null?void 0:t.url)||""),u=(g=d==null?void 0:d.visuals)==null?void 0:g.find(D=>D.name===(t==null?void 0:t.componentName));function m(D,k){if(!t)return;const L={...(t==null?void 0:t.dataInputCardIds)||{},[D]:{cardId:k,hookRef:null}};c({...t,dataInputCardIds:L})}function x(D){var B,L;const k=(B=l==null?void 0:l.cards)==null?void 0:B.filter(E=>{var C;return((C=E==null?void 0:E.customCardPreferences)==null?void 0:C.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(L=D==null?void 0:D.dataInputs)==null?void 0:L.map((E,C)=>{var f,b;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(ye,{className:"col-span-6 h-8 w-full justify-between",label:"",options:k||[],value:((b=(f=t==null?void 0:t.dataInputCardIds)==null?void 0:f[C])==null?void 0:b.cardId)||"",onValueChange:N=>m(C,N)})]},C+Math.random())})})}function h(D,k,B=[],L=""){var E,C;return t?D==="input"?e.jsx(s.Input,{className:`h-8 w-full ${s.removeRing}`,value:((E=t==null?void 0:t.settings)==null?void 0:E[k])||L,onChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f.target.value}})}},k):D==="select"?e.jsx(ye,{className:"h-8 w-full",label:"",options:B,value:((C=t==null?void 0:t.settings)==null?void 0:C[k])||L,onValueChange:f=>{c({...t,settings:{...t==null?void 0:t.settings,[k]:f}})}}):null:null}function p(D){const k=Object.entries((D==null?void 0:D.settings)||{});return e.jsx("div",{className:"space-y-3",children:k.map(([B,L])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:L.title}),h(L.ui,B,L.options,L.defaultValue)]},B))})}function j(D){t&&c({...t,visualType:D,componentName:""})}return e.jsxs(s.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",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:[e.jsx(ye,{icon:e.jsx(bt,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(t==null?void 0:t.url)||"",onValueChange:D=>c({...t||{url:"",componentName:""},url:D})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&e.jsx(s.Tabs,{value:i,onValueChange:j,children:e.jsxs(s.TabsList,{className:"h-9 w-full",children:[e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(s.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((t==null?void 0:t.type)==="component"||(t==null?void 0:t.type)===void 0)&&t&&e.jsx(e.Fragment,{children:o&&e.jsx(ye,{icon:e.jsx(St,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(o==null?void 0:o.filter(D=>D.type===i).map(D=>({value:D.name,label:D.name})))||[],value:t.componentName,onValueChange:D=>{console.log("changing value",D),c({...t,componentName:D})}})})]})})]}),((v=r==null?void 0:r.customCardPreferences)==null?void 0:v.componentName)&&e.jsxs(s.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{children:[u&&u.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:x(u)})]}),u&&u.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:p(u)})})]})]})]})}function ke(){const[t,a]=S.useState([]),n=s.useEditorStore(u=>u.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:l}=s.useEditorStore(u=>u.actions),i=s.useEditorStore(u=>u.queryResultColumns);s.useEditorStore(u=>{var m;return(m=u.card.preferences)==null?void 0:m.filterOnClickColumnIndex}),S.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(u,m){var x,h;m?n!=null&&n.onClickFilter&&((x=n==null?void 0:n.onClickFilter)==null?void 0:x.length)>0?l({...n,onClickFilter:[...n.onClickFilter,{columnIndex:u,expression:""}]}):l({...n,onClickFilter:[{columnIndex:u,expression:""}]}):(l({...n,onClickFilter:(h=n==null?void 0:n.onClickFilter)==null?void 0:h.filter(p=>p.columnIndex!==u)}),a(p=>{const j=[...p];return j[u]=!1,j}))}function o(u,m){var h;const x=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.map(p=>p.columnIndex===u?{...p,expression:m.target.value}:p);l({...n,onClickFilter:x})}function d(u){var m,x,h,p;if(t!=null&&t[u]||(x=(m=n==null?void 0:n.onClickFilter)==null?void 0:m.find(j=>j.columnIndex===u))!=null&&x.expression)return e.jsx(s.Input,{value:(p=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(j=>j.columnIndex===u))==null?void 0:p.expression,onChange:j=>o(u,j),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsx("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:i==null?void 0:i.map((u,m)=>{var x,h;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(s.Checkbox,{checked:!!((x=n==null?void 0:n.onClickFilter)!=null&&x.find(p=>p.columnIndex===m)),onCheckedChange:p=>c(m,p)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:u}),e.jsx("div",{className:"flex items-center gap-2",children:((h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(p=>p.columnIndex===m))&&e.jsx(s.Pencil,{onClick:()=>{a(p=>{const j=[...p];return j[m]=!p[m],j})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),d(m)]})},u)})})}function fn({idx:t}){var o;const a=s.useEditorStore(d=>{var u;return(u=d.card)==null?void 0:u.preferences}),n=s.useEditorStore(d=>{var u;return(u=d.card.preferences)==null?void 0:u.datasetOptions}),r=s.useEditorStore(d=>d.actions.setCardPreferences),l=(o=a==null?void 0:a.chartOptions)==null?void 0:o.indexAxis,i=n==null?void 0:n.find(d=>d.idx===t);function c(d,u){(d==="end"||d==="start")&&s.getContrastColor(s.getCanvasBackgroundColor());const m={display:d!=="none",align:d,anchor:d,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:u,datalabels:m}]});else{const x={...i};x.datalabels=m;const h=n==null?void 0:n.map(p=>p.idx===u?x:p);r({...a,datasetOptions:h})}}return e.jsxs(s.Popover,{children:[e.jsx(s.PopoverTrigger,{children:e.jsx(Ms,{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:()=>c("none",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(s.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Bt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("center",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Vt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})}),e.jsx("button",{onClick:()=>c("end",t),className:"h-7 p-1 text-xs font-normal",children:e.jsx(Rt,{className:s.cn("h-4 w-4",{"rotate-90":l==="y"})})})]})})]})}function gn(){const t=s.useEditorStore(i=>i.card),{data:a}=s.useDashboardCardQuery(t),{keys:n}=s.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!s.METADATA_KEYS.includes(i));let l=r;if(["stackedBar","stackedLine"].includes(t.type)){const i=s.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=s.getKeys(i);l=c.slice(1)}return{transformedMetricKeys:l,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ns({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:s.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:t})}),e.jsx(s.TooltipContent,{children:t})]})})}function Xs(){const t=s.useEditorStore(d=>d.card),a=s.useEditorStore(d=>{var u,m,x;return(x=(m=(u=d==null?void 0:d.card)==null?void 0:u.preferences)==null?void 0:m.chartOptions)==null?void 0:x.indexAxis}),{data:n}=s.useDashboardCardQuery(t),r=a==="y"?"Metric":"Dimension",l=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:o}=gn();return o.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(d=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:d,children:Zs(d)},d))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:l}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((d,u)=>e.jsx(et,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:d,idx:u},d))})]})]})}function Zs(t,a=30){return t.length>a?t.slice(0,a)+"...":t}function et({col:t,idx:a,className:n,iconClassName:r,children:l}){const i=s.useEditorStore(m=>{var x;return(x=m.card)==null?void 0:x.preferences}),c=s.useEditorStore(m=>{var x,h;return(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.datasetOptions}),o=c==null?void 0:c.find(m=>m.idx===a),{setCardPreferences:d}=s.useEditorStore(m=>m.actions);function u(m){if(!o)d({...i,datasetOptions:[...c||[],{idx:a,type:m==="area"?"line":m,fill:m==="area"?"origin":""}]});else{const x={...o};x.type=m==="area"?"line":m,x.fill=m==="area"?"origin":"";const h=c==null?void 0:c.map(p=>p.idx===a?x:p);d({...i,datasetOptions:h})}}return e.jsxs("div",{className:s.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[l||e.jsx(ns,{className:"max-w-[100px]",title:t,children:Zs(t)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.ChartColumnIncreasing,{onClick:()=>u("bar"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartLine,{onClick:()=>u("line"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(s.ChartArea,{onClick:()=>u("area"),className:s.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(fn,{idx:a})]})]})}function Me(){const t=s.useDashboardStore(o=>o.dashboard.filters),a=s.useEditorStore(o=>o.frame),{setFrame:n}=s.useEditorActions(),{columns:r}=s.useEditorAside(),{assignFilter:l}=Gs();function i(o){const d=l(o,"frame");n({...a,filterId:d})}const c=t==null?void 0:t.find(o=>o.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(s.Label,{children:"Card Filter"}),e.jsx(jn,{onSelect:i,columns:r}),c&&e.jsx(s.FilterHeader,{filter:c})]})}function jn({columns:t,onSelect:a}){var c;const[n,r]=He.useState(!1),[l,i]=He.useState("");return e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[l?(c=t.find(o=>o.column_name===l))==null?void 0:c.column_name:"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 framework found."}),e.jsx(s.CommandGroup,{children:t==null?void 0:t.map(o=>e.jsxs(s.CommandItem,{value:o.column_name,onSelect:d=>{const u=d===l?"":d;i(u),r(!1),u&&a(o)},children:[o.column_name,e.jsx(s.CheckIcon,{className:s.cn("ml-auto h-4 w-4",l===o.column_name?"opacity-100":"opacity-0")})]},o.column_name))})]})]})})]})}function bn({cardType:t}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(Xs,{})})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function vn({cardType:t}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} Chart`}),e.jsx(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(t)})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function st(){const t=s.useEditorStore(o=>o.card.type),a=s.useEditorStore(o=>o.isDevMode),n=s.useEditorStore(o=>o.card.preferences),{setCardPreferences:r}=s.useEditorStore(o=>o.actions);function l(o){var m;const d={datalabels:{display:o!=="none",align:o,anchor:o,clamp:!0}},u={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(m=n==null?void 0:n.chartOptions)==null?void 0:m.plugins,...d}}};r(u)}function i(){var o,d,u;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(s.Select,{value:((u=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,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 c(){var o,d,u;return e.jsx("div",{children:e.jsxs(s.Select,{value:((u=(d=(o=n==null?void 0:n.chartOptions)==null?void 0:o.plugins)==null?void 0:d.datalabels)==null?void 0:u.anchor)||"none",onValueChange:l,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:a?i():c()})}const yn={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},Nn={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function Cn(){const t=s.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(s.Accordion,{className:" ",type:"single",collapsible:!0,children:Sn(t)}),!["kpi"].includes(t)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(st,{}),e.jsx(ke,{}),e.jsx(Me,{})]})]})}function Sn(t){if(["line","bar"].includes(t))return e.jsxs(e.Fragment,{children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(yn,null,2)})]})]}),e.jsxs(s.AccordionItem,{value:"item-3",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(Nn,null,2)})]})]})]});if(t==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(t==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:t})," chart query?"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(t))return e.jsx(e.Fragment,{children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:t==="polarArea"?"Polar":t.charAt(0).toUpperCase()+t.slice(1)})," ","chart query"]})}),e.jsxs(s.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function wn({colorRanges:t,setColorRanges:a}){const n={start:-1/0,end:100,color:""};function r(c,o,d){const u=[...t];u[c]={...u[c],[o]:d},a(u)}function l(c){const o=[...t];o.splice(c,1),a(o)}function i(){a([...t,n])}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:i,variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.Plus,{className:"size-3"})})]}),t.map((c,o)=>e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx(s.Input,{onChange:d=>r(o,"start",d.target.value),value:c.start,className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx("span",{children:"-"}),e.jsx(s.Input,{value:c.end,onChange:d=>r(o,"end",d.target.value),className:s.cn(`h-7 ${s.removeRing}`)}),e.jsx(s.Input,{onChange:d=>r(o,"color",d.target.value),value:c.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:()=>l(o),variant:"secondary",className:"h-5 p-1 text-muted-foreground",children:e.jsx(s.X,{className:"size-3"})})]},o))]})}function Dn(){var m,x,h,p,j;const t=s.useEditorStore(g=>g.card.preferences),a=s.useEditorStore(g=>g.actions.setCardPreferences),n=s.useEditorStore(g=>g.card),r=s.hasValidCardConfig(n.config),l=s.useEditorStore(g=>g.actions.setNumberFormat);s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.decimalPlaces});const i=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.locale}),c=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.currency});s.useEditorStore(g=>g.actions.setFilterOnClickField);const o=s.useEditorStore(g=>{var v,D;return(D=(v=g.card.preferences)==null?void 0:v.formatNumber)==null?void 0:D.colorRanges})||[],d=s.useEditorStore(g=>g.actions.setColorRanges),u=[...new Set(s.LOCALE_CURRENCY_PAIRS.map(g=>g.currency))];return e.jsxs("div",{children:[!r&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(s.Checkbox,{checked:!!((m=t==null?void 0:t.formatNumber)!=null&&m.enabled),onCheckedChange:g=>{a({...t,formatNumber:{...t==null?void 0:t.formatNumber,enabled:g}})}}),e.jsx(s.Label,{children:"Format Number"})]}),(((x=t==null?void 0:t.formatNumber)==null?void 0:x.enabled)===!0||r)&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Locale"}),e.jsxs(s.Select,{value:i||"none",onValueChange:g=>{var v,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.currency)||"",g,((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g.locale,children:g.locale},g.locale))]})})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Currency"}),e.jsxs(s.Select,{value:c||"none",onValueChange:g=>{var v,D,k;console.log("currency",g),l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,g==="none"?"":g,((D=t==null?void 0:t.formatNumber)==null?void 0:D.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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"),u.map(g=>e.jsx(s.SelectItem,{value:g,children:g},g))]})})]})]})]}),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:((p=(h=t==null?void 0:t.formatNumber)==null?void 0:h.decimalPlaces)==null?void 0:p.toString())||"0",onValueChange:g=>{var v,D,k;return l(Number(g),((v=t==null?void 0:t.formatNumber)==null?void 0:v.currency)||"",((D=t==null?void 0:t.formatNumber)==null?void 0:D.locale)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.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(g=>e.jsx(s.SelectItem,{value:g,children:g},g))})]})]}),e.jsxs("div",{className:"w-full space-y-1",children:[e.jsx(s.Label,{children:"Suffix"}),e.jsx(s.Input,{value:((j=t==null?void 0:t.formatNumber)==null?void 0:j.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:g=>{var v,D,k;return l(((v=t==null?void 0:t.formatNumber)==null?void 0:v.decimalPlaces)||0,((D=t==null?void 0:t.formatNumber)==null?void 0:D.currency)||"",((k=t==null?void 0:t.formatNumber)==null?void 0:k.locale)||"",g.target.value)}})]})]})]})}),e.jsx(s.Separator,{className:"my-3"}),e.jsx(wn,{colorRanges:o,setColorRanges:d})]})]})}function Tn(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{type:"single",collapsible:!0,children:e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(s.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(Dn,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function _e({children:t,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,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:a}),e.jsx(s.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:t})]})}const kn=[{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"}],En=["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"],In=En.map(t=>({label:t,value:t}));function An(){var d,u,m,x,h,p,j,g,v,D,k,B,L,E,C,f,b,N;const t=s.useEditorStore(A=>A.card),a=(u=(d=t==null?void 0:t.preferences)==null?void 0:d.mapVisualOptions)==null?void 0:u.topoJsonUrl,[n,r]=S.useState(((x=(m=t==null?void 0:t.preferences)==null?void 0:m.mapVisualOptions)==null?void 0:x.customTopoJsonUrl)||""),{setCardPreferences:l}=s.useEditorActions(),{data:i}=s.useTopoJson(t),c=Object.keys((i==null?void 0:i.objects)||{}).map(A=>({label:A,value:A}))||[],o=[{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:"p-6",children:[e.jsx(_e,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ye,{className:"h-9",options:o,onValueChange:A=>{console.log("value",A),l({...t.preferences,mapVisualOptions:{topoJsonUrl:A}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(s.Input,{onChange:A=>{r(A.target.value)},onBlur:()=>{var A;console.log("onBlur",n),l({...t.preferences,mapVisualOptions:{...(A=t.preferences)==null?void 0:A.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${s.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Map Object"}),e.jsx(ye,{className:"h-9",options:c,value:((p=(h=t.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:p.objectKey)||"",label:"Map Object",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,objectKey:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Projection"}),e.jsx(ye,{className:"h-9",options:kn,value:((g=(j=t.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:g.projection)||"",label:"Projection",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projection:A}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{children:"Colors"}),e.jsx(ye,{className:"h-9",options:In,value:((D=(v=t.preferences)==null?void 0:v.mapVisualOptions)==null?void 0:D.colorScale)||"",label:"Select Color Scale",onValueChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,colorScale:A}})}})]})]})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(_e,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:.1,value:((B=(k=t.preferences)==null?void 0:k.mapVisualOptions)==null?void 0:B.projectionScale)||1,onChange:A=>{var w;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionScale:Number(A.target.value)}})}}),e.jsx(s.Label,{children:"X"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((C=(E=(L=t.preferences)==null?void 0:L.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:C[0])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[Number(A.target.value),((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(s.Label,{children:"Y"}),e.jsx(s.Input,{className:`h-9 w-full ${s.removeRing}`,type:"number",step:10,value:((N=(b=(f=t.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:b.projectionOffset)==null?void 0:N[1])||0,onChange:A=>{var w,P,I,T;l({...t.preferences,mapVisualOptions:{...(w=t.preferences)==null?void 0:w.mapVisualOptions,projectionOffset:[((T=(I=(P=t.preferences)==null?void 0:P.mapVisualOptions)==null?void 0:I.projectionOffset)==null?void 0:T[0])||0,Number(A.target.value)]}})}})]})}),e.jsx(s.Separator,{className:"my-4"}),e.jsx(ke,{})]})}function Mn(){var r;const t=s.useEditorStore(l=>l.card.preferences),{setCardPreferences:a}=s.useEditorStore(l=>l.actions);function n(l){a({...t,textVisualOptions:{...t==null?void 0:t.textVisualOptions,isDynamicText:l==="dynamic"}})}return e.jsxs(s.RadioGroup,{value:(r=t==null?void 0:t.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(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 Be({cardType:t,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return t==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:`${s.titleCase(t)} ${n}`}),e.jsx(s.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:l=>l.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),t==="text"&&e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsx(s.AccordionContent,{className:"space-y-4 px-2 py-4",children:e.jsx(Mn,{})})]}),!["range","text"].includes(t)&&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(ke,{}),e.jsx(Me,{})]})]})]})})}function Ln(){const t=s.useEditorStore(r=>{var l,i;return(i=(l=r==null?void 0:r.card)==null?void 0:l.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=s.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Sort"}),e.jsx(ye,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:t||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(s.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(s.AccordionItem,{value:"item-1",children:[e.jsx(s.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(s.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(s.AccordionItem,{value:"item-2",children:[e.jsx(s.AccordionTrigger,{children:"Settings"}),e.jsxs(s.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(Xs,{})]})]}),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(ke,{}),e.jsx(Me,{})]})]})]})})}function Fn({cardType:t="table"}){console.log("cardType",t);const a=s.useEditorStore(l=>{var i;return(i=l.card)==null?void 0:i.preferences}),n=s.useEditorStore(l=>l.actions.setCardPreferences),r=l=>{n({...a,allowDownload:l})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(s.Accordion,{defaultValue:["item-3"],type:"multiple",children: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(ke,{}),e.jsx(Me,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Checkbox,{onCheckedChange:r,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 tt({color:t,onColorChange:a,onClose:n}){const[r,l]=S.useState(0),[i,c]=S.useState(100),[o,d]=S.useState(50),[u,m]=S.useState(t);S.useEffect(()=>{const v=gs(t);if(v){const D=js(v.r,v.g,v.b);l(D.h),c(D.s),d(D.l),m(t)}},[t]);const x=v=>{l(v),p(v,i,o)},h=v=>{const D=v.currentTarget.getBoundingClientRect(),k=Math.max(0,Math.min(1,(v.clientX-D.left)/D.width)),B=Math.max(0,Math.min(1,(v.clientY-D.top)/D.height)),L=k*100,E=(1-B)*100;c(L),d(E),p(r,L,E)},p=(v,D,k)=>{const B=On(v,D,k),L=Pn(B.r,B.g,B.b);m(L)},j=v=>{if(m(v),/^#[0-9A-Fa-f]{6}$/.test(v)){const D=gs(v);if(D){const k=js(D.r,D.g,D.b);l(k.h),c(k.s),d(k.l)}}},g=()=>{/^#[0-9A-Fa-f]{6}$/.test(u)&&(a(u),n())};return e.jsxs("div",{className:"p-4 space-y-4 w-[320px]",children:[e.jsxs("div",{className:"relative h-[200px] rounded cursor-crosshair",style:{background:`hsl(${r}, 100%, 50%)`},onClick:h,onMouseMove:v=>{v.buttons===1&&h(v)},children:[e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to right, white, transparent)"}}),e.jsx("div",{className:"absolute inset-0 rounded",style:{background:"linear-gradient(to bottom, transparent, black)"}}),e.jsx("div",{className:"absolute w-4 h-4 -ml-2 -mt-2 rounded-full border-2 border-white shadow-md",style:{left:`${i}%`,top:`${100-o}%`,backgroundColor:u}})]}),e.jsx("div",{className:"space-y-2",children:e.jsx("input",{type:"range",min:"0",max:"360",value:r,onChange:v=>x(Number(v.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:u,onChange:v=>j(v.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:u}}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"NEW"})]})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(s.Button,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(s.Button,{onClick:g,children:"OK"})]})]})}function gs(t){const a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:null}function Pn(t,a,n){return"#"+((1<<24)+(t<<16)+(a<<8)+n).toString(16).slice(1)}function js(t,a,n){t/=255,a/=255,n/=255;const r=Math.max(t,a,n),l=Math.min(t,a,n);let i=0,c=0;const o=(r+l)/2;if(r!==l){const d=r-l;switch(c=o>.5?d/(2-r-l):d/(r+l),r){case t:i=((a-n)/d+(a<n?6:0))/6;break;case a:i=((n-t)/d+2)/6;break;case n:i=((t-a)/d+4)/6;break}}return{h:Math.round(i*360),s:Math.round(c*100),l:Math.round(o*100)}}function On(t,a,n){t/=360,a/=100,n/=100;let r,l,i;if(a===0)r=l=i=n;else{const c=(u,m,x)=>(x<0&&(x+=1),x>1&&(x-=1),x<.16666666666666666?u+(m-u)*6*x:x<.5?m:x<.6666666666666666?u+(m-u)*(.6666666666666666-x)*6:u),o=n<.5?n*(1+a):n+a-n*a,d=2*n-o;r=c(d,o,t+1/3),l=c(d,o,t),i=c(d,o,t-1/3)}return{r:Math.round(r*255),g:Math.round(l*255),b:Math.round(i*255)}}const Bn=["#000000","#ffffff","#6b7280","#dc2626","#ea580c","#ca8a04","#16a34a","#0891b2","#2563eb","#7c3aed","#c026d3","#e11d48","#0f172a","#f3f4f6","#fbbf24"];function at(){var B,L,E,C,f,b,N,A,w,P;const t=s.useEditorStore(I=>I.card),a=s.useEditorStore(I=>{var T;return(T=I.card)==null?void 0:T.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions(),{data:l}=s.useDashboardCardQuery(t),[i,c]=S.useState({}),[o,d]=S.useState(null),[u,m]=S.useState(null),x=S.useMemo(()=>{var M,F,z,$,O,G,R;if(!(l!=null&&l.records)||l.records.length===0)return[];const I=(t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine",T=(t==null?void 0:t.type)==="bar"||(t==null?void 0:t.type)==="line"||(t==null?void 0:t.type)==="horizontalBar"||(t==null?void 0:t.type)==="bullet",y=((M=t==null?void 0:t.config)==null?void 0:M.pivotByColumns)&&t.config.pivotByColumns.length>0;if((I||T)&&y){if(l.pivotSchema&&Array.isArray(l.pivotSchema)){const _=new Set;return l.pivotSchema.forEach(J=>{J.alias&&_.add(J.alias)}),Array.from(_)}if(l.records.length>0){const _=l.records[0],J=Object.keys(_),se=new Set;(F=t==null?void 0:t.config)!=null&&F.groupByColumns&&t.config.groupByColumns.forEach(Y=>{se.add(Y.label||Y.name),se.add(Y.alias||Y.name)});const Z=new Set;return(z=t==null?void 0:t.config)!=null&&z.metricColumns&&t.config.metricColumns.forEach(Y=>{const U=Y.alias||Y.name;Z.add(U),Z.add(`${U}_count`),Z.add(`${U}_sum`),Z.add(`${U}_avg`),Z.add(`${U}_min`),Z.add(`${U}_max`);const te=Y.entityName||Y.qualifiedEntityName;te&&(Z.add(`${te}_${U}`),Z.add(`${te}_${U}_count`))}),J.filter(Y=>!se.has(Y)&&!Z.has(Y))}}if((T||I)&&!y&&((O=($=t==null?void 0:t.config)==null?void 0:$.metricColumns)!=null&&O.length))return t.config.metricColumns.map(_=>_.alias||_.label||_.name);if((R=(G=t==null?void 0:t.config)==null?void 0:G.groupByColumns)!=null&&R.length){const _=t.config.groupByColumns[0],J=_.label||_.name,se=new Set;return l.records.forEach(Z=>{const ae=Z[J];ae!=null&&se.add(String(ae))}),Array.from(se)}return[]},[l,(B=t==null?void 0:t.config)==null?void 0:B.groupByColumns,(L=t==null?void 0:t.config)==null?void 0:L.pivotByColumns,(E=t==null?void 0:t.config)==null?void 0:E.metricColumns,t==null?void 0:t.type]),h=S.useMemo(()=>s.getDefaultChartColors(),[]);S.useEffect(()=>{const I={};x.forEach((T,y)=>{I[T]=s.getColorForValue(T,y,a==null?void 0:a.colorConfig)}),c(I)},[x,a==null?void 0:a.colorConfig,h]);const p=(I,T)=>{const y={...i,[I]:T};c(y);const M={...a||{},colorConfig:{segments:y}};n(M);const F={...t,preferences:M};r(F)},j=(I,T)=>{var O;const y=h[T%h.length],{[I]:M,...F}=((O=a==null?void 0:a.colorConfig)==null?void 0:O.segments)||{},z={...a||{},colorConfig:{segments:F}};n(z);const $={...t,preferences:z};r($),c(G=>({...G,[I]:y}))};if(!x.length||!((t==null?void 0:t.type)==="stackedBar"||(t==null?void 0:t.type)==="stackedLine"?((f=(C=t==null?void 0:t.config)==null?void 0:C.groupByColumns)==null?void 0:f.length)||((N=(b=t==null?void 0:t.config)==null?void 0:b.pivotByColumns)==null?void 0:N.length):(w=(A=t==null?void 0:t.config)==null?void 0:A.groupByColumns)==null?void 0:w.length)||["table","kpi","text","custom","heatmap"].includes(t.type))return null;const D=()=>{const I={...a||{},colorConfig:{segments:{}}};n(I);const T={...t,preferences:I};r(T);const y={};x.forEach((M,F)=>{y[M]=s.getColorForValue(M,F,void 0)}),c(y)},k=Object.keys(((P=a==null?void 0:a.colorConfig)==null?void 0:P.segments)||{}).length>0;return e.jsxs(s.AccordionItem,{value:"colors",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{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:k&&e.jsxs("button",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:D,children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset All"]})})}),e.jsx("div",{className:"max-h-[200px] space-y-2 overflow-y-auto pr-1",children:x.map((I,T)=>{const y=s.isDefaultColor(i[I],T),M=!y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:o===I,onOpenChange:F=>d(F?I: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:i[I]}})}),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:h.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",i[I]===F?"border-gray-900":"border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(null)},children:[z===T%h.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:Bn.map((F,z)=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border transition-all hover:scale-110",i[I]===F?"border-2 border-gray-900":F==="#ffffff"?"border border-gray-300":"border border-transparent"),style:{backgroundColor:F},onClick:()=>{p(I,F),d(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:I,color:i[I]}),d(null)},children:"Custom color"}),!y&&e.jsxs("button",{className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",onClick:()=>{j(I,T),d(null)},children:[e.jsx(hs,{className:"h-3 w-3"}),"Reset"]})]})]})})]}),e.jsx("span",{className:"flex-1 truncate text-sm",children:I}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(custom)"})]},I)})}),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(tt,{color:u.color,onColorChange:I=>{p(u.value,I),m(null)},onClose:()=>m(null)})})]})]})})]})}function Ne({value:t,onSave:a,placeholder:n="",type:r="text",className:l=""}){const[i,c]=S.useState(t??""),[o,d]=S.useState(!1);S.useEffect(()=>{c(t??"")},[t]);const u=()=>{a(i),d(!1)},m=()=>{c(t??""),d(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${l}`,children:[e.jsx(s.Input$1,{placeholder:n,type:r,value:o?i:t??"",onChange:x=>{c(x.target.value),d(!0)},onFocus:()=>d(!0),onClick:x=>x.stopPropagation(),className:"h-8 text-xs",onPointerDown:x=>x.stopPropagation(),onKeyDown:x=>{x.stopPropagation(),x.key==="Enter"&&o&&i!==t?u():x.key==="Escape"&&m()},"aria-label":n||"Edit field"}),o&&i!==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: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 edit",onClick:m,children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}const Rn=["auto","number","currency","percent","scientific","date"],Vn=[{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"}],zn=[{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"}],Gn=t=>t.charAt(0).toUpperCase()+t.slice(1);function rs({formatOptions:t={},onFormatOptionsChange:a,showTitle:n=!0,title:r="NUMBER FORMAT"}){const l=t.type||"auto",i=(o,d)=>{a({...t,[o]:d})},c=()=>l==="currency"?2:l==="percent"?1:0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:r}),e.jsxs(s.Select,{value:l,onValueChange:o=>i("type",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Rn.map(o=>e.jsx(s.SelectItem,{value:o,className:"text-xs",children:o==="auto"?"Auto (Default)":Gn(o)},o))})]})]}),l!=="auto"&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-4",children:[["number","currency","percent"].includes(l)&&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??c(),onChange:o=>i("decimalPlaces",parseInt(o.target.value)||0),className:"h-8 text-xs"})})]}),l==="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:o=>i("currency",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Vn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.value))})]})]}),["number","currency"].includes(l)&&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:o=>i("useSuffix",o)})]}),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:o=>i("locale",o),children:[e.jsx(s.SelectTrigger,{className:"h-8 flex-1 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:zn.map(o=>e.jsx(s.SelectItem,{value:o.value,className:"text-xs",children:o.label},o.value))})]})]}),l==="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:o=>i("prefix",o.target.value),className:"h-8 text-xs"})})]}),l==="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:o=>i("suffix",o.target.value),className:"h-8 text-xs"})})]}),["number","currency"].includes(l)&&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:o=>i("negativeInParentheses",o)})]}),l==="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:o=>i("multiplyBy",o.target.value?parseFloat(o.target.value):void 0),className:"h-8 text-xs"})})]}),l==="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:o=>i("dateFormat",o.target.value),className:"h-8 text-xs"})})]})]})]})}function bs({axis:t,label:a,type:n,config:r,onChange:l}){var x,h,p,j,g,v,D,k,B,L,E,C;const i=(f,b)=>{l({...r,[f]:b})},c=(f,b)=>{var N,A;l({...r,name:{enabled:f==="enabled"?b:((N=r==null?void 0:r.name)==null?void 0:N.enabled)??!1,text:f==="text"?b:(A=r==null?void 0:r.name)==null?void 0:A.text}})},o=(f,b)=>{var N,A;l({...r,labels:{enabled:f==="enabled"?b:((N=r==null?void 0:r.labels)==null?void 0:N.enabled)??!0,rotation:f==="rotation"?b:(A=r==null?void 0:r.labels)==null?void 0:A.rotation}})},d=(f,b)=>{l({...r,scale:{...r==null?void 0:r.scale,[f]:b===""?"auto":Number(b)}})},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:a})})}),e.jsx(s.SmallSwitch,{checked:(r==null?void 0:r.enabled)!==!1,onCheckedChange:f=>i("enabled",f),onClick:f=>f.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 justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TITLE"}),e.jsx(s.SmallSwitch,{checked:((x=r==null?void 0:r.name)==null?void 0:x.enabled)??!1,onCheckedChange:f=>c("enabled",f)})]}),((h=r==null?void 0:r.name)==null?void 0:h.enabled)&&e.jsx(Ne,{placeholder:`${a} title`,value:((p=r==null?void 0:r.name)==null?void 0:p.text)||"",onSave:f=>c("text",f),className:""})]}),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:f=>i("position",f),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":s.titleCase(f)},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",children:"LABELS"}),e.jsx(s.SmallSwitch,{checked:((j=r==null?void 0:r.labels)==null?void 0:j.enabled)!==!1,onCheckedChange:f=>o("enabled",f)})]}),((g=r==null?void 0:r.labels)==null?void 0:g.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(((v=r==null?void 0:r.labels)==null?void 0:v.rotation)||"auto"),onValueChange:f=>o("rotation",f==="auto"?"auto":Number(f)),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:m.map(f=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:f==="auto"?"Auto (Default)":`${f}°`},f))})]})]})]}),n==="value"&&e.jsx(rs,{formatOptions:(r==null?void 0:r.formatOptions)||{},onFormatOptionsChange:f=>l({...r,formatOptions:f}),showTitle:!0,title:"FORMAT"}),n==="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(Ne,{type:"number",placeholder:"auto",value:((D=r==null?void 0:r.scale)==null?void 0:D.min)==="auto"||((k=r==null?void 0:r.scale)==null?void 0:k.min)===void 0?"":String(r.scale.min),onSave:f=>d("min",f),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(Ne,{type:"number",placeholder:"auto",value:((B=r==null?void 0:r.scale)==null?void 0:B.max)==="auto"||((L=r==null?void 0:r.scale)==null?void 0:L.max)===void 0?"":String(r.scale.max),onSave:f=>d("max",f),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(Ne,{type:"number",placeholder:"auto",value:((E=r==null?void 0:r.scale)==null?void 0:E.stepSize)==="auto"||((C=r==null?void 0:r.scale)==null?void 0:C.stepSize)===void 0?"":String(r.scale.stepSize),onSave:f=>d("stepSize",f),className:""})})]})]})]})]})]})}function nt(){const t=s.useEditorStore(c=>c.card),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n,updateCardInFrame:r}=s.useEditorActions();if(!t||["tornado","pyramid","kpi","treemap"].includes(t.type))return null;const l=s.AxisConfigurator.getAxisInfo(t.type,a);if(!l.hasXAxis&&!l.hasYAxis)return null;const i=(c,o)=>{const u={...a||{},[c==="x"?"xAxisConfig":"yAxisConfig"]:o};n(u);const m={...t,preferences:u};r(m)};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(As,{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:[l.hasXAxis&&e.jsx(bs,{axis:"x",label:"X-Axis",type:l.xAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"x"),a==null?void 0:a.xAxisConfig),onChange:c=>i("x",c)}),l.hasYAxis&&e.jsx(bs,{axis:"y",label:"Y-Axis",type:l.yAxisType,config:s.mergeAxisConfig(s.getDefaultAxisConfig(t.type,"y"),a==null?void 0:a.yAxisConfig),onChange:c=>i("y",c)})]})})]})}function rt(){const t=s.useEditorStore(m=>m.card),a=s.useEditorStore(m=>{var x,h,p,j;return(j=(p=(h=(x=m.card)==null?void 0:x.preferences)==null?void 0:h.chartOptions)==null?void 0:p.plugins)==null?void 0:j.legend}),{setLegendOptions:n}=s.useEditorActions();if(!t||!s.chartSupportsLegend(t.type))return null;const r=s.getDefaultLegendConfig(t.type),l=(r==null?void 0:r.display)??!0,i=(r==null?void 0:r.position)??"top",c=(r==null?void 0:r.align)??"center",o=(m,x)=>{const h={...a,[m]:x};n(h)},d=["top","bottom","left","right"],u=["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(Ft,{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)??l,onCheckedChange:m=>o("display",m)})]}),((a==null?void 0:a.display)??l)&&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)||i,onValueChange:m=>o("position",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:d.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Alignment"}),e.jsxs(s.Select,{value:(a==null?void 0:a.align)||c,onValueChange:m=>o("align",m),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:u.map(m=>e.jsx(s.SelectItem,{value:m,className:"text-xs",children:s.titleCase(m)},m))})]})]})]})]})})]})}function lt(){var w,P,I,T,y,M,F,z,$;const t=s.useEditorStore(O=>O.card),a=s.useEditorStore(O=>{var G,R;return(R=(G=O.card)==null?void 0:G.preferences)==null?void 0:R.dataLabelsConfig}),n=s.useEditorStore(O=>{var G;return(G=O.card)==null?void 0:G.preferences}),{setCardPreferences:r,updateCardInFrame:l}=s.useEditorActions();if(!t||!s.chartSupportsDataLabels(t.type))return null;const i=((w=n==null?void 0:n.chartOptions)==null?void 0:w.indexAxis)==="y",c=t.type==="stackedBar"||t.type==="stackedLine",o=t.type==="pie"||t.type==="doughnut"||t.type==="polarArea"||t.type==="funnel",d=!o,u=(I=(P=n==null?void 0:n.chartOptions)==null?void 0:P.plugins)==null?void 0:I.datalabels,m=(u==null?void 0:u.display)!==!1&&((u==null?void 0:u.anchor)||(u==null?void 0:u.align)),x=t.type==="treemap"?!0:m,h=(a==null?void 0:a.enabled)!==void 0?a.enabled:x,p=(O,G)=>{const R={...a,[O]:G},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},j=(O,G)=>{const R={...a,font:{...a==null?void 0:a.font,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},g=(O,G)=>{const R={...a,formatOptions:{...a==null?void 0:a.formatOptions,[O]:G}},_={...t.preferences||{},dataLabelsConfig:R};r(_);const J={...t,preferences:_};l(J)},v=()=>{const O=t.type;return O==="stackedBar"||O==="stackedLine"||O==="pie"||O==="doughnut"?"center":i?"right":"top"},D=t.type!=="treemap"&&t.type!=="heatmap",k=t.type!=="treemap",B=v();let L=[];D&&(c||o?L=["center"]:L=["auto",...(i?["center","left","right"]:["center","top","bottom"]).filter(G=>G!==B),"custom"]);const E=()=>s.titleCase(B),C=["center","start","end"],f=["center","start","end","top","bottom"],b=d?["auto","number","currency","percent","none"]:["number","currency","percent","none"],N=[{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"}],A=[{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(Qt,{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:h,onCheckedChange:O=>p("enabled",O)})]}),h&&e.jsxs(e.Fragment,{children:[D&&!c&&!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:(a==null?void 0:a.position)||"auto",onValueChange:O=>p("position",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:L.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"?E():O==="custom"?"Custom (Advanced)":s.titleCase(O)},O))})]})]}),c&&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:O=>p("showTotal",O)})]}),(a==null?void 0:a.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:(a==null?void 0:a.anchor)||"center",onValueChange:O=>p("anchor",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:C.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]}),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((a==null?void 0:a.align)||"center"),onValueChange:O=>p("align",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:f.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:s.titleCase(O)},O))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"Format"}),e.jsxs(s.Select,{value:(a==null?void 0:a.format)||(d?"auto":"none"),onValueChange:O=>p("format",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:b.map(O=>e.jsx(s.SelectItem,{value:O,className:"text-xs",children:O==="auto"&&d?"Auto (Use Axis)":O==="none"?"None (Raw Value)":s.titleCase(O)},O))})]})]}),(a==null?void 0:a.format)&&!["auto","none"].includes(a.format)&&e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-muted",children:[["number","currency","percent"].includes(a.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(Ne,{type:"number",placeholder:"0",value:String(((T=a==null?void 0:a.formatOptions)==null?void 0:T.decimalPlaces)??(a.format==="currency"?2:a.format==="percent"?1:0)),onSave:O=>g("decimalPlaces",Number(O)),className:""})})]}),a.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:((y=a==null?void 0:a.formatOptions)==null?void 0:y.currency)||"USD",onValueChange:O=>g("currency",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:N.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]}),["number","currency"].includes(a.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:((M=a==null?void 0:a.formatOptions)==null?void 0:M.useSuffix)??!1,onCheckedChange:O=>g("useSuffix",O)})]}),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:((F=a==null?void 0:a.formatOptions)==null?void 0:F.locale)||"en-US",onValueChange:O=>g("locale",O),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs flex-1",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:A.map(O=>e.jsx(s.SelectItem,{value:O.value,className:"text-xs",children:O.label},O.value))})]})]})]}),k&&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(Ne,{type:"number",placeholder:"12",value:String(((z=a==null?void 0:a.font)==null?void 0:z.size)||12),onSave:O=>j("size",Number(O)),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:(($=a==null?void 0:a.font)==null?void 0:$.weight)||"normal",onValueChange:O=>j("weight",O),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:(a==null?void 0:a.color)==="auto"||!(a!=null&&a.color)?"auto":"custom",onValueChange:O=>{O==="auto"&&p("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(Ne,{type:"number",placeholder:"0",value:String((a==null?void 0:a.rotation)||0),onSave:O=>p("rotation",Number(O)),className:""})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"degrees"})]})]})]})]})})]})}function Re({value:t,onCommit:a,type:n="text",placeholder:r,className:l}){const[i,c]=S.useState(t),o=S.useRef(!1);S.useEffect(()=>{c(t)},[t]);const d=()=>{if(o.current){o.current=!1;return}i!==t&&a(i)},u=m=>{if(m.key==="Enter"){m.currentTarget.blur();return}m.key==="Escape"&&(o.current=!0,c(t),m.currentTarget.blur())};return e.jsx(s.Input,{type:n,placeholder:r,value:i,onChange:m=>c(m.target.value),onBlur:d,onKeyDown:u,className:l})}const vs=["poor","satisfactory","good"];function ys(t){if(!t)return;const a={...t};return a.targetMetricKey||delete a.targetMetricKey,a.comparativeMetricKey||delete a.comparativeMetricKey,!a.targetValue&&a.targetValue!==0&&delete a.targetValue,(!a.rangeKeys||Object.keys(a.rangeKeys).length===0)&&delete a.rangeKeys,(!a.ranges||Object.keys(a.ranges).length===0)&&delete a.ranges,(!a.rangeLabels||Object.keys(a.rangeLabels).length===0)&&delete a.rangeLabels,a}function ot(){var I,T;const t=s.useEditorStore(y=>y.card.preferences),a=s.useEditorStore(y=>y.card),n=s.useEditorStore(y=>y.isDevMode),{setCardPreferences:r,setChartOrientation:l}=s.useEditorActions(),i=S.useMemo(()=>(t==null?void 0:t.bulletConfig)||{},[t==null?void 0:t.bulletConfig]),o=s.hasValidCardConfig(a==null?void 0:a.config)&&!n,[d,u]=S.useState(i.showRanges??!1),[m,x]=S.useState(i.rangesArePercentages??!1),h=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o,[p,j]=S.useState(h);S.useEffect(()=>{u(i.showRanges??!1)},[i.showRanges]),S.useEffect(()=>{x(i.rangesArePercentages??!1)},[i.rangesArePercentages]);const g=i.targetValue===void 0?"":String(i.targetValue);S.useEffect(()=>{const y=i.disableAutoComparative?!1:i.comparativeMetricKey!==void 0||!o;j(y)},[i.disableAutoComparative,i.comparativeMetricKey,o]);const v=S.useMemo(()=>{var y,M;return((M=(y=a==null?void 0:a.config)==null?void 0:y.metricColumns)==null?void 0:M.map(F=>{const z=F.label||F.name||F.alias||"";return{value:z,label:z}}))||[]},[(I=a==null?void 0:a.config)==null?void 0:I.metricColumns]);S.useEffect(()=>{var R,_;if(!t||v.length===0)return;const y={};let M=!1;const F=(R=v[1])==null?void 0:R.value;!i.targetMetricKey&&F&&(y.targetMetricKey=F,M=!0);const z=(_=v[2])==null?void 0:_.value;!i.comparativeMetricKey&&!i.disableAutoComparative&&z&&(y.comparativeMetricKey=z,M=!0);const $=v.slice(3),O={...i.rangeKeys||{}};let G=!1;if(vs.forEach((J,se)=>{!O[J]&&$[se]&&(O[J]=$[se].value,G=!0)}),G&&(y.rangeKeys=O,M=!0,i.showRanges===void 0&&(y.showRanges=!0)),M){const J=ys({...i,...y});r({...t,bulletConfig:J})}},[v,i,t,r]);const D=y=>{const M=ys({...i,...y});r({...t,bulletConfig:M})},k=(y,M)=>{const F={...i.rangeKeys||{},[y]:M.trim()};M.trim()||delete F[y],D({rangeKeys:Object.keys(F).length>0?F:void 0})},B=(y,M)=>{const F=M===""?void 0:Number(M),z={...i.ranges||{}};F===void 0||Number.isNaN(F)?delete z[y]:z[y]=F,D({ranges:Object.keys(z).length?z:void 0})},L=y=>{if(y===""){D({targetValue:void 0});return}const M=Number(y);D({targetValue:Number.isNaN(M)?void 0:M})},E=(y,M)=>{const F=M.trim(),z={...i.rangeLabels||{}};F?z[y]=F:delete z[y],D({rangeLabels:Object.keys(z).length>0?z:void 0})},C=y=>{u(y),D({showRanges:y})},f=y=>{x(y),D({rangesArePercentages:y})},b=i.orientation||(((T=t==null?void 0:t.chartOptions)==null?void 0:T.indexAxis)==="y"?"horizontal":"vertical"),N=y=>{D({orientation:y}),l(y==="horizontal"?"y":"x")},A=[{value:"__none",label:"None"},...v.map(y=>({value:y.value,label:y.label}))],w=A,P=y=>{if(j(y),!y){D({comparativeMetricKey:void 0,disableAutoComparative:!0});return}if(!o){D({disableAutoComparative:!1});return}if(i.comparativeMetricKey)D({disableAutoComparative:!1});else{const M=v.find(F=>F.value!==i.targetMetricKey);D({comparativeMetricKey:M==null?void 0:M.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:b,onValueChange:y=>N(y),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"})]})]})]}),o&&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:i.targetMetricKey||"__none",onValueChange:y=>D({targetMetricKey:y==="__none"?void 0:y}),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"}),v.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"COMPARATIVE METRIC"}),o?e.jsxs(s.Select,{value:i.comparativeMetricKey||"__none",onValueChange:y=>D({comparativeMetricKey:y==="__none"?void 0:y,disableAutoComparative:y==="__none"}),children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select metric"})}),e.jsx(s.SelectContent,{children:A.map(y=>e.jsx(s.SelectItem,{value:y.value,className:"text-xs",children:y.label},y.value))})]}):e.jsxs("div",{className:"space-y-2 rounded-md border border-border/50 p-3 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between font-medium",children:[e.jsx("span",{children:"Show comparative"}),e.jsx(s.SmallSwitch,{checked:p,onCheckedChange:y=>P(y)})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comparative values are auto-detected from the third metric in your results."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(s.Label,{className:"text-xs font-medium",children:"TARGET VALUE (FALLBACK)"}),e.jsx(Re,{type:"number",className:"h-8 text-xs",value:g,onCommit:L,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:d,onCheckedChange:C})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[e.jsx("input",{type:"checkbox",checked:m,disabled:!d,onChange:y=>f(y.target.checked),className:"h-3.5 w-3.5 accent-primary disabled:opacity-50"}),e.jsx("span",{children:"Use % of value"})]})]}),d&&e.jsx("div",{className:"space-y-3",children:vs.map(y=>{var M,F,z,$,O;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:[y," LABEL"]}),e.jsx(Re,{placeholder:`Display label (${y})`,value:((M=i.rangeLabels)==null?void 0:M[y])||"",onCommit:G=>E(y,G),className:"h-8 text-xs"})]}),o?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(s.Label,{className:"text-[11px] font-medium uppercase tracking-wide",children:[y," COLUMN"]}),e.jsxs(s.Select,{value:((F=i.rangeKeys)==null?void 0:F[y])||"__none",onValueChange:G=>{G==="__none"?k(y,""):k(y,G)},children:[e.jsx(s.SelectTrigger,{className:"h-8 text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select column"})}),e.jsx(s.SelectContent,{children:w.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:[y," COLUMN KEY"]}),e.jsx(Re,{placeholder:"Column key",value:((z=i.rangeKeys)==null?void 0:z[y])||"",onCommit:G=>k(y,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:[y," VALUE"]}),e.jsx(Re,{type:"number",placeholder:m?"0.80":"Static value",value:(($=i.ranges)==null?void 0:$[y])===void 0?"":String((O=i.ranges)==null?void 0:O[y]),onCommit:G=>B(y,G),className:"h-8 text-xs"})]})]},y)})})]})]})]})}const Ns=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],$n=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Pe({value:t,onChange:a,label:n}){const[r,l]=S.useState(!1),[i,c]=S.useState(!1),o=()=>{const d=Ns.find(u=>u.value===t);return d?d.color:t.startsWith("#")?t:Ns[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:l,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:o()},"aria-label":`Change color for ${n}`})}),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:$n.map(d=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",o()===d?"border-gray-900":"border-transparent"),style:{backgroundColor:d},onClick:()=>{a(d),l(!1)},children:e.jsx("span",{className:"sr-only",children:d})},d))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{c(!0),l(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),i&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>c(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(tt,{color:o(),onColorChange:d=>{a(d),c(!1)},onClose:()=>c(!1)})})]})]})}const qn=Object.keys(s.HEATMAP_PRESET_PALETTES);function it(){const t=s.useEditorStore(h=>h.card),a=s.useEditorStore(h=>{var p;return(p=h.card)==null?void 0:p.preferences}),{setCardPreferences:n}=s.useEditorActions(),r=(t==null?void 0:t.type)==="heatmap",l=(a==null?void 0:a.heatmapConfig)||{},i=l.colorPalette??"green",c=l.legendPosition??"bottom",o=S.useMemo(()=>l.colorRange&&l.colorRange[0]&&l.colorRange[1]?[l.colorRange[0],l.colorRange[1]]:[...s.DEFAULT_HEATMAP_CUSTOM_RANGE],[l.colorRange]),d=h=>{const p={...l,...h};p.colorPalette!=="custom"?delete p.colorRange:(!p.colorRange||!p.colorRange[0]||!p.colorRange[1])&&(p.colorRange=[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]),n({...a||{},heatmapConfig:p})},u=h=>{d({colorPalette:h,colorRange:h==="custom"?l.colorRange??[...s.DEFAULT_HEATMAP_CUSTOM_RANGE]:void 0})},m=(h,p)=>{const j=[...o];j[h]=p,d({colorPalette:"custom",colorRange:j})},x=h=>{d({legendPosition:h})};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:i,onValueChange:h=>u(h??"blue"),className:"space-y-3",children:[qn.map(h=>{const p=s.HEATMAP_PRESET_PALETTES[h];return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(s.RadioGroupItem,{id:`heatmap-${h}`,value:h}),e.jsxs(s.Label,{htmlFor:`heatmap-${h}`,className:"flex w-full flex-col gap-1 text-sm font-normal",children:[e.jsx("span",{className:"font-medium",children:p.label}),e.jsx("span",{className:"h-2 rounded-full",style:{background:`linear-gradient(90deg, ${p.start}, ${p.end})`}})]})]},h)}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.RadioGroupItem,{id:"heatmap-custom",value:"custom"}),e.jsx(s.Label,{htmlFor:"heatmap-custom",className:"text-sm font-medium",children:"Custom colors"})]}),i==="custom"&&e.jsxs("div",{className:"flex flex-col gap-3 pl-6",children:[e.jsx(Pe,{value:o[0],onChange:h=>m(0,h),label:"Start color"}),e.jsx(Pe,{value:o[1],onChange:h=>m(1,h),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:c,onValueChange:h=>x(h??"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(h=>e.jsx(s.SelectItem,{value:h,className:"text-xs",children:h[0].toUpperCase()+h.slice(1)},h))})]})]})]})]}):null}function Un(){const t=s.useEditorStore(a=>a.card);return e.jsxs("div",{className:"space-y-4 px-6 py-4",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Chart Configuration"}),e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full px-2",children:[(t==null?void 0:t.type)==="heatmap"&&e.jsx(it,{}),(t==null?void 0:t.type)==="bullet"&&e.jsx(ot,{}),e.jsx(at,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})]})}const Kn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),_n=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Hn=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:t=>t.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Jn(){const t=s.useEditorStore(n=>n.card.type);function a(n){const r=["kpi","table","text","map","custom"],l=i=>r.includes(n)?i:e.jsxs(e.Fragment,{children:[i,e.jsx(Un,{})]});switch(n){case"stackedBar":case"stackedLine":return l(e.jsx(Ln,{}));case"tornado":case"pyramid":return l(e.jsx(Be,{docContent:Kn,cardType:n}));case"kpi":return e.jsx(Tn,{});case"line":case"bar":return l(e.jsx(bn,{cardType:n}));case"range":return l(e.jsx(Be,{docContent:_n,cardType:n}));case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return l(e.jsx(Be,{cardType:n}));case"bubble":case"scatter":return l(e.jsx(vn,{cardType:n}));case"table":return e.jsx(Fn,{cardType:n});case"text":return e.jsx(Be,{docContent:Hn,cardType:n,suffix:"Visual"});case"map":return e.jsx(An,{});case"custom":return e.jsx(pn,{});default:return l(e.jsx(Cn,{}))}}return e.jsxs(s.ScrollArea,{className:"h-full w-full text-sm",children:[a(t),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})}function Qn(){const t=S.useRef(null),a=S.useRef(null),n=s.useEditorStore(l=>l.isShowingVisual),r=s.useEditorStore(l=>l.showAIDialog);return S.useEffect(()=>{var l,i,c,o;r?((l=t.current)==null||l.resize(0),(i=a.current)==null||i.resize(0)):((c=t.current)==null||c.resize(25),(o=a.current)==null||o.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(Qa,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!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(Jn,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(fs,{})})]}):e.jsx(fs,{})})]})}function Wn(t){var me;s.useAIInteractionStore(q=>q.currentAIContext);const[a,n]=S.useState(""),[r,l]=S.useState(null),{authToken:i,tokenProps:c}=s.useSemaphorContext(),o=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.sql}),d=s.useEditorStore(q=>q.isDevMode),u=s.useEditorStore(q=>{var W;return(W=q==null?void 0:q.card)==null?void 0:W.python}),{setCardPython:m,setCardSql:x,setRunSql:h,switchCardType:p,setQueryConfig:j}=s.useEditorActions(),g=s.useEditorStore(q=>q.currentAssitantScope)||[],v=s.useEditorStore(q=>q.userInputForAI),D=s.useEditorStore(q=>q.triggerAIRun),k=s.useEditorStore(q=>q.card),B=s.useEditorStore(q=>q.selectedDatabaseName),L=s.useEditorStore(q=>q.selectedTableName),E=s.useEditorStore(q=>q.selectedConnectionId),C=s.useEditorStore(q=>q.selectedSchemaName),f=s.useDashboardStore(q=>q.dashboard.aiScopeTables),{errorMessage:b,refetch:N,data:A}=s.useDashboardCardQuery(k),{setTriggerAIRun:w,setCurrentAssitantScope:P,setCardConfig:I}=s.useEditorActions(),{selectedDatamodelName:T,connectionType:y,selectedDatamodelId:M}=s.useEditorAside(),F=(me=s.useDashboardQuery().data)==null?void 0:me.assistantProfileId,{messages:z,setMessages:$,regenerate:O,error:G,sendMessage:R,status:_,addToolResult:J,stop:se,clearError:Z}=s.useChat({transport:new s.DefaultChatTransport({api:`${c.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${i==null?void 0:i.accessToken}`}),body:()=>{const q=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:F,isDevMode:d,aiContext:q.currentAIContext,reasoningEffort:q.reasoningEffort,showReasoning:q.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:q,body:W})=>({body:{...W,messages:s.cleanupIncompleteMessages(q)}})}),onError:q=>{var W;if(q.name==="AbortError"||(W=q.message)!=null&&W.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",q)},onToolCall:ae,onFinish({isAbort:q,isDisconnect:W,isError:de}){n(""),console.log(q?"[Editor Assistant] Stream aborted by user":W?"[Editor Assistant] Stream disconnected (network error)":de?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});S.useEffect(()=>{D&&v&&(R({role:"user",parts:[{type:"text",text:v}]}),w(!1))},[D,v,R,w]);async function ae({toolCall:q}){var W,de,pe,fe,ce,V,ee,X,je,ge,be,ve,he,Ee,Se,we;if(["createChartFromSql","createForecast"].includes(q.toolName)){const Q=((W=q.input)==null?void 0:W.sql)??((de=q.args)==null?void 0:de.sql),ne=((pe=q.input)==null?void 0:pe.python)??((fe=q.args)==null?void 0:fe.python),le=((ce=q.input)==null?void 0:ce.chartType)??((V=q.args)==null?void 0:V.chartType);p(le),x(Q),m(ne),h(!0),J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(q.toolName==="getUserSql"){if(!o){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",message:"No SQL found"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",sql:o,python:u||""}})}else if(q.toolName==="generateQueryConfig"){n("Generating query config...");const Q=((ee=q.input)==null?void 0:ee.chartType)??((X=q.args)==null?void 0:X.chartType),ne=((je=q.input)==null?void 0:je.queryConfig)??((ge=q.args)==null?void 0:ge.queryConfig);((be=q.input)==null?void 0:be.cardConfig)??((ve=q.args)==null||ve.cardConfig),p(Q),I(ne),x(void 0),m(void 0);const le=await N();if((he=le==null?void 0:le.data)!=null&&he.error){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"error",queryConfig:ne,message:(Ee=le==null?void 0:le.data)==null?void 0:Ee.error.message}});return}if((Se=le==null?void 0:le.data)!=null&&Se.records){J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized"}});return}J({tool:q.toolName,toolCallId:q.toolCallId,output:{status:"success",queryConfig:ne,message:"The data has been visualized",records:(we=le==null?void 0:le.data)==null?void 0:we.records}})}else n("Analyzing...")}function Y(q){const W=s.removeFromScopeArray(g,q);U(W)}function U(q){const W=s.sanitizeAIScope(q);P(W),$(de=>[...de,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(W)}`}]}])}function te(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelId:M||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||""},W=s.dedup([...g,q]);U(W)}function H(){const q={databaseName:B||"",schemaName:C||"",tableName:L||"",datamodelName:s.resolveDatamodelName(T),connectionId:E||"",connectionType:y||"",datamodelId:M||""};if(!s.isInAiScopeArray([...f||[],...g],q)||g.length===0){const de=s.dedup([...f||[],...g,q]).filter(pe=>pe.connectionId===q.connectionId);U(de)}}const re=!["ready","error"].includes(_),ue=s.getErrorMessage(G);return{messages:z,setMessages:$,sendMessage:R,regenerate:O,isLoading:re,handleSetAIScope:H,handleAddCurrentTableToScope:te,removeFromCurrentSelections:Y,currentAssitantScope:g,setCurrentAssitantScope:P,stop:se,status:_,toolStatus:a,llmUsage:r,onFinish:t,errorMessage:ue,clearError:Z}}const Yn=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Cs({isFullscreen:t,onFullscreenChange:a,fullscreenContainer:n}){const r=S.useRef(null),[l,i]=S.useState(!1),[c,o]=S.useState(s.isDevEnv),[d,u]=S.useState(!1),[m,x]=S.useState(!1),[h,p]=S.useState(!1),j=t??h,g=s.useCurrentAIContext(),{setCurrentAIContext:v}=s.useAIActions(),{clearQueue:D}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),B=s.useFileAttachments("editor"),L=s.useDashboardStore(Q=>Q.dashboard.aiContext),E=s.useEditorStore(Q=>Q.card.dataSource),C=s.useEditorStore(Q=>Q.actions.setCardSql),f=s.useEditorStore(Q=>Q.actions.setRunSql),b=s.useEditorStore(Q=>Q.showAIDialog),N=s.useDashboardStore(Q=>Q.handleOpenAssistantProfile),{setShowAIDialog:A,setCardPython:w}=s.useEditorActions(),{setDataSource:P}=s.useEditorActions(),{assistantProfile:I}=s.useAssistantProfile(),{messages:T,setMessages:y,sendMessage:M,isLoading:F,stop:z,status:$,llmUsage:O,errorMessage:G,clearError:R}=Wn(),[_,J]=S.useState(""),se=Q=>{J(Q.target.value)},Z=Q=>{Q.preventDefault();const ne=_.trim();if(!ne&&B.length===0)return;const le=[];ne&&le.push({type:"text",text:ne}),B.forEach(De=>{De.data&&le.push({type:"file",mediaType:De.type,filename:De.name,url:`data:${De.type};base64,${De.data}`})}),M({role:"user",parts:le}),J(""),k("editor"),W({force:!0})},{visibleMessages:ae,hasMoreMessages:Y,totalMessageCount:U,loadMoreMessages:te,resetMessageWindow:H}=s.useMessageWindow(T,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:re,isAtBottom:ue,hasNewMessages:me,newMessageCount:q,scrollToBottom:W,handleScroll:de,resetNewMessageCount:pe}=s.useAutoScroll(ae,{threshold:50,behavior:"smooth",isStreaming:F});S.useEffect(()=>{var Q;b&&((Q=r.current)==null||Q.focus(),v({selectedEntities:(E==null?void 0:E.selectedEntities)||[]}))},[b,E,v]),s.useAutoSubmitQueue({assistantType:"editor",status:$,isLoading:F,sendMessage:M});const{hasActiveTools:fe}=s.useActiveToolStatus(T),ce=S.useCallback(Q=>{a==null||a(Q),t===void 0&&p(Q)},[t,a]);S.useEffect(()=>{if(!j)return;function Q(ne){ne.key==="Escape"&&ce(!1)}return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[j,ce]);const V=S.useCallback(Q=>{M({role:"user",parts:[{type:"text",text:Q}]}),W({force:!0})},[M,W]),ee=S.useCallback(async()=>{const Q=JSON.stringify(T??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Q),s.ue.success("Conversation copied")}catch(ne){console.error("Failed to copy conversation",ne),s.ue.error("Unable to copy conversation")}},[T]),X=S.useCallback(()=>{ce(!j)},[j,ce]);function je(Q,ne){ne==="sql"?(C(Q),f(!0)):ne==="python"&&(w(Q),f(!0))}function ge(){g.selectedEntities.length===0&&v({selectedEntities:(L==null?void 0:L.selectedEntities)||[]})}function be(Q){ge();const ne={role:"user",parts:[{type:"text",text:Q.title+" "+Q.subtitle}]};M(ne)}function ve(Q){ge(),M({role:"user",parts:[{type:"text",text:Q}]})}function he(){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:l,onCheckedChange:i,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:o,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:u,children:"System Message"})]})]})}function Ee(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const Se=(_==null?void 0:_.length)===0&&(T==null?void 0:T.filter(Q=>Q.role==="user").length)===0,we=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",j&&"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:[Ee(),N&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:N,children:(I==null?void 0:I.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[he(),c&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:ee,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:j?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:X,children:j?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:()=>{y([]),D("editor"),R(),H()},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:()=>{A(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:re,className:"mt-2 flex w-full grow basis-0",onScroll:de,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Y&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:te,className:"text-xs",children:["Load ",Math.min(5,U-ae.length)," ","more messages (",U-ae.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:ae,showTools:c,handleRun:je,showSystemMessage:d,onQuickReply:V,disableQuickReplies:F}),!fe&&e.jsx(s.AssistantStatus,{status:$,errorMessage:G})]})}),b&&!ue&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{W({force:!0}),pe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),me&&q>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:q>9?"9+":q})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[Se&&!I&&e.jsx(s.Placeholders,{onClick:be,placeholders:Yn}),e.jsx("div",{children:Se&&I&&e.jsx(s.SeedQuestions,{seedQuestions:I.seedQuestions||[],handleSeedQuestionClick:ve})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:J,stop:z,input:_,handleInputChange:se,handleSubmit:Q=>{ge(),Z(Q),W({force:!0})},isLoading:F,status:$,assistantType:"editor",onFocus:()=>{}})]}),O&&l&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",O.inputTokens," prompt tokens, ",O.outputTokens," ","completion tokens, ",O.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(E==null?void 0:E.selectedEntities)||[],open:m,onOpenChange:x,dataSource:E||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return j&&n?gt.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:we})}),n):we}function $e(t,a){const[n,r]=S.useState(()=>{const l=localStorage.getItem(t);return l?JSON.parse(l):a});return S.useEffect(()=>{localStorage.setItem(t,JSON.stringify(n))},[n,t]),[n,r]}const Xn="chart-selector-standard-first";function Zn(){const[t,a]=$e(Xn,!0);return{standardFirst:t,updatePreference:a}}const Ss=({pluginVisual:t,index:a,onSelect:n})=>{const r=Ge(t.icon||""),l=t.name.charAt(0).toUpperCase(),i=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:n,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):i||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:l}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${a}`)},ws=["default","standardPlugin","customPlugin"];function er({selectedChart:t,onChartChange:a}){var E;const[n,r]=S.useState(!1),{data:l}=Qs();Zn();const c=((E=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:E.url)||"";Xe(c);const{setCardType:o,setCardPreferences:d,setIsDevMode:u}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:m,setCustomCardPreferences:x,setQueryConfig:h}=s.useEditorActions(),[p,j]=$e("chart-section-active",null),g=S.useMemo(()=>p?[p,...ws.filter(C=>C!==p)]:ws,[p]);function v(C){m(null),d({}),o(C),["custom","map"].includes(C)&&(u(!0),h(void 0)),a(C),r(!1)}function D(C){m(null),d({}),o("custom"),x({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),h(void 0),a("custom"),r(!1)}const k=S.useMemo(()=>s.chartTypes.some(f=>f.id==="bullet")?s.chartTypes:[...s.chartTypes,{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"}],[]),B=()=>{var f;if(t==="custom"){const b=s.useEditorStore.getState().card;return((f=b==null?void 0:b.customCardPreferences)==null?void 0:f.componentName)||"Custom Visual"}const C=k.find(b=>b.id===t);return(C==null?void 0:C.label)||"Select chart type"},L=()=>{var f,b;if(t==="custom"){const N=s.useEditorStore.getState().card,A=(f=N==null?void 0:N.customCardPreferences)==null?void 0:f.icon,w=(b=N==null?void 0:N.customCardPreferences)==null?void 0:b.componentName;if(A&&w)return e.jsx(sr,{icon:A,componentName:w});if(w){const P=s.getAutoDetectedChartIcon(w);if(P)return P}return e.jsx(Ae,{className:"h-4 w-4"})}const C=k.find(N=>N.id===t);if(C){const N=C.icon;return e.jsx(N,{className:"h-4 w-4"})}return e.jsx(Ae,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:n,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[L(),e.jsx("span",{children:B()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),g.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="default",onCheckedChange:f=>j(f?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:k.map(f=>{const b=f.icon;return e.jsx(s.CommandItem,{value:`${f.label} ${f.id} chart graph visualization`,onSelect:()=>v(f.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b,{className:"h-4 w-4"}),e.jsx("span",{children:f.label})]})},f.id)})},"default");if(C==="standardPlugin"){const f=l.filter(b=>b.pluginType==="standard");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="standardPlugin",onCheckedChange:b=>j(b?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.filter(b=>b.componentType==="chart").map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"standardPlugin"):null}if(C==="customPlugin"){const f=l.filter(b=>b.pluginType==="custom");return f.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:p==="customPlugin",onCheckedChange:b=>j(b?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:f.map((b,N)=>e.jsx(Ss,{pluginVisual:b,index:N,onSelect:()=>D(b)},`${b.url}-${b.name}-${N}`))},"customPlugin"):null}return null})]})]})})]})})}const sr=({icon:t,componentName:a})=>{const n=Ge(),r=s.getAutoDetectedChartIcon(a);return n?e.jsx(n,{className:"h-4 w-4"}):r||e.jsx(Ae,{className:"h-4 w-4"})},tr=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!1},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"},{id:"treemap",icon:s.TbChartTreemap,label:"Treemap"},{id:"bullet",icon:s.BulletChartIcon,label:"Bullet Chart"},{id:"funnel",icon:s.TbChartFunnel,label:"Funnel Chart"},{id:"tornado",icon:s.Tornado,label:"Tornado Chart"},{id:"heatmap",icon:s.Grid3x3,label:"Heatmap"},{id:"range",icon:s.ChartNoAxesGantt,label:"Range Chart"}];function ar({selectedChart:t,onChartChange:a,isDropdownExpanded:n,onToggleDropdown:r}){var o;const l=s.useEditorStore(d=>d.card),i=((o=l==null?void 0:l.config)==null?void 0:o.pivotByColumns)&&l.config.pivotByColumns.length>0,c=tr.filter(d=>!(d.requiresPivot&&!i));return e.jsxs("div",{className:"grid grid-cols-7 gap-2",children:[c.map(d=>{const u=d.icon,m=t===d.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>a(d.id),className:s.cn("h-8 w-8 p-0",m&&"bg-accent text-accent-foreground"),children:[e.jsx(u,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:d.label})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:d.label}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]},d.id)}),r&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0","aria-label":n?"Hide all charts":"Show all charts",children:n?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsxs(s.TooltipContent,{side:"bottom",className:"border-foreground/20 bg-foreground text-background",children:[e.jsx("p",{children:n?"Hide dropdown":"Show all charts"}),e.jsx(s.TooltipArrow,{className:"fill-foreground"})]})]})]})}const ls=({dataType:t})=>s.getFieldIconComponent(t);function nr({aliasTemplate:t,onAliasTemplateChange:a}){var d;const[n,r]=S.useState(t),[l,i]=S.useState(!1),c=(d=s.useEditorStore(u=>{var m;return(m=u.card.config)==null?void 0:m.pivotByColumns}))==null?void 0:d[0],o=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(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:o,value:l?n:t,onChange:u=>{r(u.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:u=>u.stopPropagation(),className:"h-8 text-xs",onKeyDown:u=>{u.key==="Enter"&&l&&n!==t?(a(n),i(!1)):u.key==="Escape"&&(r(t),i(!1))},"aria-label":"Edit alias template"}),l&&n!==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:()=>{a(n),i(!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),i(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function rr({valueAliases:t,onValueAliasesChange:a}){const[n,r]=S.useState(null),[l,i]=S.useState(""),[c,o]=S.useState(""),d=()=>{a({...t,"":""})},u=x=>{const h={...t};delete h[x],a(h)},m=x=>{const h={...t};delete h[x],h[l]=c,a(h),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(([x,h],p)=>e.jsx("div",{className:"flex items-center gap-2",children:n===x?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:l,onChange:j=>i(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:c,onChange:j=>o(j.target.value),className:"h-8 w-24 text-xs",onPointerDown:j=>j.stopPropagation(),onKeyDown:j=>{j.key==="Enter"?m(x):j.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:()=>m(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 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:x,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:h,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(x),i(x),o(h)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(x),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},x+p)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:d,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function lr({column:t}){const a=s.useEditorStore(d=>d.card.type),n=s.useEditorStore(d=>{var u,m;return(m=(u=d.card)==null?void 0:u.config)==null?void 0:m.metricColumns}),r=(n==null?void 0:n.map(d=>d.label))||[],l=r==null?void 0:r.find(d=>d===t.label||d===t.name),i=l?r.indexOf(l):-1;function c(){return e.jsx("div",{className:"pr-1",children:l&&e.jsx(et,{idx:i,col:l,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function o(){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(st,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&o()]})}function or({field:t,searchQuery:a="",limit:n=500}){const{authToken:r,tokenProps:l}=s.useSemaphorContext(),i=s.useEditorStore(u=>u.card),c=i==null?void 0:i.dataSource,o=["attribute-values",t.entityName,t.name,a,n],d=s.useQuery({queryKey:o,queryFn:async()=>{if(!(c!=null&&c.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const u={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:a?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:a}],groups:[]}:void 0,rowLimit:n},m={connection_id:c.connectionId,cardConfig:u,cardDataSource:c,cache_config:s.getCacheConfig({card:i})};console.log("requestBody",m);const x=await s.postRequestRegular(`${l.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",m);if(x!=null&&x.error)return console.error("Error fetching attribute values:",x.error),[];const h=t.name;return((x==null?void 0:x.records)||[]).map(j=>{const g=j[h]||j[t.alias||h]||j[t.label];return{id:g||"",value:g||"",label:String(g||"(empty)")}})}catch(u){return console.error("Error fetching attribute values:",u),[]}},enabled:!!t&&!!(c!=null&&c.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:d.data||[],isLoading:d.isLoading,isFetching:d.isFetching,isError:d.isError,error:d.error,refetch:d.refetch}}function ir({open:t,onOpenChange:a,availableFields:n,existingFilters:r,editingCondition:l,onSave:i}){var B,L;const c=!!l,[o,d]=S.useState(c?"values":"fields"),[u,m]=S.useState(""),[x,h]=S.useState({id:(l==null?void 0:l.id)||s.v4(),field:(l==null?void 0:l.field)||null,selectedValues:l?Array.isArray(l.value)?l.value:[l.value]:[]}),p=n.filter(E=>{var f;return c?!1:!((f=r==null?void 0:r.conditions)==null?void 0:f.some(b=>b.field.id===E.id))&&E.label.toLowerCase().includes(u.toLowerCase())}),j=E=>{h({...x,field:E}),d("values")},g=()=>{if(x.field&&x.selectedValues.length>0){const E={id:x.id,field:x.field,operator:"in",value:x.selectedValues};let C;if(c){const f=((r==null?void 0:r.conditions)||[]).map(b=>b.id===l.id?E:b);C={...r,conditions:f}}else{const f=(r==null?void 0:r.conditions)||[];C={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...f,E],groups:[]}}i(C),a(!1)}},v=()=>{if(!c||!l)return;const E=((r==null?void 0:r.conditions)||[]).filter(C=>C.id!==l.id);if(E.length>0){const C={...r,conditions:E};i(C)}else i(void 0);a(!1)},D=E=>{h({...x,selectedValues:E})},k=()=>{c&&l?(h({id:l.id,field:l.field,selectedValues:Array.isArray(l.value)?l.value:[l.value]}),d("values")):(h({id:s.v4(),field:null,selectedValues:[]}),d("fields")),m("")};return S.useEffect(()=>{t&&k()},[t,c,l]),e.jsx(s.Dialog,{open:t,onOpenChange:a,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:c?`Edit Filter: ${(B=x.field)==null?void 0:B.label}`:o==="fields"?"Select Field to Filter":`Select Values for ${(L=x.field)==null?void 0:L.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!c&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&o==="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(E=>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:[E.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(E.value)?`${E.value.length} values`:String(E.value)})]},E.id))})]}),o==="fields"&&!c?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:u,onChange:E=>m(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:p.map(E=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>j(E),children:[e.jsx(ls,{dataType:s.getDataType(E.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:E.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[E.entityName,".",E.name]})]})]},E.id))}),p.length===0&&u&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',u,'"']}),p.length===0&&!u&&n.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(cr,{field:x.field,selectedValues:x.selectedValues,onValuesChange:D,onBack:c?void 0:()=>d("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:c?e.jsx(s.Button,{variant:"destructive",onClick:v,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:g,disabled:!x.field||x.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function cr({field:t,selectedValues:a,onValuesChange:n,onBack:r}){const[l,i]=S.useState(""),{values:c,isLoading:o,isFetching:d}=or({field:t,searchQuery:l,limit:500}),u=l?c.filter(h=>String(h.value).toLowerCase().includes(l.toLowerCase())):c,m=h=>{const p=a.includes(h);n(p?a.filter(j=>j!==h):[...a,h])},x=()=>{a.length===u.length&&u.length>0?n([]):n(u.map(h=>h.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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:l,onChange:h=>i(h.target.value),className:"pl-10"})]}),o||d?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:a.length===u.length&&u.length>0,onCheckedChange:x}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",u.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:u.map(h=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>m(h.value),children:[e.jsx(s.Checkbox,{checked:a.includes(h.value),onCheckedChange:()=>m(h.value)}),e.jsx(ns,{className:"text-sm",children:h.label})]},h.id))})]})]})}function dr({field:t,zone:a,index:n,sortDirection:r,onSortDirectionChange:l,hasPivotColumns:i=!1,cardType:c}){var is,cs,ds,us;const{attributes:o,listeners:d,setNodeRef:u,transform:m,transition:x,isDragging:h}=s.useSortable({id:t.id}),p=s.useEditorStore(K=>K.card),{updateLabel:j,handleAggregationChange:g,handleDateFormatChange:v,handleGranularityChange:D,handleAliasTemplateChange:k,handleValueAliasesChange:B,removeField:L,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:C,handleKpiTrendlineWindowChange:f,handleKpiTrendlineGranularityChange:b,handleKpiTargetValueChange:N}=ss(p),[A,w]=S.useState(!1),[P,I]=S.useState(!1),[T,y]=S.useState(null),[M,F]=S.useState(t.dateFormat||"YYYY-MM-DD"),[z,$]=S.useState(t.customFormat||""),[O,G]=S.useState(!!t.customFormat),[R,_]=S.useState(t.granularity||"day"),[J,se]=S.useState(t.aliasTemplate||""),[Z,ae]=S.useState(t.valueAliases||{}),[Y,U]=S.useState((is=t.parameters)==null?void 0:is.filters),te=K=>{K==="custom"?G(!0):(G(!1),F(K),a==="groupBy"&&v(n,K,""))},H=K=>{$(K),a==="groupBy"&&v(n,"custom",K)},re=K=>{var xe;_(K);const ie=(xe=s.getDateFormatOptionsForGranularity(K)[0])==null?void 0:xe.value;ie&&!O&&(F(ie),a==="groupBy"&&v(n,ie,"")),a==="groupBy"&&D(n,K)},ue=K=>{se(K),a==="metrics"&&k(n,K)},me=K=>{ae(K),a==="metrics"&&B(n,K)},q=K=>{j(a,n,K)},W=K=>{var oe;if(U(K),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:K}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}I(!1)},de=()=>{L(a,n)},pe={transform:s.CSS.Transform.toString(m),transition:x},fe=s.getDataType(t.dataType),ce=fe==="date",V=c==="kpi",ee=s.getDateFormatOptionsForGranularity(R),X=a!=="pivotBy",je=ce&&a==="groupBy"&&(!V||((cs=p.config)==null?void 0:cs.comparisonType)==="start_vs_end"),ge=!V&&ce&&a==="groupBy",be=c&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(c)&&ce&&a==="groupBy",ve=c==="kpi"&&ce&&a==="groupBy",he=c&&c!=="pivotTable"&&a==="metrics"&&((ds=p.config)==null?void 0:ds.comparisonType)==="target",Ee=a==="metrics",Se=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:K=>{K.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}`}),we=()=>X?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(Ne,{value:t.label??"",onSave:q,placeholder:"Display label...",type:"text"})]}):null,Q=()=>je?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:R,onValueChange:re,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,ne=()=>ge?e.jsxs(e.Fragment,{children:[Q(),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:O?"custom":M,onValueChange:te,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:ee.map(K=>e.jsx(s.SelectItem,{className:"text-xs",value:K.value,children:K.label},K.value))})]}),O&&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(),H(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,le=()=>{var ie,xe,Ce,Le,ms;const K=be,oe=ve;return!K&&!oe?null:e.jsxs(e.Fragment,{children:[K&&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:((ie=p.config)==null?void 0:ie.comparisonType)||"none",onValueChange:E,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"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),oe&&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:((xe=p.config)==null?void 0:xe.showTrendline)||!1,onCheckedChange:C})]})}),((Ce=p.config)==null?void 0:Ce.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:((Le=p.config)==null?void 0:Le.trendlineWindow)||30,onChange:pt=>{const ft=parseInt(pt.target.value)||30;f(ft)},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:((ms=p.config)==null?void 0:ms.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"})]})]})]})]})]})]})},De=()=>{var K,oe;return he?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(Ne,{value:((K=p.config)==null?void 0:K.targetValue)!==void 0&&((oe=p.config)==null?void 0:oe.targetValue)!==null?String(p.config.targetValue):"",onSave:ie=>{!isNaN(Number(ie))&&ie!==null?N(Number(ie)):N(0)},placeholder:"Enter target value...",type:"text"})]}):null},mt=()=>Ee?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:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:K=>{g(n,K)},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"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Y==null?void 0:Y.conditions)&&Y.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Y.conditions.map(K=>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:()=>{y(K),I(!0)},children:[e.jsxs("span",{className:"font-medium",children:[K.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(K.value)?K.value.length===1?String(K.value[0]):K.value.length<=2?K.value.join(", "):`${K.value.slice(0,2).join(", ")} +${K.value.length-2}`:String(K.value)})}),Array.isArray(K.value)&&K.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 (",K.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:K.value.map((oe,ie)=>e.jsx("div",{children:String(oe)},ie))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:oe=>{var xe;oe.stopPropagation();const ie=Y.conditions.filter(Ce=>Ce.id!==K.id);if(ie.length>0){const Ce={...Y,conditions:ie};W(Ce)}else if(U(void 0),a==="metrics"){const Ce={...t,parameters:{...t.parameters,filters:void 0}},Le=[...((xe=p.config)==null?void 0:xe.metricColumns)||[]];Le[n]=Ce,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:Le})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},K.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{y(null),I(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(lr,{column:t}),i&&e.jsxs(e.Fragment,{children:[e.jsx(nr,{aliasTemplate:J,onAliasTemplateChange:ue}),e.jsx(rr,{valueAliases:Z,onValueAliasesChange:me})]})]}):null,{columns:ht=[]}=s.useColumns(),xt=(Y==null?void 0:Y.conditions)&&Y.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:u,style:pe,...o,...d,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 ${h?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(ls,{dataType:fe}),e.jsx(ns,{className:s.cn("w-[140px] flex-1 text-sm",xt&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),a==="metrics"&&((us=Y==null?void 0:Y.conditions)==null?void 0:us.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:Y.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Y.conditions.map(K=>e.jsxs("div",{children:[K.field.label,":"," ",Array.isArray(K.value)?`${K.value.length} values`:String(K.value)]},K.id))})})]})}),a!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),w(!A)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${A?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:K=>{K.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const oe=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",oe),l(oe)},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(),de()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),A&&e.jsxs("div",{className:"space-y-3",children:[Se(),we(),c==="kpi"&&Q(),ne(),le(),De(),mt()]})]}),P&&e.jsx(ir,{open:P,onOpenChange:K=>{I(K),K||y(null)},availableFields:ht,existingFilters:Y,editingCondition:T,onSave:K=>{var oe;if(K)W(K);else if(U(void 0),a==="metrics"){const ie={...t,parameters:{...t.parameters,filters:void 0}},xe=[...((oe=p.config)==null?void 0:oe.metricColumns)||[]];xe[n]=ie,s.useEditorStore.getState().actions.updateCardConfig(p.id,{metricColumns:xe})}y(null)}})]})}function ur({concept:t}){const a=()=>{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"})]})]})]});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:a()})]})})}function Ve({zone:t,fields:a,label:n,placeholder:r,shouldShow:l,hasPivotColumns:i=!1,activeField:c=null}){const{isOver:o,setNodeRef:d}=s.useDroppable({id:t}),{updateSortByColumn:u}=s.useEditorActions(),m=s.useEditorStore(v=>v.card),x=s.useEditorStore(v=>v.card.type),h=a.length>0,p=S.useMemo(()=>!c||!o?!0:Fe(c,t,x).isValid,[c,o,t,x]),j=(v,D)=>{var B;!((B=m.config)!=null&&B.sortByColumns)||m.config.sortByColumns.findIndex(L=>L.id===v)===-1||u(m.id,v,{direction:D})};if(t==="sortBy"&&l===!1)return null;const g=t!=="sortBy"&&x!=="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:n}),g&&e.jsx(ur,{concept:t})]}),e.jsx("div",{ref:d,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":o&&p,"border-red-500 bg-red-50 dark:bg-red-950":o&&!p,"border-muted-foreground/30 bg-muted/40":!o&&h,"min-h-[60px] border-muted-foreground/20 bg-background":!o&&!h}),children:a.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,{items:a.map(v=>v.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map((v,D)=>{const B=v.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(dr,{field:v,zone:t,index:D,sortDirection:B,onSortDirectionChange:L=>j(v.id,L),hasPivotColumns:i,cardType:x})})},v.id)})})})})]})}const Ds={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%
|
|
240
|
+
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 mr(){var h,p,j,g,v,D,k,B,L,E,C;const t=s.useEditorStore(f=>f.card),{setCardPreferences:a}=s.useEditorActions(),n=((h=t.config)==null?void 0:h.metricColumns)||[],r=((p=t.config)==null?void 0:p.groupByColumns)||[],l=n.length===2&&r.length===0,i=n.length>=1&&r.length>0;if(!(t.type==="kpi"&&(l||i)))return null;const o=((g=(j=t.preferences)==null?void 0:j.kpiVisualOptions)==null?void 0:g.metricComparison)||{},d=f=>{var N;const b={...t.preferences,kpiVisualOptions:{...(N=t.preferences)==null?void 0:N.kpiVisualOptions,metricComparison:{...o,...f}}};a(b)},u=i||o.enabled,m=((v=t.config)==null?void 0:v.comparisonType)||"none",x=m==="previous_period"||m==="same_period_last_year"||m==="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(At,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[l&&n.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:o.enabled||!1,onCheckedChange:f=>d({enabled:f,...f&&!o.calculationType?{calculationType:"difference"}:{}})})]}),u&&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=o.calculationType||"difference",b=Ds[f];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:b==null?void 0:b.label}),e.jsx("p",{children:b==null?void 0:b.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:b==null?void 0:b.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",b==null?void 0:b.example]})]})})()})]})]}),e.jsxs(s.Select,{value:o.calculationType||"difference",onValueChange:f=>d({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(Ds).map(([f,b])=>e.jsx(s.SelectItem,{value:f,className:"text-xs",children:b.label},f))})]})]}),e.jsx(rs,{formatOptions:o.formatOptions||{},onFormatOptionsChange:f=>d({formatOptions:f}),showTitle:!0,title:"COMPARISON FORMAT"}),(x||l)&&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"}),l&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:o.position||"right",onValueChange:f=>d({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:o.showArrow!==!1,onCheckedChange:f=>d({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:o.showColor!==!1,onCheckedChange:f=>d({showColor:f})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),o.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Pe,{value:((D=o.colorConfig)==null?void 0:D.increase)||"green",onChange:f=>d({colorConfig:{...o.colorConfig,increase:f}}),label:"Primary > Secondary"}),e.jsx(Pe,{value:((k=o.colorConfig)==null?void 0:k.decrease)||"red",onChange:f=>d({colorConfig:{...o.colorConfig,decrease:f}}),label:"Primary < Secondary"}),e.jsx(Pe,{value:((B=o.colorConfig)==null?void 0:B.noChange)||"neutral",onChange:f=>d({colorConfig:{...o.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:o.conditionalLabel||!1,onCheckedChange:f=>d({conditionalLabel:f})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),o.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((L=o.conditionalLabels)==null?void 0:L.increase)??"Increase",onChange:f=>d({conditionalLabels:{...o.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:((E=o.conditionalLabels)==null?void 0:E.decrease)??"Decrease",onChange:f=>d({conditionalLabels:{...o.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:((C=o.conditionalLabels)==null?void 0:C.noChange)??"No change",onChange:f=>d({conditionalLabels:{...o.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:o.labelName??"",onChange:f=>d({labelName:f.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function hr(){var l,i;const t=s.useEditorStore(c=>c.card),{setCardPreferences:a}=s.useEditorActions();if(t.type!=="kpi")return null;const n=((i=(l=t.preferences)==null?void 0:l.kpiVisualOptions)==null?void 0:i.formatOptions)||{},r=c=>{var d;const o={...t.preferences,kpiVisualOptions:{...(d=t.preferences)==null?void 0:d.kpiVisualOptions,formatOptions:c}};a(o)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(rs,{formatOptions:n,onFormatOptionsChange:r,showTitle:!1})})]})}function xr(){var i;const t=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.type}),a=s.useEditorStore(c=>{var o;return(o=c.card)==null?void 0:o.preferences}),{setCardPreferences:n}=s.useEditorActions();if(t!=="treemap")return null;const r=((i=a==null?void 0:a.chartOptions)==null?void 0:i.treemapColorMode)??"branch",l=c=>{const o={...a||{},chartOptions:{...a==null?void 0:a.chartOptions,treemapColorMode:c}};n(o)};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:c=>l(c??"branch"),className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border px-3 py-2",children:[e.jsx(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."})]})]})]})})]})}function pr({groupByFields:t,pivotByFields:a,metricsFields:n,sortByFields:r,activeField:l}){const i=s.useEditorStore(v=>{var D;return((D=v.card.customCardPreferences)==null?void 0:D.url)&&v.card.type==="custom"}),c=s.useEditorStore(v=>v.card),o=c==null?void 0:c.type,d=t.length>0||n.length>0,u=o!=="kpi"||n.length<=2,m=o!=="kpi",x=o!=="kpi"&&d,h=["pie","doughnut","polar","funnel","aggregateTable"].includes(o),p=m&&!h,j=()=>o==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},g=()=>o==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Columns",placeholder:"Drop fields to measure"};return 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:[u&&e.jsx(Ve,{zone:"groupBy",fields:t,label:j().label,placeholder:j().placeholder,activeField:l}),p&&e.jsx(Ve,{zone:"pivotBy",fields:a,label:"Pivot Columns",placeholder:"Drop fields to pivot data",activeField:l}),e.jsx(Ve,{zone:"metrics",fields:n,label:g().label,placeholder:g().placeholder,hasPivotColumns:a.length>0,activeField:l}),x&&e.jsx(Ve,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:l})]})]}),!i&&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:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(hr,{}),e.jsx(mr,{}),e.jsx(at,{}),e.jsx(xr,{}),e.jsx(it,{}),o==="bullet"&&e.jsx(ot,{}),e.jsx(nt,{}),e.jsx(rt,{}),e.jsx(lt,{})]})})]})]})}function fr({onEditJoins:t}){const a=s.useEditorStore(o=>o.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(a);if(!(n!=null&&n.autoResolved))return null;const{resolvedJoinPlan:r}=n,l=(r==null?void 0:r.joins)||[];if(l.length===0)return null;const i=o=>!o||o.length===0?"No conditions":o.map(d=>{var h,p,j,g;const u=`${(h=d.source)==null?void 0:h.entityName}.${(p=d.source)==null?void 0:p.name}`,m=`${(j=d.target)==null?void 0:j.entityName}.${(g=d.target)==null?void 0:g.name}`,x=d.operator||"=";return`${u} ${x} ${m}`}).join(" AND "),c=o=>!o.joinKeyGroups||o.joinKeyGroups.length===0?"No conditions defined":o.joinKeyGroups.length===1?i(o.joinKeyGroups[0].keys):o.joinKeyGroups.map((d,u)=>({id:u,operator:d.operator,condition:i(d.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(Xt,{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:"Auto-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:l.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:l.map((o,d)=>{const u=c(o),m=Array.isArray(u);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:o.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:o.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:o.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:m?u.map(x=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:x.condition}),x.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",x.operator,")"]})]},x.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:u})})})]},o.id||d)})})})]})})]}),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 Ts={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(a){return console.warn(`Failed to read from localStorage (${t}):`,a),null}},setItem(t,a){if(!(typeof window>"u"))try{localStorage.setItem(t,a)}catch(n){console.warn(`Failed to write to localStorage (${t}):`,n)}}};function gr({selectedChart:t,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c}){var f,b;const[o,d]=S.useState(()=>Ts.getItem("chart-selector-expanded")==="true"),[u,m]=S.useState(!1),x=s.useEditorStore(N=>N.card),h=s.useEditorStore(N=>N.actions.updateCardConfig),p=n.length>0||r.length>0||l.length>0,{data:j,autoJoinMetadata:g}=s.useDashboardCardQuery(x),v=((f=x==null?void 0:x.config)==null?void 0:f.joinPlan)||(g!=null&&g.autoResolved?g.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),D=((b=x==null?void 0:x.dataSource)==null?void 0:b.selectedEntities)||[],k=N=>{h(x.id,{...x==null?void 0:x.config,joinPlan:N}),m(!1)},B=()=>{h(x.id,{...x==null?void 0:x.config,joinPlan:void 0}),m(!1)},L=()=>{m(!1)},E=()=>{m(!0)};S.useEffect(()=>{Ts.setItem("chart-selector-expanded",String(o))},[o]);const C=()=>{d(N=>!N)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":o}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",o?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:o&&e.jsx(er,{selectedChart:t,onChartChange:a})}),e.jsx("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center",children:e.jsx(ar,{selectedChart:t,onChartChange:a,isDropdownExpanded:o,onToggleDropdown:C})})]}),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:p||j}),children:e.jsx(Ze,{})})}),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(fr,{onEditJoins:E}),e.jsx(pr,{groupByFields:n,pivotByFields:r,metricsFields:l,sortByFields:i,activeField:c})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(We,{open:u,onOpenChange:m,joinPlan:v,availableDataSources:D,onSave:k,onCancel:L,onRemove:B,children:e.jsx("div",{})})]})}function jr({initialFilters:t,availableFields:a}={}){const[n,r]=S.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(E=>E.card.dataSource);const{columns:l,isLoading:i}=s.useColumns(),o=a||l||[],d={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},u=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,conditions:[...f.conditions,{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},m=E=>{const C=f=>{if(f.id===E){const b=o[0]||d,N=s.getDataType(b.dataType)==="date";return{...f,groups:[...f.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:b,operator:N?"between":"=",value:N?[]:""}],groups:[]}]}}return{...f,groups:f.groups.map(C)}};r(C(n))},x=(E,C)=>{const f=b=>b.id===E?{...b,conditions:b.conditions.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},h=(E,C)=>{const f=b=>b.id===E?{...b,groups:b.groups.filter(N=>N.id!==C)}:{...b,groups:b.groups.map(f)};r(f(n))},p=(E,C,f,b)=>{if(f==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const N=A=>A.id===E?{...A,conditions:A.conditions.map(w=>w.id===C?{...w,[f]:b}:w)}:{...A,groups:A.groups.map(N)};r(N(n))},j=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:N.conditions.map(A=>A.id===C?{...A,...f}:A)}:{...N,groups:N.groups.map(b)};r(b(n))},g=(E,C)=>{const f=b=>b.id===E?{...b,logicalOperator:C}:{...b,groups:b.groups.map(f)};r(f(n))},v=(E,C)=>{const f=b=>b.id===E?{...b,negate:C}:{...b,groups:b.groups.map(f)};r(f(n))},D=(E,C,f)=>{const b=N=>N.id===E?{...N,conditions:s.arrayMove(N.conditions,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},k=(E,C,f)=>{const b=N=>N.id===E?{...N,groups:s.arrayMove(N.groups,C,f)}:{...N,groups:N.groups.map(b)};r(b(n))},B=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const C=b=>{let N="";typeof b.field=="object"?N=b.field.entityName?`${b.field.entityName}.${b.field.name}`:b.field.name:N=String(b.field);const A=b.operator;let w=b.value;if(b.field.dataType==="string"&&!["in","not in"].includes(b.operator))typeof w=="string"?w=`'${w}'`:Array.isArray(w)&&(w=`'${w.join(", ")}'`);else if(b.field.dataType==="date"||b.field.dataType==="datetime"||b.field.dataType==="timestamp")if(b.operator==="between"&&Array.isArray(w)&&w.length===2){const P=w[0]?`'${w[0]}'`:"NULL",I=w[1]?`'${w[1]}'`:"NULL";return`${N} BETWEEN ${P} AND ${I}`}else if((b.operator==="in"||b.operator==="not in")&&Array.isArray(w)){const P=w.map(I=>I?`'${I}'`:"NULL").join(", ");return`${N} ${A} (${P})`}else typeof w=="string"||w instanceof Date?w=`'${w}'`:Array.isArray(w)&&w.length>0&&(w=`'${w[0]}'`);else if(["in","not in"].includes(b.operator)){let P=[];Array.isArray(w)?P=w.map(I=>typeof I=="string"?`'${I}'`:String(I)):typeof w=="string"?P=w.split(",").map(I=>{const T=I.trim();return b.field.dataType==="string"?`'${T}'`:T}):typeof w=="number"&&(P=[String(w)]),w=`(${P.join(", ")})`}switch(A){case"contains":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"startsWith":return typeof w=="string"?`${N} LIKE '${w.replace(/'/g,"")}%'`:`${N} LIKE '${String(w)}%'`;case"endsWith":return typeof w=="string"?`${N} LIKE '%${w.replace(/'/g,"")}'`:`${N} LIKE '%${String(w)}'`;case"isNull":return`${N} IS NULL`;case"isNotNull":return`${N} IS NOT NULL`;default:return`${N} ${A} ${w}`}},f=b=>{const N=b.conditions.map(C),A=b.groups.map(T=>f(T)),w=[...N,...A].filter(Boolean);if(w.length===0)return"";const P=w.join(` ${b.logicalOperator} `),I=w.length>1?`(${P})`:P;return b.negate?`NOT ${I}`:I};return f(E)},L=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:o,isLoading:i,addCondition:u,addGroup:m,removeCondition:x,removeGroup:h,updateCondition:p,updateConditionFields:j,updateGroupOperator:g,updateGroupNegate:v,reorderConditions:D,reorderGroups:k,generateSQLPreview:B,hasAnyFilters:L}}function br({children:t,className:a,delayDuration:n}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:n,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const vr=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},yr=t=>{if(t.qualifiedEntityName){const a=t.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function Nr({value:t,onValueChange:a,availableFields:n,placeholder:r="Select field",className:l="w-64"}){const[i,c]=S.useState(!1),o=S.useMemo(()=>{const d={};return n.forEach(u=>{const m=yr(u);d[m]||(d[m]={}),d[m][u.entityId]||(d[m][u.entityId]=[]),d[m][u.entityId].push(u)}),d},[n]);return e.jsxs(s.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:s.cn("justify-between",!t&&"text-muted-foreground",l),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(br,{children:[t.entityName,".",t.name]})}):r,e.jsx(yt,{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(o).map(([d,u])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),d]}),children:Object.entries(u).map(([m,x])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 bg-gray-50/50 px-2 py-1 text-xs font-medium text-gray-600",children:[vr(x[0].entityType),e.jsx("span",{children:x[0].entityName})]}),x.map((h,p)=>e.jsxs(s.CommandItem,{value:h.id,onSelect:()=>{a(h),c(!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)===h.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:h.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:h.description&&e.jsx("span",{children:h.description})})]})]},h.id+p))]},`${d}-${m}`))},d))})]})})]})}function os(t){var g;const a=s.useEditorStore(v=>v.card),{authToken:n,tokenProps:r}=s.useSemaphorContext(),l=s.useEditorStore(v=>v.card.config),i=l==null?void 0:l.joinPlan,c={...t,alias:t.name,label:"value",role:"groupby"},o={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...c,role:"sortby",direction:"asc"},u={joinPlan:i,groupByColumns:[c],metricColumns:[o],sortByColumns:[d]},m=((g=a.dataSource)==null?void 0:g.connectionId)||a.connectionId,{data:x,isPending:h,error:p}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(n==null?void 0:n.accessToken)||"",{connection_id:m,cardConfig:u,cardDataSource:a.dataSource})}catch(v){console.log(t),console.error("error",v)}},enabled:!!m,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((x==null?void 0:x.records)||[]).map(v=>({label:v.value||"BLANK",value:v.value||"BLANK",count:(v==null?void 0:v.count)||0})),isPending:h,error:p}}function Cr({field:t,selected:a,onChange:n,placeholder:r="Select items...",className:l}){const[i,c]=He.useState(!1),{filterValues:o}=os(t),d=m=>{n(a.filter(x=>x!==m))},u=m=>{a.includes(m)?n(a.filter(x=>x!==m)):n([...a,m])};return e.jsx("div",{className:s.cn("w-full",l),children:e.jsxs(s.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(m=>{const x=o.find(h=>h.value===m);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[x==null?void 0:x.label,e.jsx("div",{className:"ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:h=>{h.key==="Enter"&&d(m)},onMouseDown:h=>{h.preventDefault(),h.stopPropagation()},onClick:h=>{h.stopPropagation(),d(m)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},m)}):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:o.map((m,x)=>e.jsxs(s.CommandItem,{onSelect:()=>u(m.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",a.includes(m.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:m.count})]})]},m.value+x))})]})]})})]})})}function Sr({field:t,value:a,onChange:n,placeholder:r="Select value...",className:l}){const{filterValues:i,isPending:c,error:o}=os(t);return c?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..."]}):o?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:a,onValueChange:n,children:[e.jsx(s.SelectTrigger,{className:l||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:a})}),e.jsx(s.SelectContent,{children:i.map((d,u)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:d.value,children:d.label},d.value+u))})]})}function wr({value:t,operator:a,onChange:n,className:r}){var d;const{tokenProps:l}=s.useSemaphorContext(),i=(d=l==null?void 0:l.params)==null?void 0:d.timeZone,c=S.useMemo(()=>{if(t){if(a==="between"||a==="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(a==="="||a==="!="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:u}}}else if(a===">"||a===">="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:u,to:void 0}}}else if(a==="<"||a==="<="){if(!Array.isArray(t)&&t){const u=new Date(t);if(!isNaN(u.getTime()))return{from:void 0,to:u}}}else if((a==="in"||a==="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,a]),o=u=>{if(!u){n(void 0);return}if(u.from&&u.to)n([u.from.toISOString(),u.to.toISOString()]);else if(u.from){const m=new Date(u.from);m.setHours(23,59,59,999),n([u.from.toISOString(),m.toISOString()])}else if(u.to){const m=new Date(u.to);m.setHours(0,0,0,0),n([m.toISOString(),u.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:c,onChange:o,timezone:i,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const Dr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],Tr=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kr=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Er=["=","!=","isNull","isNotNull"],Ir=["between","isNull","isNotNull"],Ar={"=":"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 ks(t){return Ar[t]||s.titleCase(t)}function Mr(t){switch(t){case"string":return Tr;case"number":return kr;case"boolean":return Er;case"date":return Ir;default:return Dr}}function ct({condition:t,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:l,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:o,updateConditionFields:d}){const{attributes:u,listeners:m,setNodeRef:x,transform:h,transition:p,isDragging:j}=s.useSortable({id:t.id}),{isPending:g,error:v}=os(t.field),D={transform:s.CSS.Transform.toString(h),transition:p};return e.jsxs("div",{ref:x,style:D,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${j?"z-50 opacity-50":""}`,children:[e.jsx("div",{...u,...m,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>c(n,k),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"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(Nr,{value:t.field,onValueChange:k=>{const B=k,L=s.getDataType(B.dataType)==="date";d(n,t.id,{field:B,value:"",operator:L?"between":"="})},availableFields:o,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?d(n,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?d(n,t.id,{operator:k,value:null}):d(n,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?ks(t.operator):""})}),e.jsx(s.SelectContent,{children:Mr(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:ks(k)},k))})]}),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"?g?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..."]}):v?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(Cr,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>d(n,t.id,{value:k}),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:k=>d(n,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Sr,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>d(n,t.id,{value:k}),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:k=>d(n,t.id,{value:k==="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(wr,{value:t.value,operator:t.operator,onChange:k=>d(n,t.id,{value:k}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:k=>l(n,t.id,"value",k.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:()=>i(n,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function Lr({group:t,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:l,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onReorderConditions:u,onReorderGroups:m,onAddCondition:x,onAddGroup:h,availableFields:p,renderFilterGroup:j,updateConditionFields:g}){const{attributes:v,listeners:D,setNodeRef:k,transform:B,transition:L,isDragging:E}=s.useSortable({id:t.id}),C={transform:s.CSS.Transform.toString(B),transition:L},f=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id){const P=t.conditions.findIndex(T=>T.id===A.id),I=t.conditions.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&u(t.id,P,I)}},b=N=>{const{active:A,over:w}=N;if(w&&A.id!==w.id&&n){const P=t.groups.findIndex(T=>T.id===A.id),I=t.groups.findIndex(T=>T.id===w.id);P!==-1&&I!==-1&&m(n,P,I)}};return e.jsxs("div",{ref:k,style:C,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...v,...D,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:()=>l(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:N=>r(t.id,N),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:()=>n&&i(n,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>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:f,children:e.jsx(s.SortableContext,{items:t.conditions.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((N,A)=>e.jsx(ct,{condition:N,index:A,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:c,onUpdateField:o,onRemoveCondition:d,onUpdateGroupOperator:r,availableFields:p,updateConditionFields:g},N.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:b,children:e.jsx(s.SortableContext,{items:t.groups.map(N=>N.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(N=>j(N,a+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:()=>x(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:()=>h(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Fr({filters:t,availableFields:a,onSave:n,onClearAll:r,onCancel:l}){const{currentFilters:i,availableFields:c,isLoading:o,addCondition:d,addGroup:u,removeCondition:m,removeGroup:x,updateCondition:h,updateConditionFields:p,updateGroupOperator:j,updateGroupNegate:g,reorderConditions:v,reorderGroups:D,generateSQLPreview:k,hasAnyFilters:B,setCurrentFilters:L}=jr({initialFilters:t,availableFields:a}),E=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[C,f]=S.useState(!1),b=(w,P,I)=>{const T=y=>y.id===w?{...y,conditions:y.conditions.map(M=>M.id===P?{...M,field:I,dataType:I.dataType}:M)}:{...y,groups:y.groups.map(T)};L(T(i))},N=(w,P=0,I)=>P===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.conditions.findIndex($=>$.id===y.id),z=w.conditions.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&v(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.conditions.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.conditions.map((T,y)=>e.jsx(ct,{condition:T,index:y,groupId:w.id,groupLogicalOperator:w.logicalOperator,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onUpdateGroupOperator:j,availableFields:c,updateConditionFields:p},T.id))})}),e.jsx(s.DndContext,{sensors:E,collisionDetection:s.closestCenter,onDragEnd:T=>{const{active:y,over:M}=T;if(M&&y.id!==M.id){const F=w.groups.findIndex($=>$.id===y.id),z=w.groups.findIndex($=>$.id===M.id);F!==-1&&z!==-1&&D(w.id,F,z)}},children:e.jsx(s.SortableContext,{items:w.groups.map(T=>T.id),strategy:s.verticalListSortingStrategy,children:w.groups.map(T=>N(T,P+1,w.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:()=>d(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),C&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>u(w.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},w.id):e.jsx(Lr,{group:w,depth:P,parentGroupId:I,onUpdateGroupOperator:j,onUpdateGroupNegate:g,onRemoveGroup:x,onUpdateCondition:h,onUpdateField:b,onRemoveCondition:m,onReorderConditions:v,onReorderGroups:D,onAddCondition:d,onAddGroup:u,availableFields:c,renderFilterGroup:N,updateConditionFields:p},w.id),A=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:[o?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..."})]}):N(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.SmallSwitch,{id:"advanced-mode",checked:C,onCheckedChange:w=>f(w)}),e.jsx(s.Label,{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),B&&e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"SQL WHERE Clause Preview"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:k(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:l,children:"Cancel"}),A>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>n(B?i:null),children:"Apply Filters"})]})]})}function Pr({cardId:t,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:l,isOpen:i,onOpenChange:c}){const o=u=>{n(t,u),c(!1)},d=()=>{r(t),c(!1)};return e.jsxs(s.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&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:u=>{u.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(Fr,{filters:a,availableFields:l,onSave:o,onCancel:()=>c(!1),onClearAll:d})]})]})}function Or({activeCardId:t,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var v,D;const[l,i]=S.useState(null),c=s.useEditorStore(k=>k.card),o=s.useEditorStore(k=>k.actions.updateCardConfig),d=(v=c==null?void 0:c.config)==null?void 0:v.joinPlan,u=(D=c==null?void 0:c.dataSource)==null?void 0:D.semanticDomainId,{data:m}=es(u),x=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],h=S.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||a.find(B=>B.id===k)?"source":n("groupBy").find(B=>B.id===k)?"groupBy":n("metrics").find(B=>B.id===k)?"metrics":n("pivotBy").find(B=>B.id===k)?"pivotBy":n("sortBy").find(B=>B.id===k)?"sortBy":null,[a,n]),p=S.useCallback(k=>{i(k.active.id)},[]),j=S.useCallback(k=>{var N;const{active:B,over:L}=k;if(!L||!t){i(null);return}const E=B.id,C=L.id,f=h(E),b=h(C)||C;if(b==="sortBy"){if(f==="source"){const A=a.find(P=>P.id===E);if(!A){i(null);return}if(!(n("groupBy").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName)||n("metrics").some(P=>P.name===A.name&&P.qualifiedEntityName===A.qualifiedEntityName))){i(null);return}}else if(f==="pivotBy"){i(null);return}else if(f!=="groupBy"&&f!=="metrics"&&f!=="sortBy"){i(null);return}}if(f==="source"&&b==="sortBy"){const A=[...a].find(T=>T.id===E);if(!A){i(null);return}const w=n("sortBy");if(s.fieldAlreadyExists(A,w)){i(null);return}const P=Fe(A,"sortBy",c.type);if(!P.isValid){s.ue.error("Invalid Field Type",{description:P.reason,position:"top-center",duration:3e3}),i(null);return}const I=s.getNewField(A,"sortBy",w);i(null),r("sortBy",[...w,I]);return}if(f==="source"&&b!=="source"&&b!=="sortBy"){const A=[...a].find(M=>M.id===E);if(!A){i(null);return}const w=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(w.length>0){const M=w[0].qualifiedEntityName;if(!M){i(null);return}if(M!==A.qualifiedEntityName&&A.qualifiedEntityName)if(u&&(m!=null&&m.joinabilityMap)){if(s.calculateFieldState(A,{joinabilityMap:m.joinabilityMap,selectedFields:w,baseEntityName:(N=d==null?void 0:d.baseEntity)==null?void 0:N.name}).state==="unreachable"){s.showJoinRequiredNotification(),i(null);return}}else{if(!d){s.showJoinRequiredNotification(),i(null);return}if(!s.areEntitiesJoined(M,A.qualifiedEntityName,d)){s.showJoinRequiredNotification(),i(null);return}}}const P=n(b);if(s.fieldAlreadyExists(A,P)){i(null);return}const I=Fe(A,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(A,b,P),y=[...P,T];i(null),r(b,y),b==="metrics"&&t&&Qe(c.type,c.config,o,t,y);return}if(f&&b&&f!=="source"&&b!=="source"&&f!==b){const A=n(f),w=n(b),P=A.find(F=>F.id===E);if(!P){i(null);return}const I=Fe(P,b,c.type);if(!I.isValid){s.ue.error("Invalid Field Type",{description:I.reason,position:"top-center",duration:3e3}),i(null);return}const T=s.getNewField(P,b,w);if(i(null),b==="sortBy"){s.fieldAlreadyExists(P,w)||r(b,[...w,T]);return}const y=A.filter(F=>F.id!==E),M=[...w,T];r(f,y),r(b,M),b==="metrics"&&t&&Qe(c.type,c.config,o,t,M);return}if(f&&b&&f===b&&f!=="source"){const A=n(f),w=A.findIndex(I=>I.id===E),P=A.findIndex(I=>I.id===C);if(w!==P){const I=s.arrayMove(A,w,P);r(f,I)}}i(null)},[t,a,n,r,h,d,u,m,c.type,o,c.config]),g=l?x.find(k=>k.id===l):null;return{activeId:l,activeField:g,handleDragStart:p,handleDragEnd:j}}function Br({activeView:t,onViewChange:a,splitViewEnabled:n}){const r=s.useEditorStore(d=>d.card),{config:l}=S.useContext(s.SemaphorContext).tokenProps,i=(l==null?void 0:l.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(r),o=()=>n?!1:!["table","pivotTable","aggregateTable"].includes(r.type);return e.jsx(s.Tabs,{value:t,onValueChange:d=>a(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"&&i&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Rr=[{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 Vr(){var d,u;const t=s.useEditorStore(m=>m.card),{updateRowLimit:a}=s.useEditorActions(),[n,r]=S.useState(!1),[l,i]=S.useState(""),c=m=>{if(m==="custom"){r(!0);return}r(!1),a(t.id,parseInt(m))},o=m=>{const x=m.target.value;i(x),x&&!isNaN(parseInt(x))&&a(t.id,parseInt(x))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(s.Input,{type:"number",value:l,onChange:o,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((u=(d=t.config)==null?void 0:d.rowLimit)==null?void 0:u.toString())||"100",onValueChange:c,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:Rr.map(m=>e.jsx(s.SelectItem,{value:m.value,children:m.label},m.value))})]})})}function zr({card:t,queryData:a,isLoading:n,isFetching:r,pagination:l,onPaginationChange:i,onSortChange:c,sortState:o,splitViewEnabled:d}){const u=S.useMemo(()=>(a==null?void 0:a.records)||[],[a==null?void 0:a.records]);return!d||["table","pivotTable","aggregateTable"].includes(t.type)?e.jsx(Ye,{}):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(Ye,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{defaultSize:40,minSize:20,role:"results-section",className:"flex flex-col",children:e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:(a==null?void 0:a.records)&&e.jsx(s.TableVisual,{card:t,data:u,paginationMetadata:l,onPaginationChange:i,isLoading:n||r,onSortChange:c,sortState:o})})})]})}const Gr="semaphor-split-view-enabled";function $r(){return $e(Gr,!0)}function qr({isOpen:t,onClose:a}){const n=Ls(a,{enabled:t}),r=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.url)||""}),l=s.useEditorStore(m=>m.card),i=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.pluginChartType)||""}),c=s.useEditorStore(m=>{var x;return((x=m.card.customCardPreferences)==null?void 0:x.settings)||{}}),{data:o}=s.useDashboardCardQuery(l),{getCard:d}=s.useCustomVisual(r),u=S.useMemo(()=>!r||r.trim()===""?null:d("Chart Settings"),[d,r]);return e.jsx("div",{ref:n,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:a,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:u&&e.jsx(S.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(u,{chartData:(o==null?void 0:o.records)||[],chartType:i,settings:c})})})]})})}function Ur({activeView:t,onViewChange:a,showDebug:n,onDebugToggle:r,onFiltersClick:l,activeCard:i,columns:c,columnsLoading:o,columnsError:d}){var Y,U,te;const u=s.useEditorStore(H=>H.card),m=s.useDashboardStore(H=>H.filterValues),{updateCardConfig:x,setCard:h,updateCardInFrame:p,setShowAIDialog:j}=s.useEditorActions(),g=s.useEditorStore(H=>H.showAIDialog),v=s.useDashboardStore(H=>H.isVisualEditing),[D,k]=S.useState(!1),[B,L]=S.useState(!1),[E,C]=S.useState(null),{config:f}=S.useContext(s.SemaphorContext).tokenProps,b=(f==null?void 0:f.showInfoTab)!==!1,[N,A]=$r(),w=s.useEditorStore(H=>{var re;return((re=H.card.customCardPreferences)==null?void 0:re.url)&&H.card.type==="custom"}),{data:P,errorMessage:I,isLoading:T,isFetching:y,errorSql:M,pagination:F,refetch:z,comparisonMetadata:$}=s.useDashboardCardQuery(i),O=S.useMemo(()=>(P==null?void 0:P.records)||[],[P==null?void 0:P.records]),[G,R]=S.useState(!1);S.useEffect(()=>{y||R(!1)},[y]);const _=()=>{const H=!N;H&&t==="table"&&a("chart"),A(H)},J=(H,re)=>{const ue={...i,paginationConfig:{page:H+1,pageSize:re}};h(ue),p(ue)};function se(){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(u.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(m||{},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(i.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",c.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:o?"Loading...":d?"Error loading columns":JSON.stringify(c.slice(0,5),null,2)})]})]})]})}const Z=H=>{if(!u.config)return;const re=s.sortStateToSortByColumns(H,u.config.metricColumns,u.config.groupByColumns);x(u.id,{...u.config,sortByColumns:re})},ae=S.useMemo(()=>{var H;return s.sortByColumnsToSortState((H=u.config)==null?void 0:H.sortByColumns)},[(Y=u.config)==null?void 0:Y.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":g&&v}),children:[n&&se(),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"&&g&&e.jsx(Ws,{variant:"outline"}),e.jsx(Br,{activeView:t,onViewChange:a,splitViewEnabled:N}),e.jsx(s.FilterInfo,{cardId:i.id,cardFilters:(U=i.config)==null?void 0:U.filters,cardFilterCount:s.getFilterCount(((te=i.config)==null?void 0:te.filters)||null),onFiltersClick:l}),$&&e.jsx(s.ComparisonMetadataBadge,{metadata:$,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Vr,{})}),g&&e.jsx(Ze,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:T||y,onClick:()=>{R(!0),z()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(s.IconButton,{tooltip:N?"Hide Results Table":"Show Results Table",onClick:_,children:N?e.jsx(It,{className:"size-4"}):e.jsx(_t,{className:"size-4"})}),t==="chart"&&e.jsx(Ys,{}),!g&&e.jsx(s.IconButton,{onClick:()=>j(!g),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!D&&w&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),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":N&&!["table","pivotTable","aggregateTable"].includes(i.type)}),children:e.jsx(zr,{card:i,queryData:P,isLoading:T,isFetching:y,pagination:F,onPaginationChange:J,onSortChange:Z,sortState:ae,splitViewEnabled:N})}),t==="table"&&(P==null?void 0:P.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:i,data:O,paginationMetadata:F,onPaginationChange:J,isLoading:T||y,onSortChange:Z,sortState:ae})}),t==="info"&&b&&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:I?e.jsx(as,{error:I,errorSql:M,onSendFeedback:()=>{const H=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:u.config,dataSource:i.dataSource,dashboardFilters:m,errorMessage:I,errorSql:M,generatedSql:P==null?void 0:P.sql});C(H),L(!0)},onOpenInEditor:()=>{j(!0),setTimeout(()=>{const H=s.useEditorStore.getState().actions;H.setIsDevMode(!0),H.setCardSql(M||""),setTimeout(()=>{H.setRunSql(!0)},100)},100)}}):e.jsx(Ks,{sql:P==null?void 0:P.sql,error:I,errorSql:M})})})]}),e.jsx(qr,{isOpen:D,onClose:()=>k(!1)}),E&&e.jsx(s.FeedbackDialog,{open:B,onOpenChange:L,feedbackData:E})]})]})}function Kr({activeField:t}){const[a,n]=S.useState(!0);return S.useEffect(()=>{t&&n(!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 ${a?"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(ls,{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 _r=()=>{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 a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var l;if((l=r.reason)!=null&&l.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=t,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Hr(){var $,O;const[t,a]=S.useState("chart"),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(!0),d=s.useEditorStore(G=>G.showAIDialog),u=s.useDashboardStore(G=>G.isVisualEditing),{setCardType:m}=s.useEditorActions(),x=s.useEditorStore(G=>G.card.type);S.useEffect(()=>_r(),[]);const h=G=>{m(G)},p=s.useEditorStore(G=>G.frame),j=s.useEditorStore(G=>G.card);s.useEditorStore(G=>G.activeTabCardId),s.useEditorStore(G=>G.actions.getAvailableFields);const{addCard:g,removeCard:v,updateCard:D,setActiveCard:k,updateFilters:B}=s.useEditorActions(),{columns:L=[],isLoading:E,error:C}=s.useColumns(),f=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),b=j,{getFieldsForContainer:N,setFieldsForContainer:A}=ss(b),{activeField:w,handleDragStart:P,handleDragEnd:I}=Or({activeCardId:p.activeCardId,sourceFields:L,getFieldsForContainer:N,setFieldsForContainer:A}),T=(G,R)=>{R&&B(G,R)},y=G=>{var R;D(G,{config:{...(R=p.cards.find(_=>_.id===G))==null?void 0:R.config,filters:void 0}})},M=L,F=G=>{if(!G)return 0;let R=G.conditions.length;return G.groups.forEach(_=>{R+=F(_)}),R},z=F((($=b==null?void 0:b.config)==null?void 0:$.filters)||null);return e.jsxs(s.DndContext,{sensors:f,collisionDetection:s.closestCenter,onDragStart:P,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Us,{isVisible:c,onToggleVisibility:()=>o(!c)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!d&&e.jsx(gr,{selectedChart:x,onChartChange:h,groupByFields:N("groupBy"),pivotByFields:N("pivotBy"),metricsFields:N("metrics"),sortByFields:N("sortBy"),activeField:w}),e.jsx(Ur,{selectedChart:x,activeView:t,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onFiltersClick:()=>i(!0),filterCount:z,activeCard:b,dataSourceState:j.dataSource||s.EMPTY_DATA_SOURCE,columns:L,columnsLoading:E,columnsError:C,getFieldsForContainer:N,cards:p.cards,activeCardId:p.activeCardId,addCard:g,setActiveCard:k})]}),!c&&u&&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:()=>o(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),b&&e.jsx(Pr,{cardId:b.id,filters:((O=b.config)==null?void 0:O.filters)||null,onFiltersChange:T,onClearFilters:y,availableFields:M,isOpen:l,onOpenChange:i}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx(Kr,{activeField:w||null})})]})}function Jr({authToken:t,onSave:a,onClose:n}){const r=S.useRef(null),l=s.useEditorStore(C=>C.showAIDialog),i=s.useEditorStore(C=>C.isDevMode),c=s.useAssistantLayoutStore(C=>C.setFullscreen),o=s.useAssistantLayoutStore(C=>C.setPanelOpen),d=s.useAssistantLayoutStore(C=>C.setContainer),u=s.useAssistantPanel("editor"),m=s.useFullscreenAssistant(),x=s.useAssistantContainer("editor"),h=m==="editor",p=S.useCallback(C=>{d("editor",C)},[d]),{setAuthToken:j}=s.useDashboardActions(),{setShowAIDialog:g,setOnSave:v,setOnClose:D}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();S.useEffect(()=>{a&&v(a),n&&D(n)},[a,v,n,D]),S.useEffect(()=>{t&&t.accessToken&&j(t)},[t,j]),S.useEffect(()=>{var C,f;l?((C=r.current)==null||C.resize(40),o("editor",!0),k("editor")):((f=r.current)==null||f.resize(0),o("editor",!1),m==="editor"&&c(null),k(null))},[l,o,k,c,m]);function B(C){C<1?(g(!1),o("editor",!1),m==="editor"&&c(null),k(null)):(l||(g(!0),k("editor")),u.isOpen||o("editor",!0))}function L(){return e.jsxs(e.Fragment,{children:[e.jsx(Us,{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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Qn,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})]})}function E(){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",h&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Hr,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:B,defaultSize:u.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Cs,{isFullscreen:h,onFullscreenChange:C=>c(C?"editor":null),fullscreenContainer:x})})})]}),e.jsx("div",{ref:p,className:s.cn("absolute inset-0",!h&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:i?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:L()}):E()})}function Qr(){s.useDashboardStore(c=>c.selectedCardId);const t=s.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=s.useDashboardStore(c=>c.actions),n=s.useDashboardStore(c=>c.isVisualEditing),r=s.useDashboardStore(c=>c.actions.updateFrame);function l(c){t&&(r(t,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:s.cn("flex-1 grow basis-0 overflow-auto",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Jr,{onSave:l,onClose:i})})}function Wr(){qs();const t=s.useDashboardStore(d=>d.selectedSheetId),a=s.useDashboardStore(d=>d.selectedFrameId),n=s.useDashboardStore(d=>d.dashboard),r=s.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:l}=s.useDashboardActions(),{setCard:i}=s.useEditorActions(),c=s.useEditorStore(d=>d.card.dataSource);return S.useEffect(()=>{var u,m;let d=r();if(!d){const x=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===t),h=(m=x==null?void 0:x.frames)==null?void 0:m[0];h&&(l(h.id),d=h)}if(d){const x=d.cards.find(h=>h.id===d.activeCardId);x&&i(x)}},[r,t,a,n,l,i]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Yr(){const t=s.useDashboardStore(n=>n.actions.setShowFilters),{hasEntities:a}=Wr();return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[e.jsx(s.Label,{className:"px-2 text-base",children:"Dashboard Filters"}),e.jsx(s.Button,{onClick:()=>t(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(s.Cross2Icon,{})})]}),!a&&e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[e.jsx(s.Database,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),a&&e.jsx("div",{className:"flex grow",children:e.jsx(s.DndContext,{collisionDetection:s.closestCenter,children:e.jsx(s.SortableContext,{items:[],strategy:s.verticalListSortingStrategy,children:e.jsx($s,{context:"filter"})})})})]})}function Xr(){const t=s.useDashboardStore(r=>r.dashboard.filters),a=s.useDashboardStore(r=>r.theme),n=t==null?void 0:t.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:s.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(s.FilterHeader,{filter:r}),e.jsx(s.FilterComponent,{filter:r})]},r.id))}):null}function Zr(){const t=s.useDashboardStore(r=>r.showFilters),a=s.useDashboardStore(r=>r.isVisualEditing),n=s.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:s.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(Xr,{}),e.jsx(s.DashboardTabs,{})]}),t&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Yr,{})})]})}function el(){const t=s.useDashboardStore(l=>l.dashboard),a=s.useDashboardStore(l=>l.actions.setDashboard),n=s.useDashboardStore(l=>l.showDashboardJSON),r=s.useDashboardStore(l=>l.actions.setShowDashboardJSON);return e.jsxs("div",{className:s.cn("relative p-2",{hidden:!n}),children:[e.jsxs(s.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(s.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(s.de,{onChange:l=>{if(l)try{JSON.parse(l),a(JSON.parse(l))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(t,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function dt(){return e.jsx(s.ScrollArea,{className:"w-full flex-1",children:e.jsxs("div",{className:"space-y-4 px-4 py-2",children:[e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"h-9 w-full rounded bg-muted animate-pulse"}),e.jsx("div",{className:"space-y-3 pt-2",children:[...Array(3)].map((t,a)=>e.jsxs("div",{className:"flex gap-3 animate-pulse",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-2/3 rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},a))})]})})}const sl=t=>{const a=s.useDashboardStore(l=>l.isVisualEditing),n=s.useDashboardStore(l=>l.selectedFrameId),r=s.useEditorStore(l=>l.frame);return!!(a&&n&&(r==null?void 0:r.visualId)===t)};function tl({visual:t,isDeleting:a,isDuplicating:n,onAddVisual:r,onOpenVisual:l,onEditDetails:i,onDeleteClick:c,onDuplicateVisual:o,onShareVisual:d,formatDate:u}){var E,C,f,b;const{selectVisual:m}=s.useManagementActions(),x=s.useIsVisualSelected(t.id),h=sl(t.id),{isConsoleMode:p}=s.useDashboardPreferences(),j=S.useRef(null),[g,v]=S.useState(!1),[D,k]=S.useState(!1);S.useEffect(()=>{n?(v(!0),k(!0)):D&&(v(!1),k(!1))},[n,D]),S.useEffect(()=>{h&&j.current&&j.current.scrollIntoView({behavior:"smooth",block:"center"})},[h]);const B=()=>e.jsx(s.Grid3x3,{className:"h-4 w-4"}),L=()=>{m(t),l==null||l(t)};return e.jsx(s.Card,{ref:j,className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",h?"border-purple-500":x&&"border-primary"),onClick:L,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:B()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(E=t.description)!=null&&E.trim()?t.description:"No description"}),e.jsxs("div",{className:s.cn("invisible flex flex-shrink-0 items-center gap-1 transition-opacity duration-150 group-hover:visible",x&&"visible"),onClick:N=>N.stopPropagation(),children:[e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),r(t)},title:"Add to dashboard",children:e.jsx(s.Plus,{className:"h-3.5 w-3.5"})}),t.ownership.isOwner&&e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:N=>{N.stopPropagation(),i==null||i(t)},title:"Edit details",children:e.jsx(s.PenLine,{className:"h-3 w-3"})}),e.jsxs(s.DropdownMenu,{modal:!1,open:g,onOpenChange:v,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",children:e.jsx(s.Ellipsis,{className:"h-3 w-3"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"z-[51] w-40",children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),r(t)},children:[e.jsx(s.Plus,{className:"mr-2 h-3 w-3"}),"Add"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),l==null||l(t)},children:[e.jsx(Et,{className:"mr-2 h-3 w-3"}),"Open"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.preventDefault(),N.stopPropagation(),o(t.id)},disabled:n,children:[n?e.jsx(s.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):e.jsx(s.Copy,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}),t.ownership.isOwner&&e.jsxs(e.Fragment,{children:[e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),i==null||i(t)},children:[e.jsx(s.PenLine,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),d(t)},children:[e.jsx(s.Users,{className:"mr-2 h-3 w-3"}),"Share"]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs(s.DropdownMenuItem,{onClick:N=>{N.stopPropagation(),c(t)},className:"text-destructive",disabled:a,children:[e.jsx(s.Trash2,{className:"mr-2 h-3 w-3"}),a?"Deleting...":"Delete"]})]}),e.jsx(s.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-slate-500 dark:text-slate-400",children:[(((C=t.ownership.createdBy)==null?void 0:C.type)==="tenant"||((f=t.ownership.createdBy)==null?void 0:f.type)==="organization"&&p)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.User,{className:"h-3 w-3"}),e.jsx("span",{children:((b=t.ownership.createdBy)==null?void 0:b.name)||"Unknown"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:u(t.lastModified)})]})]})]})]})]})]})]})]})},t.id)}function al({open:t,onOpenChange:a,onSubmit:n,isCreating:r}){const[l,i]=S.useState(""),[c,o]=S.useState("");S.useEffect(()=>{t||(i(""),o(""))},[t]);const d=()=>{l.trim()&&n({title:l,description:c})},u=m=>{a(m)};return e.jsx(s.Dialog,{open:t,onOpenChange:u,children:e.jsxs(s.DialogContent,{children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Create New Visual"}),e.jsx(s.DialogDescription,{children:"Add a new visual to your library. You can configure it after creation."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"title",children:"Visual Title"}),e.jsx(s.Input$1,{id:"title",placeholder:"Enter visual title...",value:l,onChange:m=>i(m.target.value),disabled:r,onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(s.Input$1,{id:"description",placeholder:"Enter visual description...",value:c,onChange:m=>o(m.target.value),disabled:r})]})]}),e.jsxs(s.DialogFooter,{children:[e.jsx(s.Button,{variant:"outline",onClick:()=>u(!1),disabled:r,children:"Cancel"}),e.jsx(s.Button,{onClick:d,disabled:!l.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Visual"})]})]})})}function nl(){const[t,a]=S.useState(""),[n,r]=S.useState(!1),[l,i]=S.useState(!1),[c,o]=S.useState(null),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(null),[j,g]=S.useState(null),{selectVisual:v}=s.useManagementActions(),{handleEditLibraryVisual:D,handleAddLibraryVisual:k}=Te(),{resources:B,isLoading:L,isError:E,createResource:C,updateResource:f,deleteResource:b,duplicateResource:N,isCreating:A,isDeleting:w}=s.useVisualManagement(()=>{u(!1),x(null)},U=>{r(!1),U&&(v(U),D(U))});s.useCurrentUserInfo();const P=B.filter(U=>{var te,H;return((te=U==null?void 0:U.title)==null?void 0:te.toLowerCase().includes(t.toLowerCase()))||((H=U==null?void 0:U.description)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))}),I=U=>new Date(U).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),T=U=>{C({title:U.title,description:U.description,isPrivate:!1})},y=U=>{x(U),u(!0)},M=()=>{m&&b(m.id)},{startUpdating:F,stopUpdating:z,isUpdating:$}=s.useResourceUpdateState(),O=(U,te,H)=>{var q;const re=Object.fromEntries(Object.entries(te).filter(([,W])=>W!==void 0));if(Object.keys(re).length===0){(q=H==null?void 0:H.onSuccess)==null||q.call(H);return}const ue=Object.keys(re),me=ue.length===1?ue[0]:void 0;F(U,me),f({resourceId:U,data:re},{onSuccess:()=>{var W;z(U,me),(W=H==null?void 0:H.onSuccess)==null||W.call(H)},onError:()=>{var W;z(U,me),(W=H==null?void 0:H.onError)==null||W.call(H)}})},G=U=>{p(U),N(U,{onSettled:()=>p(null)})},R=U=>{D(U)},_=U=>{k(U)},J=U=>{const te=B.find(H=>H.id===U);te&&f({resourceId:U,data:{isPrivate:!te.isPrivate}})},se=U=>{o(U),i(!0)},Z=U=>{g(U)},ae=()=>{g(null)},Y=({title:U,description:te})=>{if(!j)return;const H={};U!==j.title&&(H.title=U),(j.description||"")!==te&&(H.description=te),O(j.id,H,{onSuccess:()=>{g(null)}})};return L?e.jsx(dt,{}):E?e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load visuals"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]})}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[B&&B.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:t,onChange:U=>a(U.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:P.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.Grid3x3,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:t?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:t?"Try adjusting your search":"Create your first visual component to get started"}),!t&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>r(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Visual"]})]}):P.map(U=>e.jsx(tl,{visual:U,onAddVisual:_,onOpenVisual:R,onEditDetails:Z,onDeleteClick:y,onDuplicateVisual:G,onTogglePrivacy:J,onShareVisual:se,isDeleting:w,isDuplicating:h===U.id,formatDate:I},U.id))})}),l&&c&&e.jsx(s.ShareDialog,{resource:c,resourceType:s.ResourceType.VISUAL,onClose:()=>{i(!1),o(null)}}),j&&e.jsx(s.ResourceEditDialog,{open:!!j,resourceLabel:"Visual",initialTitle:j.title||"",initialDescription:j.description||"",onClose:ae,onSave:Y,isSaving:$(j.id)}),e.jsx(s.AlertDialog,{open:d,onOpenChange:U=>{!U&&w||(u(U),U||x(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Visual"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:w,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:U=>{U.preventDefault(),U.stopPropagation(),M()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:w,children:[w?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),w?"Deleting...":"Delete"]})]})]})}),e.jsx(al,{open:n,onOpenChange:r,onSubmit:T,isCreating:A}),e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>r(!0),"aria-label":"Create visual",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function rl({dashboard:t,isDeleting:a,isDuplicating:n,onLoadDashboard:r,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d,onDashboardItemClick:u}){var k,B;const{selectDashboard:m}=s.useManagementActions(),x=s.useIsDashboardSelected(t.id),{userContext:h,isLoading:p}=s.useCurrentUserInfo(),j=((k=h==null?void 0:h.permissions)==null?void 0:k.canEdit)??!1,g=p||!j,v=()=>e.jsx(s.LayoutDashboard,{className:"h-4 w-4"}),D=()=>{m(t),r(t.id),u==null||u(t.id)};return e.jsx(s.Card,{className:s.cn("group cursor-pointer border border-border/50 p-3 transition-colors hover:bg-accent/50",x&&"border-primary"),onClick:D,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded bg-muted p-1.5",children:v()}),e.jsxs("div",{className:"min-w-0 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",title:t.title||"Untitled Dashboard",children:t.title||"Untitled Dashboard"}),t.ownership.status==="shared"&&e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:[e.jsx(s.Users,{className:"mr-1 h-2.5 w-2.5"}),"Shared"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 flex-1",title:t.description||"No description",children:(B=t.description)!=null&&B.trim()?t.description:"No description"}),e.jsx(s.DashboardActionsMenu,{dashboard:t,isDeleting:a,isDuplicating:n,shouldHideActions:g,onEditDetails:l,onDeleteClick:i,onDuplicateDashboard:c,onShareDashboard:o,formatDate:d})]})]})]})},t.id)}function ll({onRetry:t}){return e.jsx(s.ScrollArea,{className:"w-full flex-1 pr-2",children:e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx("p",{className:"text-sm text-destructive",children:"Failed to load dashboards"}),e.jsx(s.Button,{variant:"outline",size:"sm",className:"mt-2",onClick:t,children:"Retry"})]})})}function ol(t){var ce;const{onLoadDashboard:a,onEditDashboard:n,onDashboardItemClick:r}=t,[l,i]=S.useState(""),[c,o]=S.useState(!1),[d,u]=S.useState(!1),[m,x]=S.useState(null),[h,p]=S.useState(!1),[j,g]=S.useState(null),[v,D]=S.useState(null),[k,B]=S.useState(null),L=s.useManagementStore(V=>V.lastSelectedDashboard),E=s.useManagementStore(V=>V.selectedDashboard),C=s.useManagementStore(V=>V.actions.selectDashboard),f=s.useManagementStore(V=>V.actions.clearSelectedDashboard),{tokenProps:b,id:N}=s.useSemaphorContext();s.useRoleAwareDisplayPreferences();const{onCreateSuccess:A}=s.useDashboardCreation({onDashboardSelect:r}),{resources:w,isLoading:P,isError:I,createResource:T,updateResource:y,deleteResource:M,duplicateResource:F,isCreating:z,isDeleting:$,refetch:O}=s.useDashboardManagement(()=>{p(!1);const V=j==null?void 0:j.id;g(null),(E==null?void 0:E.id)===V&&(!(b!=null&&b.dashboard_id)&&!N?f():L&&L.id!==V&&C(L))},V=>{o(!1),A(V,O)}),{currentUser:G,userContext:R}=s.useCurrentUserInfo(),_=((ce=R==null?void 0:R.permissions)==null?void 0:ce.canCreateDashboard)??!1,J=w.filter(V=>{var ee,X;return((ee=V==null?void 0:V.title)==null?void 0:ee.toLowerCase().includes(l.toLowerCase()))||((X=V==null?void 0:V.description)==null?void 0:X.toLowerCase().includes(l.toLowerCase()))}),se=V=>new Date(V).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}),Z=V=>{T({title:V.title,description:V.description,isPrivate:!1})},ae=V=>{a==null||a(V)},Y=V=>{g(V),p(!0)},U=()=>{j&&M(j.id)},te=V=>{D(V),F(V,{onSettled:()=>D(null)})},{startUpdating:H,stopUpdating:re,isUpdating:ue}=s.useResourceUpdateState(),me=(V,ee,X)=>{var ve;const je=Object.fromEntries(Object.entries(ee).filter(([,he])=>he!==void 0));if(Object.keys(je).length===0){(ve=X==null?void 0:X.onSuccess)==null||ve.call(X);return}const ge=Object.keys(je),be=ge.length===1?ge[0]:void 0;H(V,be),y({resourceId:V,data:je},{onSuccess:()=>{var he;re(V,be),(he=X==null?void 0:X.onSuccess)==null||he.call(X)},onError:()=>{var he;re(V,be),(he=X==null?void 0:X.onError)==null||he.call(X)}})},q=V=>{const ee=w.find(X=>X.id===V);ee&&y({resourceId:V,data:{isPrivate:!ee.isPrivate}})},W=V=>{x(V),G==null||G.type,u(!0)},de=V=>{n==null||n(V.id),B(V)},pe=()=>{B(null)},fe=({title:V,description:ee})=>{if(!k)return;const X={};V!==k.title&&(X.title=V),(k.description||"")!==ee&&(X.description=ee),me(k.id,X,{onSuccess:()=>{B(null)}})};return P?e.jsx(dt,{}):I?e.jsx(ll,{onRetry:()=>window.location.reload()}):e.jsxs("div",{className:"relative flex h-full flex-1 flex-col gap-4",children:[w&&w.length>5&&e.jsx("div",{className:"space-y-2",children:e.jsx(s.Input$1,{id:"search",placeholder:"Search by title or description...",value:l,onChange:V=>i(V.target.value),className:"h-9"})}),e.jsx("div",{className:"flex flex-1 flex-col",children:e.jsx("div",{className:"flex flex-1 basis-0 flex-col gap-3 overflow-y-auto",children:J.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"mb-3",children:e.jsx(s.ChartColumn,{className:"mx-auto h-12 w-12 text-muted-foreground/50"})}),e.jsx("h3",{className:"mb-1 font-medium text-foreground",children:l?"No dashboards found":"No dashboards yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:l?"Try adjusting your search":_?"Create your first dashboard to get started":"No dashboards have been shared with you yet"}),_&&!l&&e.jsxs(s.Button,{size:"sm",className:"bg-primary hover:bg-primary/90",onClick:()=>o(!0),children:[e.jsx(s.Plus,{className:"mr-2 h-4 w-4"}),"Create Dashboard"]})]}):J.map(V=>e.jsx(rl,{dashboard:V,isDeleting:$,isDuplicating:v===V.id,onLoadDashboard:ae,onEditDetails:de,onDeleteClick:Y,onDuplicateDashboard:te,onTogglePrivacy:q,onShareDashboard:W,formatDate:se,onDashboardItemClick:r},V.id))})}),d&&m&&e.jsx(s.ShareDialog,{resource:m,resourceType:s.ResourceType.DASHBOARD,onClose:()=>{u(!1),x(null)}}),e.jsx(s.AlertDialog,{open:h,onOpenChange:V=>{!V&&$||(p(V),V||g(null))},children:e.jsxs(s.AlertDialogContent,{children:[e.jsxs(s.AlertDialogHeader,{children:[e.jsx(s.AlertDialogTitle,{children:"Delete Dashboard"}),e.jsxs(s.AlertDialogDescription,{children:['Are you sure you want to delete "',j==null?void 0:j.title,'"? This action cannot be undone.']})]}),e.jsxs(s.AlertDialogFooter,{children:[e.jsx(s.AlertDialogCancel,{disabled:$,children:"Cancel"}),e.jsxs(s.AlertDialogAction,{onClick:V=>{V.preventDefault(),V.stopPropagation(),U()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:$,children:[$?e.jsx(s.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):e.jsx(s.Trash2,{className:"mr-2 h-3.5 w-3.5"}),$?"Deleting...":"Delete"]})]})]})}),k&&e.jsx(s.ResourceEditDialog,{open:!!k,resourceLabel:"Dashboard",initialTitle:k.title||"",initialDescription:k.description||"",onClose:pe,onSave:fe,isSaving:ue(k.id)}),e.jsx(s.CreateDashboardDialog,{open:c,onOpenChange:o,onSubmit:Z,isCreating:z}),_&&e.jsx(s.Button,{size:"icon",className:"absolute bottom-2 left-2 h-11 w-11 rounded-full shadow-lg shadow-black/15",onClick:()=>o(!0),"aria-label":"Create dashboard",children:e.jsx(s.Plus,{className:"h-5 w-5"})})]})}function ut({isOpen:t,onClose:a,className:n,onDashboardItemClick:r,variant:l="inline"}){s.useDashboardStore(C=>C.dashboard);const i=s.useDashboardStore(C=>C.isDashboardEditing),{setDashboard:c,addSheet:o}=s.useDashboardStore(C=>C.actions),{currentUser:d}=s.useCurrentUserInfo(),u=d,{permissions:m}=s.useRoleAwareDisplayPreferences(),h=s.useSelectedDashboard()&&m.canAccessVisuals&&i,p="dashboards",[j,g]=$e("resource-management-active-tab",p),v=h?j:"dashboards",D=l==="overlay",k=Ls(a,{enabled:t&&D}),B=s.cn("flex h-full flex-col border-r bg-background",D?s.cn("absolute inset-y-0 left-0 z-[51] w-96 shadow-lg transition-transform duration-300 ease-in-out",t?"translate-x-0":"pointer-events-none -translate-x-full"):"w-full max-w-[28rem] min-w-[18rem] overflow-hidden shadow-sm",n),L=C=>{},E=C=>{console.log("Editing dashboard:",C)};return e.jsx(s.TooltipProvider,{children:(!D||t)&&e.jsxs("div",{ref:k,className:B,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border p-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:u&&e.jsxs(e.Fragment,{children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"flex h-8 w-8 cursor-default items-center justify-center rounded-full bg-primary/10",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:u.name.charAt(0).toUpperCase()})})}),e.jsx(s.TooltipContent,{side:"bottom",className:"ml-2 max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email}),u.role&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Role:"," ",s.toTitleCase(u.role.replace(/_/g," "))]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["ID: ",u.id]})]})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-sm font-medium text-foreground",children:u.name})})]})}),e.jsx(s.IconButton,{className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",onClick:a,tooltip:"Close Sidebar",children:e.jsx(qt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:e.jsxs(s.Tabs,{value:v,onValueChange:h?g:void 0,className:"flex h-9 grow flex-col",children:[h&&e.jsx("div",{className:"px-4 pt-4",children:e.jsxs(s.TabsList,{className:"grid w-full grid-cols-2",children:[e.jsx(s.TabsTrigger,{value:"dashboards",className:"text-sm",children:"Dashboards"}),e.jsx(s.TabsTrigger,{value:"visuals",className:"text-sm",children:"Visuals"})]})}),e.jsx(s.TabsContent,{value:"dashboards",className:"flex-1 px-4 py-4",children:e.jsx(ol,{onLoadDashboard:L,onEditDashboard:E,onDashboardItemClick:r})}),h&&e.jsx(s.TabsContent,{value:"visuals",className:"flex-1 px-4 py-4",children:e.jsx(nl,{})})]})})]})})}function il({showControls:t=!1,showFooter:a=!0,...n}){const r=s.useDashboardStore(h=>h.isDashboardPanelOpen);s.useDashboardStore(h=>h.isVisualEditing);const l=s.useDashboardStore(h=>h.actions.setIsDashboardPanelOpen),i=20,c=20,o=30,d=r,u=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{u.current&&m.current&&(r?(u.current.resize(i),m.current.resize(100-i)):(u.current.resize(0),m.current.resize(100)))},[r]);const{preferences:x}=n;return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:e.jsxs(s.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(s.$e,{}),e.jsx(s.UXProvider,{children:e.jsxs(s.DashboardPreferencesProvider,{preferences:x,children:[e.jsx(el,{}),e.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[t&&e.jsx(Aa,{}),e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",className:"flex grow overflow-hidden",children:[e.jsx(s.ResizablePanel,{ref:u,className:s.cn("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?i:0,minSize:d?c:0,maxSize:d?o:0,children:e.jsx(ut,{isOpen:r,onClose:()=>l(!1),variant:"inline"})}),e.jsx(s.ResizableHandle,{className:s.cn("",{"w-0":!d})}),e.jsx(s.ResizablePanel,{ref:m,className:"flex min-w-0 flex-1",defaultSize:d?100-i:100,minSize:d?40:100,children:e.jsxs(s.Container,{...n,type:"dashboard",children:[e.jsx(Qr,{}),e.jsx(Zr,{})]})})]})]})]})})]})})}exports.AdvancedModeToggle=Rs;exports.DashboardPlus=il;exports.ResourceManagementPanel=ut;exports.ScheduleDashboard=Ps;exports.VisualEditingControls=Bs;exports.cleanCard=Fs;exports.getDashbaordStateWithoutData=ze;
|