react-semaphor 0.1.266 → 0.1.267

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/chunks/{dashboard-controls-nYrePhKP.js → dashboard-controls-BRv37g5w.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-DxBpzTlu.js → dashboard-controls-d8j31cnQ.js} +4 -4
  3. package/dist/chunks/{dashboard-filter-controls-button-DnKmHlG3.js → dashboard-filter-controls-button-BOs9T2hG.js} +3 -3
  4. package/dist/chunks/{dashboard-filter-controls-button-DjCrZizC.js → dashboard-filter-controls-button-DKRyKRsP.js} +1 -1
  5. package/dist/chunks/{dashboard-json-BSPGwZoR.js → dashboard-json-CnEYIbNI.js} +1 -1
  6. package/dist/chunks/{dashboard-json-B9J-U_dZ.js → dashboard-json-DjNS3G-C.js} +1 -1
  7. package/dist/chunks/{dashboard-summary-settings-dialog-Bk7VmHgo.js → dashboard-summary-settings-dialog-CrBOuggE.js} +1 -1
  8. package/dist/chunks/{dashboard-summary-settings-dialog-Ds7gUWV2.js → dashboard-summary-settings-dialog-DOVwh8Cc.js} +1 -1
  9. package/dist/chunks/{edit-dashboard-visual-BJg06zc9.js → edit-dashboard-visual-D4UMcS6R.js} +3 -3
  10. package/dist/chunks/{edit-dashboard-visual-f17MIvBF.js → edit-dashboard-visual-D6RokBEF.js} +2 -2
  11. package/dist/chunks/{index-xs5JKKah.js → index-C2i6CRUk.js} +3 -3
  12. package/dist/chunks/{index-CKko7o0J.js → index-D5jdzvu3.js} +13 -15
  13. package/dist/chunks/{resource-management-panel-CXh-XKhy.js → resource-management-panel-3XD0FrTD.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-CtIxVLTX.js → resource-management-panel-ZK4SWoad.js} +1 -1
  15. package/dist/chunks/{use-create-flow-overlay-state-CjgEH2On.js → use-create-flow-overlay-state-Bb83NOgW.js} +2 -2
  16. package/dist/chunks/{use-create-flow-overlay-state-Cq7aXkf1.js → use-create-flow-overlay-state-Cmt64wFE.js} +1 -1
  17. package/dist/chunks/{use-visual-utils-B8kTq0CR.js → use-visual-utils-Bdwejpa1.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-B9_ewYu9.js → use-visual-utils-Bj7eAUMG.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/surfboard/index.cjs +1 -1
  24. package/dist/surfboard/index.js +2 -2
  25. package/package.json +1 -1
@@ -1150,7 +1150,7 @@ setTimeout(semaphorPostHeight, 500);
1150
1150
  <\/script>`;return/<head[^>]*>/i.test(e)?e.replace(/<head([^>]*)>/i,`<head$1>${n}`):`${n}${e}`}function nrt({html:e,title:t,className:n,onRuntimeError:r}){const[s,o]=w.useState(!1),[i,a]=w.useState(J9),c=w.useRef(null),u=w.useMemo(()=>`dynamic-visual-${Math.random().toString(36).slice(2)}`,[]),d=w.useMemo(()=>trt(e,u),[e,u]);return w.useEffect(()=>{o(!1),a(J9)},[e]),w.useEffect(()=>{function f(h){var p,g;const m=h.data;if(m&&h.source===((p=c.current)==null?void 0:p.contentWindow)&&m.type==="semaphor-dynamic-visual-height"&&m.frameId===u&&typeof m.height=="number"){const b=Math.max(ert,Math.ceil(m.height));a(x=>x===b?x:b);return}m&&h.source===((g=c.current)==null?void 0:g.contentWindow)&&m.type==="semaphor-dynamic-visual-error"&&m.frameId===u&&(o(!0),r==null||r())}return window.addEventListener("message",f),()=>window.removeEventListener("message",f)},[u,r]),s?l.jsx("div",{className:"flex min-h-[360px] items-center justify-center rounded-md border border-dashed border-border/60 bg-muted/20 p-4 text-sm text-muted-foreground",children:"The dynamic visual could not be rendered in the iframe host."}):l.jsx("div",{className:Q("relative min-h-[360px] overflow-hidden rounded-md bg-background",n),children:l.jsx("iframe",{ref:c,title:t,className:"block w-full border-0 bg-transparent",sandbox:"allow-scripts",scrolling:"no",srcDoc:d,loading:"lazy",style:{height:`${i}px`},onError:()=>{o(!0),r==null||r()}})})}const j_=w.memo(({cfg:e,onDatapointClick:t})=>l.jsx(U0,{cfg:e,onDatapointClick:t}),(e,t)=>JSON.stringify(e.cfg)===JSON.stringify(t.cfg)&&e.onDatapointClick===t.onDatapointClick),Yw=w.memo(oh,(e,t)=>{const n=e.data===t.data,r=e.card===t.card,s=e.isLoading===t.isLoading;return n&&r&&s}),rrt=new Set(["tool-getChartDataFromSqlAndPython","tool-getChartDataFromCardConfig","tool-getForecastDataFromSqlAndPython"]);function srt({part:e,messageId:t,onAddToDashboard:n,messages:r,showTools:s=!1}){var Oe,Ee,le,se,Se,he,fe,Fe,ye,Ne,$e;const o=e.output,i=e.input,a=e==null?void 0:e.toolCallId,[c,u]=w.useState(!1),[d,f]=w.useState(!1),[h,m]=w.useState("visual"),[p,g]=w.useState(!1),[b,x]=w.useState(null),[y,v]=w.useState(!1),C=w.useMemo(()=>a??kr(),[a]),{queueMessage:S}=zp(),N=qD(),j=Xy(),k=YD(t),{tokenProps:_}=w.useContext(t0),E=(_==null?void 0:_.type)==="dashboard";Vo();const T=k?"dashboard":N,M=k||j,F=()=>{const Ue=`Can you explain how this visual was calculated? [ref: ${(D==null?void 0:D.toolCallId)||a}]`;S("dashboard",Ue)},P=()=>{var ie;const Re=r==null?void 0:r.filter(Te=>Te.role==="user").pop(),Ue=(ie=Re==null?void 0:Re.parts)==null?void 0:ie.find(Te=>Te.type==="text"),He=(Ue==null?void 0:Ue.text)||"",Ye=T==="dashboard"?sd.DASHBOARD_ASSISTANT:sd.EDITOR_ASSISTANT,et=mE(Ye,{errorMessage:(o==null?void 0:o.error)||"An error occurred while generating the visualization",toolType:e.type,toolInput:i,toolOutput:o,assistantType:T,userQuery:He,messages:r,aiContext:M,cardConfig:i==null?void 0:i.cardConfig,dataSource:o==null?void 0:o.dataSource,generatedSql:i==null?void 0:i.sql});x(et),g(!0)},D=w.useMemo(()=>{var Ye,et,ie,Te,Pe;if(!(r!=null&&r.length)||!t||!a)return null;const Re=r.find(Ie=>Ie.id===t),Ue=Array.isArray(Re==null?void 0:Re.parts)?Re.parts:[],He=Ue.findIndex(Ie=>(Ie==null?void 0:Ie.type)===e.type&&(Ie==null?void 0:Ie.toolCallId)===a);if(He<=0)return null;for(let Ie=He-1;Ie>=0;Ie-=1){const Ze=Ue[Ie];if(!Ze||Ze.state!=="output-available"||!rrt.has(Ze.type))continue;const ke=Ze.output,We=Ze.input,ct=((Ye=ke==null?void 0:ke.data)==null?void 0:Ye.userSql)||((et=ke==null?void 0:ke.data)==null?void 0:et.sql)||(We==null?void 0:We.sql),Be=((ie=ke==null?void 0:ke.data)==null?void 0:ie.python)||(We==null?void 0:We.python);if(!(!ct&&!Be))return{toolCallId:Ze.toolCallId,sql:ct,python:Be,cardConfig:((Te=ke==null?void 0:ke.data)==null?void 0:Te.cardConfig)||(We==null?void 0:We.cardConfig),chartType:((Pe=ke==null?void 0:ke.data)==null?void 0:Pe.chartType)||(We==null?void 0:We.chartType)}}return null},[t,r,e.type,a]),L=(i==null?void 0:i.chartType)||(D==null?void 0:D.chartType),z=i==null?void 0:i.connectionId,U=(i==null?void 0:i.cardConfig)||(D==null?void 0:D.cardConfig),B=i==null?void 0:i.chartTitle,R=i==null?void 0:i.sql,O=((Oe=o==null?void 0:o.data)==null?void 0:Oe.userSql)||((Ee=o==null?void 0:o.data)==null?void 0:Ee.sql)||R||(D==null?void 0:D.sql),I=(i==null?void 0:i.python)||(D==null?void 0:D.python),W=(le=o==null?void 0:o.data)==null?void 0:le.records,X=o==null?void 0:o.dataSource,Z=o==null?void 0:o.customVisualPreferences,$=o==null?void 0:o.dynamicVisual,Y=($==null?void 0:$.renderer)==="dynamic-visual",q=(o==null?void 0:o.suppressVisualRender)&&!Y&&!(o!=null&&o.error),H=(Y?(se=$==null?void 0:$.fallback)==null?void 0:se.chartType:L)||"table",K=($==null?void 0:$.title)||B||"Untitled Chart";w.useEffect(()=>{v(!1)},[$==null?void 0:$.artifactId]);const G=cw(W??[],hTe),J=cw(X),re=cw(U),me=cw(H),ee=Y&&((G==null?void 0:G.length)||0)>0||me!=="table"&&me!=="pivotTable"&&me!=="detailTable",xe=Y&&($==null?void 0:$.status)==="fallback"?`Dynamic fallback: ${((Se=$.error)==null?void 0:Se.stage)==="html_validation"?"HTML validation failed":((he=$.error)==null?void 0:he.stage)==="html_generation"?"HTML generation failed":((fe=$.error)==null?void 0:fe.stage)==="row_cap"?"row cap exceeded":((Fe=$.error)==null?void 0:Fe.stage)==="query"?"query fallback":((ye=$.fallback)==null?void 0:ye.reason)||"fallback used"}`:null,oe=w.useMemo(()=>me?{id:C,config:re,type:me,dataSource:J,preferences:{tablePrefs:{pageSize:10,forceClientPagination:!0}}}:null,[C,re,me,J]),de=w.useMemo(()=>!oe||me==="pivotTable"||me==="detailTable"?null:nP({card:oe,cardType:me,data:G||[],queryConfig:{}}),[oe,me,G]),Ce=w.useMemo(()=>{var et,ie,Te,Pe;if(me!=="pivotTable"||!o)return null;const Re=((et=o.data)==null?void 0:et.pivotSchema)||[],Ue=((ie=o.data)==null?void 0:ie.subtotalColumns)||[],He=(Te=o.data)==null?void 0:Te.columnSubtotalMeta,Ye=(Pe=o.data)==null?void 0:Pe.groupByColumns;return{records:G||[],pivotSchema:Re,subtotalColumns:Ue,columnSubtotalMeta:He,groupByColumns:Ye}},[me,o,G]),je=Cg(oe,Ce),ge=(()=>{const Re=oe?jl(oe.config):!1,Ue=Uj.find(Ye=>Ye.id===me),He=Ue==null?void 0:Ue.icon;return I?{type:"advanced",label:"Advanced Analysis",icons:[pl,TT]}:Re&&He?{type:"standard",label:"Standard Analysis",icons:[He]}:{type:"sql",label:"SQL Analysis",icons:[pl]}})();if(!o||q)return null;if(o.error){const Re=o.errorType||"unknown",Ue=o.hint||"",He=o.rootCause||o.error,Ye=o.shouldRetry!==!1,et=o.validationErrors||[],ie=o.suggestions||[],Te=et.length>0,Pe=Te?{border:"border-purple-500/60 dark:border-purple-500/50",bg:"bg-purple-50 dark:bg-purple-500/10",text:"text-purple-800 dark:text-purple-300",iconColor:"text-purple-600 dark:text-purple-500",accentBg:"bg-purple-100 dark:bg-purple-900/30",accentText:"text-purple-900 dark:text-purple-200"}:{border:"border-yellow-500/60 dark:border-yellow-500/50",bg:"bg-yellow-50 dark:bg-yellow-500/10",text:"text-yellow-800 dark:text-yellow-300",iconColor:"text-yellow-600 dark:text-yellow-500",accentBg:"bg-yellow-100 dark:bg-yellow-900/30",accentText:"text-yellow-900 dark:text-yellow-200"},Ie=()=>Te?Ye?"Configuration validation failed. Retrying...":"Configuration validation failed":Re==="group_by_error"?Ye?"SQL grouping error. Retrying...":"SQL grouping error":Re==="syntax_error"?Ye?"SQL syntax error. Retrying...":"SQL syntax error":Re==="type_mismatch"?Ye?"Data type mismatch. Retrying...":"Data type mismatch":Ye?"Retrying...":"Couldn't generate this visual";if(!s){const Ze=Ye?"Let me try that a different way...":"I'm ready with a revised plan.",ke=Ue||(He&&He!==o.error?He:"");return l.jsx("div",{className:"mt-2 rounded-md border border-border/40 bg-muted/30 p-3 text-xs",children:l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(X1,{className:"size-4 shrink-0 text-primary","aria-hidden":"true"}),l.jsxs("div",{className:"space-y-1 text-foreground/80",children:[l.jsx("div",{className:"font-medium text-foreground",children:Ze}),ke&&l.jsx("div",{className:"text-[11px] text-muted-foreground",children:ke})]})]})})}return l.jsxs(l.Fragment,{children:[l.jsx(ho,{open:d,onOpenChange:f,children:l.jsxs("div",{className:`relative space-y-2 rounded-md border ${Pe.border} ${Pe.bg} p-3 text-xs`,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Hp,{className:`size-4 shrink-0 ${Pe.iconColor}`,"aria-hidden":"true"}),l.jsx("span",{className:`font-medium ${Pe.text}`,children:Ie()})]}),Te&&l.jsx("div",{className:`text-[10px] ${Pe.text} opacity-80`,children:"Self-healing defense: Config validated before execution"}),He&&He!==o.error&&l.jsxs("div",{className:"text-foreground/80",children:[l.jsx("span",{className:"font-semibold",children:"Issue:"})," ",He]}),Ue&&l.jsxs("div",{className:`rounded-md ${Pe.accentBg} p-2 ${Pe.accentText}`,children:[l.jsx("span",{className:"font-semibold",children:"Fix:"})," ",Ue]}),et.length>0&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:`font-semibold ${Pe.text}`,children:"Configuration issues found:"}),l.jsxs("ul",{className:"ml-4 list-disc space-y-0.5",children:[et.slice(0,3).map((Ze,ke)=>l.jsx("li",{className:"text-foreground/70 dark:text-foreground/60",children:Ze},ke)),et.length>3&&l.jsxs("li",{className:"text-muted-foreground",children:["...and ",et.length-3," more"]})]})]}),l.jsxs("div",{className:"flex items-center justify-between pt-1",children:[l.jsx(mo,{asChild:!0,children:l.jsxs(ne,{variant:"ghost",size:"sm",className:`gap-1 text-[11px] ${Pe.text}`,children:[d?"Hide":"View"," technical details",l.jsx(vr,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),l.jsxs(ne,{variant:"ghost",size:"sm",className:`gap-1 text-[11px] ${Pe.text}`,onClick:P,children:[l.jsx(bA,{className:"h-3 w-3"}),"Report Issue"]})]}),l.jsxs(po,{className:"mt-2 space-y-2",children:[ie.length>0&&l.jsxs("div",{className:"rounded-md border border-blue-500/40 bg-background/60 p-2 dark:bg-background/40",children:[l.jsx("div",{className:"mb-1 text-[11px] font-semibold text-blue-900 dark:text-blue-200",children:"Suggested fixes:"}),l.jsx("ul",{className:"ml-3 list-disc space-y-1",children:ie.map((Ze,ke)=>l.jsx("li",{className:"text-[11px] leading-relaxed text-foreground/80",children:Ze},ke))})]}),l.jsxs("div",{className:`rounded-md border ${Pe.border} bg-background/60 p-2 dark:bg-background/40`,children:[l.jsx("div",{className:`mb-1 text-[11px] font-semibold ${Pe.text}`,children:"Raw error:"}),l.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-foreground/80",children:o.error})]})]})]})}),b&&l.jsx(Dy,{open:p,onOpenChange:Ze=>{g(Ze),Ze||x(null)},feedbackData:b})]})}return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid w-full max-w-full grid-cols-1",children:[xe&&l.jsx("div",{className:"flex justify-start pb-2",children:l.jsx(tt,{variant:"outline",className:"border-amber-500/40 bg-amber-500/10 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:xe})}),!Y&&l.jsx("div",{className:"pb-2",children:l.jsx("h3",{className:"text-sm font-semibold text-foreground",children:K})}),l.jsxs("div",{children:[l.jsx("div",{className:Q("isolate flex w-full grow flex-col",me!=="table"&&me!=="pivotTable"&&me!=="detailTable"&&me!=="custom"&&"min-h-[360px]"),children:l.jsx("div",{className:"flex grow flex-col",children:Y?h==="table"||!($!=null&&$.html)||y?((Ne=$==null?void 0:$.fallback)==null?void 0:Ne.mode)==="chart"&&de&&h!=="table"?l.jsx(j_,{cfg:de}):oe?l.jsx("div",{className:"min-w-0",children:l.jsx(Yw,{card:oe,data:G||[],isLoading:!1})}):l.jsx("div",{className:"flex min-h-[240px] items-center justify-center rounded-md border border-dashed border-border/60 bg-muted/20 px-4 text-sm text-muted-foreground",children:"Unable to render the fallback view for this dynamic visual."}):l.jsx(nrt,{html:$.html,title:K,onRuntimeError:()=>v(!0)}):Z&&me==="custom"?h==="table"?l.jsx("div",{className:"min-w-0 pb-6",children:l.jsx(Yw,{card:oe,data:G||[],isLoading:!1})}):l.jsx(Jnt,{customVisualPreferences:Z,data:G||[],cardId:C}):(me==="table"||me==="detailTable")&&oe?l.jsx("div",{className:"min-w-0",children:l.jsx(Yw,{card:oe,data:G||[],isLoading:!1})}):me==="pivotTable"&&je&&oe?l.jsx(J0,{data:je.data,card:oe,options:je.options}):de&&me!=="table"&&me!=="pivotTable"&&me!=="detailTable"?h==="table"?l.jsx("div",{className:"min-w-0 pb-6",children:l.jsx(Yw,{card:oe,data:G||[],isLoading:!1})}):l.jsx(j_,{cfg:de}):de&&l.jsx(j_,{cfg:de})})}),(R||I||Y||ee||oe&&jl(oe.config))&&l.jsxs(ho,{open:c,onOpenChange:u,children:[l.jsxs("div",{className:"flex items-center justify-end gap-2 pt-1",children:[ee&&l.jsx($s,{value:h,onValueChange:m,children:l.jsxs(js,{className:"h-7",children:[l.jsx(sn,{value:"visual",className:"h-6 w-6 p-0","aria-label":"View as chart",children:l.jsx(QS,{className:"h-3 w-3"})}),l.jsx(sn,{value:"table",className:"h-6 w-6 p-0","aria-label":"View as table",children:l.jsx(NA,{className:"h-3 w-3"})})]})}),l.jsx(mo,{asChild:!0,children:l.jsxs(ne,{variant:"outline",size:"sm",className:"h-7 gap-1.5 border-border/50 px-2.5 text-[11px] text-muted-foreground hover:text-foreground",children:[ge.icons.map((Re,Ue)=>l.jsx(Re,{className:"h-3 w-3"},Ue)),l.jsx("span",{children:ge.label}),l.jsx(vr,{className:Q("h-3 w-3 transition-transform",c&&"rotate-180")})]})}),!E&&!Y&&l.jsxs(ne,{variant:"outline",size:"sm",className:"h-7 gap-1.5 border-border/50 px-2.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:()=>{n==null||n({sql:R||"",data:G||[],dataSource:J||pE,cardConfig:U,cardTitle:K,connectionId:z||"",cardType:me||"bar",python:I||"",customVisualPreferences:Z}),Ge.success("Card added to dashboard")},"aria-label":"Add visual to dashboard",children:[l.jsx(qr,{className:"h-3 w-3"}),l.jsx("span",{children:"Add to dashboard"})]})]}),l.jsxs(po,{className:"flex flex-col gap-3 pt-1 pb-4",children:[O&&l.jsxs("div",{className:"overflow-hidden rounded-md border border-border/60 bg-card/50",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-muted/30 px-3 py-1.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(pl,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"font-mono text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"SQL Query"})]}),l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsxs(ne,{variant:"ghost",size:"sm",className:"h-6 gap-1 px-1.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:F,title:"Ask for explanation",children:[l.jsx(xr,{className:"h-3 w-3"}),"Explain"]}),l.jsx(rd,{text:O})]})]}),l.jsx(Ap,{language:"sql",code:O,wrapLongLines:!0})]}),I&&l.jsxs("div",{className:"overflow-hidden rounded-md border border-border/60 bg-card/50",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 bg-muted/30 px-3 py-1.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(TT,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"font-mono text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Python"})]}),l.jsx(rd,{text:I})]}),l.jsx(Ap,{language:"python",code:I,wrapLongLines:!0})]}),Y&&$&&l.jsxs("div",{className:"overflow-hidden rounded-md border border-border/60 bg-card/50",children:[l.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border/50 bg-muted/30 px-3 py-1.5",children:[l.jsx(X1,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"font-mono text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:"Dynamic Visual"})]}),l.jsxs("div",{className:"space-y-0.5 px-3 py-2 font-mono text-[11px] leading-relaxed text-muted-foreground",children:[l.jsxs("div",{children:["Artifact: ",$.artifactId]}),l.jsxs("div",{children:["Provenance: ",$.provenance]}),l.jsxs("div",{children:["Status: ",$.status]}),l.jsxs("div",{children:["Fallback: ",$.fallback.reason]}),(($e=$.error)==null?void 0:$e.message)&&l.jsxs("div",{className:"text-destructive",children:["Error: ",$.error.message]})]})]})]})]})]})]}),b&&l.jsx(Dy,{open:p,onOpenChange:Re=>{g(Re),Re||x(null)},feedbackData:b})]})}const ort=["tool-getChartDataFromSqlAndPython","tool-getChartDataFromCardConfig","tool-getForecastDataFromSqlAndPython","tool-generateQueryConfig","tool-generateDynamicVisual","tool-generateDynamicVisualFromData"];function irt({part:e,idx:t,messageId:n,showTools:r,onAddToDashboard:s,messages:o}){if(!e.state||e.state==="input-streaming"||e.state==="input-available")return null;if(e.state==="output-available"){const i=ort.includes(e.type);return l.jsxs("div",{className:"my-1 space-y-2",children:[r&&l.jsx(Gnt,{part:e,showTools:r}),i&&l.jsx(srt,{part:e,messageId:n,onAddToDashboard:s,messages:o,showTools:r})]},t)}return e.state==="output-error"?r?l.jsx("div",{className:"mt-2",children:l.jsx(Knt,{part:e,messageId:n,messages:o})},t):l.jsx("div",{className:"my-2 rounded-md border border-border/40 bg-muted/30 px-3 py-2 text-sm text-muted-foreground",children:"I hit a snag while working on that and will adjust the approach."},t):l.jsx("div",{},t)}const eV=/```quickreply\s*([\s\S]*?)```/i;function art(e){let t=e,n=null;const r=e.toLowerCase().indexOf("```quickreply");if(r!==-1){const i=e.match(eV);if(i)n=i[1].trim(),t=e.replace(i[0],"").trim();else return{cleanedText:e.slice(0,r).trimEnd(),quickReplies:[]}}else{const i=e.match(eV);i&&(n=i[1].trim(),t=e.replace(i[0],"").trim())}const s=t===e?e.toLowerCase().indexOf("quickreply"):-1;if(!n&&s!==-1){const i=e.indexOf("{",s);if(i!==-1){let a=0,c=-1;for(let u=i;u<e.length;u++){const d=e[u];if(d==="{")a++;else if(d==="}"&&(a--,a===0)){c=u;break}}if(c!==-1)n=e.slice(i,c+1).trim(),t=(e.slice(0,s)+e.slice(c+1)).trim();else return{cleanedText:e.slice(0,s).trimEnd(),quickReplies:[]}}else return{cleanedText:e.slice(0,s).trimEnd(),quickReplies:[]}}let o=[];if(n)try{const i=JSON.parse(n);o=(Array.isArray(i==null?void 0:i.options)?i.options:[]).map(c=>{const u=typeof(c==null?void 0:c.label)=="string"?c.label.trim():"",d=typeof(c==null?void 0:c.value)=="string"?c.value.trim():"";return u&&d?{label:u,value:d}:null}).filter(Boolean)}catch{o=[]}return{cleanedText:t.trim(),quickReplies:o}}function lrt(e){if(e==null)return"Something went wrong.";if(e instanceof Error)return e.message||"Something went wrong.";const t=r=>{if(!r||typeof r!="object")return null;const s=r.error&&typeof r.error=="object"?r.error:r,o=typeof s.code=="string"&&s.code?s.code.trim():"",i=typeof s.docs=="string"&&s.docs?`
1151
1151
  More info: ${s.docs}`:"",a=typeof s.message=="string"&&s.message.trim()?s.message.trim():typeof s.error=="string"&&s.error.trim()?s.error.trim():null;if(a){const c=o?` (code: ${o})`:"",u=o==="insufficient_quota"||a.toLowerCase().includes("quota")?`
1152
1152
 
1153
- Semaphor supports bring-your-own OpenAI API keys. Add yours in Settings or drop a note to support@semaphor.cloud and we’ll help you get set up.`:"";return`${a}${c}${i}${u}`}return null};if(typeof e=="string"){const r=e.trim();if(!r)return"Something went wrong.";try{const s=JSON.parse(r),o=t(s);if(o)return o}catch{}return r}const n=t(e);if(n)return n;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function p5({errorMessage:e}){return l.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-red-500/10 p-2 text-sm text-red-500 backdrop-blur-sm",children:[l.jsx(Hp,{className:"mt-0.5 h-4 w-4 shrink-0"}),l.jsx("span",{className:"whitespace-pre-wrap break-words",children:lrt(e)})]})}function crt({error:e,resetErrorBoundary:t}){return l.jsxs("div",{className:"my-4 space-y-2 rounded-md border border-border/50 bg-muted/20 p-3",children:[l.jsx(p5,{errorMessage:e==null?void 0:e.message}),l.jsx("button",{type:"button",className:"text-xs font-medium text-muted-foreground underline hover:text-foreground",onClick:t,children:"Try again"})]})}function urt({text:e,files:t}){return l.jsxs("div",{className:"group flex gap-2.5",children:[l.jsx("div",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted",children:l.jsx(fme,{className:"size-4 text-muted-foreground"})}),l.jsxs("div",{className:"min-w-0 flex-1 space-y-1 pt-0.5",children:[l.jsxs("div",{className:"space-y-2 text-sm",children:[e&&l.jsx("div",{className:"whitespace-pre-line",children:e}),t&&t.length>0&&l.jsx("div",{className:"flex flex-wrap gap-2",children:t.map(n=>l.jsx(Ynt,{file:n},n.id))})]}),e&&l.jsx("div",{className:"opacity-0 transition-opacity group-hover:opacity-100",children:l.jsx(rd,{text:e,className:"h-5"})})]})]})}function drt({text:e}){const t=e.split("|"),n=t[0],r=t[1]||"{}",s=JSON.parse(r);return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"font-bold",children:"System Message:"})," ",n]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"font-mono text-xs",children:"Scope:"}),l.jsx(LGe,{children:JSON.stringify(s,null,2)})]})]})}function tie({status:e,errorMessage:t,activeToolText:n}){return e==="submitted"||e==="streaming"?l.jsx("div",{className:"h-6 animate-pulse text-[13px] font-medium leading-6 text-muted-foreground",children:n||(e==="submitted"?"Thinking...":"Generating...")}):e==="error"?l.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:l.jsx(p5,{errorMessage:t})}):null}function nie({messages:e,showTools:t=!1,onAddToDashboard:n,showSystemMessage:r=!1,handleRun:s,onQuickReply:o,disableQuickReplies:i=!1}){return l.jsx("div",{children:e==null?void 0:e.map((a,c)=>{var g,b,x,y;if(a.role==="user"){const v=((g=a.parts)==null?void 0:g.filter(j=>j.type==="text"))||[],C=((b=a.parts)==null?void 0:b.filter(j=>j.type==="file"))||[],S=v.map(j=>j.text).join(`
1153
+ Semaphor supports bring-your-own OpenAI API keys. Add yours in Settings or drop a note to support@semaphor.cloud and we’ll help you get set up.`:"";return`${a}${c}${i}${u}`}return null};if(typeof e=="string"){const r=e.trim();if(!r)return"Something went wrong.";try{const s=JSON.parse(r),o=t(s);if(o)return o}catch{}return r}const n=t(e);if(n)return n;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function p5({errorMessage:e}){return l.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-red-500/10 p-2 text-sm text-red-500 backdrop-blur-sm",children:[l.jsx(Hp,{className:"mt-0.5 h-4 w-4 shrink-0"}),l.jsx("span",{className:"whitespace-pre-wrap break-words",children:lrt(e)})]})}function crt({error:e,resetErrorBoundary:t}){return l.jsxs("div",{className:"my-4 space-y-2 rounded-md border border-border/50 bg-muted/20 p-3",children:[l.jsx(p5,{errorMessage:e==null?void 0:e.message}),l.jsx("button",{type:"button",className:"text-xs font-medium text-muted-foreground underline hover:text-foreground",onClick:t,children:"Try again"})]})}function urt({text:e,files:t}){return l.jsxs("div",{className:"group flex items-start gap-2.5",children:[l.jsx("div",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted",children:l.jsx(fme,{className:"size-4 text-muted-foreground"})}),l.jsxs("div",{className:"min-w-0 flex-1 pt-1 text-sm",children:[e&&l.jsx("div",{className:"whitespace-pre-line",children:e}),t&&t.length>0&&l.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:t.map(n=>l.jsx(Ynt,{file:n},n.id))})]}),e&&l.jsx("div",{className:"shrink-0 pt-0.5 opacity-0 transition-opacity group-hover:opacity-100",children:l.jsx(rd,{text:e,className:"h-5"})})]})}function drt({text:e}){const t=e.split("|"),n=t[0],r=t[1]||"{}",s=JSON.parse(r);return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"font-bold",children:"System Message:"})," ",n]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"font-mono text-xs",children:"Scope:"}),l.jsx(LGe,{children:JSON.stringify(s,null,2)})]})]})}function tie({status:e,errorMessage:t,activeToolText:n}){return n?l.jsx("div",{className:"h-6 animate-pulse text-[13px] font-medium leading-6 text-muted-foreground",children:n}):e==="submitted"||e==="streaming"?l.jsx("div",{className:"h-6 animate-pulse text-[13px] font-medium leading-6 text-muted-foreground",children:e==="submitted"?"Thinking...":"Generating..."}):e==="error"?l.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:l.jsx(p5,{errorMessage:t})}):null}function nie({messages:e,showTools:t=!1,onAddToDashboard:n,showSystemMessage:r=!1,handleRun:s,onQuickReply:o,disableQuickReplies:i=!1}){return l.jsx("div",{className:"space-y-5",children:e==null?void 0:e.map((a,c)=>{var g,b,x,y;if(a.role==="user"){const v=((g=a.parts)==null?void 0:g.filter(j=>j.type==="text"))||[],C=((b=a.parts)==null?void 0:b.filter(j=>j.type==="file"))||[],S=v.map(j=>j.text).join(`
1154
1154
  `).trim(),N=C.map((j,k)=>{var T,M;let _="",E;if((T=j.url)!=null&&T.startsWith("data:")){const F=j.url.match(/data:[^;]+;base64,(.+)/);F&&(_=F[1],(M=j.mediaType)!=null&&M.startsWith("image/")&&(E=j.url))}return{id:`${a.id||c}-file-${k}`,name:j.filename||`File ${k+1}`,size:0,type:j.mediaType||"application/octet-stream",data:_,preview:E}});return l.jsx(urt,{text:S||void 0,files:N.length>0?N:void 0},a.id||c)}const u=((x=a.parts)==null?void 0:x.filter(v=>v.type==="reasoning"))||[],d=u.length>0,f=u.some(v=>v.state==="streaming"),h=u.filter(v=>v.text&&v.text.trim().length>0),m=d&&(h.length>0||f)?l.jsxs(ho,{className:"my-2",defaultOpen:!1,children:[l.jsx(mo,{asChild:!0,children:l.jsxs(ne,{variant:"ghost",size:"sm",className:"group h-auto gap-1 px-1 py-0.5 text-xs text-muted-foreground hover:text-foreground",children:[l.jsx(vs,{className:"h-3.5 w-3.5 transition-transform duration-200 group-data-[state=open]:rotate-90"}),l.jsxs("span",{className:f?"animate-pulse":"",children:[f?"Reasoning...":"Show reasoning",h.length>1&&` (${h.length} steps)`]})]})}),l.jsx(po,{className:"mt-3",children:l.jsx("div",{children:h.map((v,C)=>l.jsxs("div",{className:"flex gap-3 pb-3",children:[l.jsxs("div",{className:"flex flex-col items-center pt-0.5",children:[l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background text-xs font-medium text-foreground",children:C+1}),C<h.length-1&&l.jsx("div",{className:"mt-1 w-px flex-1 bg-border"})]}),l.jsx("div",{className:"flex-1 pt-0.5",children:l.jsx(X9,{className:"text-sm text-muted-foreground",text:v.text})})]},`${a.id||c}-reasoning-${C}`))})})]},`${a.id||c}-reasoning`):null,p=(y=a.parts)==null?void 0:y.map((v,C)=>{var N;const S=`${a.id||c}-${C}`;switch(v.type){case"text":{const j=typeof v.text=="string"?v.text:JSON.stringify(v.text??"",null,2);if(a.role==="assistant"){const{cleanedText:k,quickReplies:_}=art(j),E=k.trim().length>0;return l.jsxs("div",{className:"my-4 space-y-3",children:[E&&l.jsx(X9,{text:k,handleRun:s,onAddToDashboard:n,messageId:a.id,messages:e}),_.length>0&&o&&l.jsxs("div",{className:"mt-3 space-y-2",children:[_.length>=3&&l.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Suggested next steps"}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:_.map(({label:T,value:M},F)=>l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsx(ne,{size:"sm",variant:"outline",className:"h-7 rounded-full border-border/50 bg-muted/40 px-3 text-xs font-normal text-foreground/80 transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",disabled:i,onClick:()=>o(M),children:T})}),l.jsx(Tn,{side:"top",align:"center",children:l.jsx("p",{className:"max-w-xs text-xs",children:M})})]},`${S}-qr-${F}`))})]})]},S)}return a.role==="system"&&r?l.jsx(drt,{text:j},S):null}case"error":{const j=v,k=j.errorText??j.error??j.message;return l.jsx("div",{className:"my-4",children:l.jsx(p5,{errorMessage:k})},S)}case"reasoning":return null;default:return(N=v.type)!=null&&N.startsWith("tool-")||v.type==="dynamic-tool"?l.jsx(Fa,{FallbackComponent:({error:j,resetErrorBoundary:k})=>l.jsx(crt,{error:j,resetErrorBoundary:k}),children:l.jsx(irt,{part:v,idx:S,messageId:a.id,showTools:t,onAddToDashboard:n,messages:e})},S):null}});return l.jsxs("div",{children:[m,p]},a.id||c)})})}function rie({placeholders:e,onClick:t}){return l.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:e==null?void 0:e.map(n=>l.jsxs("div",{onClick:()=>t(n),className:"cursor-pointer rounded-xl border border-border/50 bg-muted/30 px-3 py-2.5 transition-colors hover:bg-muted/60",children:[l.jsx("p",{className:"text-xs font-medium text-foreground/80",children:n.title}),l.jsx("p",{className:"text-xs text-muted-foreground/60",children:n.subtitle})]},n.title))})}var sie="vercel.ai.error",frt=Symbol.for(sie),oie,hrt=class iie extends Error{constructor({name:t,message:n,cause:r}){super(n),this[oie]=!0,this.name=t,this.cause=r}static isInstance(t){return iie.hasMarker(t,sie)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};oie=frt;var od=hrt;function aie(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var lie="AI_InvalidArgumentError",cie=`vercel.ai.error.${lie}`,mrt=Symbol.for(cie),uie,prt=class extends od{constructor({message:e,cause:t,argument:n}){super({name:lie,message:e,cause:t}),this[uie]=!0,this.argument=n}static isInstance(e){return od.hasMarker(e,cie)}};uie=mrt;var die="AI_JSONParseError",fie=`vercel.ai.error.${die}`,grt=Symbol.for(fie),hie,tV=class extends od{constructor({text:e,cause:t}){super({name:die,message:`JSON parsing failed: Text: ${e}.
1155
1155
  Error message: ${aie(t)}`,cause:t}),this[hie]=!0,this.text=e}static isInstance(e){return od.hasMarker(e,fie)}};hie=grt;var mie="AI_TypeValidationError",pie=`vercel.ai.error.${mie}`,brt=Symbol.for(pie),gie,xrt=class eD extends od{constructor({value:t,cause:n}){super({name:mie,message:`Type validation failed: Value: ${JSON.stringify(t)}.
1156
1156
  Error message: ${aie(n)}`,cause:n}),this[gie]=!0,this.value=t}static isInstance(t){return od.hasMarker(t,pie)}static wrap({value:t,cause:n}){return eD.isInstance(n)&&n.value===t?n:new eD({value:t,cause:n})}};gie=brt;var jS=xrt;class nV extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function E_(e){}function yrt(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=E_,onError:n=E_,onRetry:r=E_,onComment:s}=e;let o="",i=!0,a,c="",u="";function d(g){const b=i?g.replace(/^\xEF\xBB\xBF/,""):g,[x,y]=vrt(`${o}${b}`);for(const v of x)f(v);o=y,i=!1}function f(g){if(g===""){m();return}if(g.startsWith(":")){s&&s(g.slice(g.startsWith(": ")?2:1));return}const b=g.indexOf(":");if(b!==-1){const x=g.slice(0,b),y=g[b+1]===" "?2:1,v=g.slice(b+y);h(x,v,g);return}h(g,"",g)}function h(g,b,x){switch(g){case"event":u=b;break;case"data":c=`${c}${b}
@@ -1192,8 +1192,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1192
1192
 
1193
1193
  `)},flush(e){e.enqueue(`data: [DONE]
1194
1194
 
1195
- `)}})}});var Olt=Iat(()=>Xie(Qi([Mr({type:rn("text-start"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("text-delta"),id:Et(),delta:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("text-end"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("error"),errorText:Et()}),Mr({type:rn("tool-input-start"),toolCallId:Et(),toolName:Et(),providerExecuted:Ko().optional(),dynamic:Ko().optional()}),Mr({type:rn("tool-input-delta"),toolCallId:Et(),inputTextDelta:Et()}),Mr({type:rn("tool-input-available"),toolCallId:Et(),toolName:Et(),input:el(),providerExecuted:Ko().optional(),providerMetadata:Xr.optional(),dynamic:Ko().optional()}),Mr({type:rn("tool-input-error"),toolCallId:Et(),toolName:Et(),input:el(),providerExecuted:Ko().optional(),providerMetadata:Xr.optional(),dynamic:Ko().optional(),errorText:Et()}),Mr({type:rn("tool-output-available"),toolCallId:Et(),output:el(),providerExecuted:Ko().optional(),dynamic:Ko().optional(),preliminary:Ko().optional()}),Mr({type:rn("tool-output-error"),toolCallId:Et(),errorText:Et(),providerExecuted:Ko().optional(),dynamic:Ko().optional()}),Mr({type:rn("reasoning-start"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("reasoning-delta"),id:Et(),delta:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("reasoning-end"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("source-url"),sourceId:Et(),url:Et(),title:Et().optional(),providerMetadata:Xr.optional()}),Mr({type:rn("source-document"),sourceId:Et(),mediaType:Et(),title:Et(),filename:Et().optional(),providerMetadata:Xr.optional()}),Mr({type:rn("file"),url:Et(),mediaType:Et(),providerMetadata:Xr.optional()}),Mr({type:qie(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Et().optional(),data:el(),transient:Ko().optional()}),Mr({type:rn("start-step")}),Mr({type:rn("finish-step")}),Mr({type:rn("start"),messageId:Et().optional(),messageMetadata:el().optional()}),Mr({type:rn("finish"),finishReason:Uie(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:el().optional()}),Mr({type:rn("abort")}),Mr({type:rn("message-metadata"),messageMetadata:el()})])));function Llt(e){return e.type.startsWith("data-")}function oae(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=oae(o,s):n[r]=s}return n}function $lt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function iae(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await MS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await MS({text:$lt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function I1(e){return e.type.startsWith("tool-")}function zlt(e){return e.type==="dynamic-tool"}function iD(e){return I1(e)||zlt(e)}function MV(e){return e.type.split("-").slice(1).join("-")}function Vlt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Blt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(C){const N=u.message.parts.filter(I1).find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(C){const N=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(C){var S;const N=u.message.parts.find(_=>I1(_)&&_.toolCallId===C.toolCallId),j=C,k=N;N!=null?(N.state=C.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(S=j.providerExecuted)!=null?S:N.providerExecuted,j.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(C){var S,N;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),k=C,_=j;j!=null?(j.state=C.state,_.toolName=C.toolName,_.input=k.input,_.output=k.output,_.errorText=k.errorText,_.rawInput=(S=k.rawInput)!=null?S:_.rawInput,_.preliminary=k.preliminary,_.providerExecuted=(N=k.providerExecuted)!=null?N:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function v(C){if(C!=null){const S=u.message.metadata!=null?oae(u.message.metadata,C):C;t!=null&&await EV({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(m=a.providerMetadata)!=null?m:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(I1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:S}=await iae(C.text);C.dynamic?y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:MV(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:MV(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Llt(a)){(n==null?void 0:n[a.type])!=null&&await EV({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const S=C.id!=null?u.message.parts.find(N=>C.type===N.type&&C.id===N.id):void 0;S!=null?S.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function Ult({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}bv({prefix:"aitxt",size:24});bv({prefix:"aiobj",size:24});var Hlt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};bv({prefix:"aiobj",size:24});var Wlt={};klt(Wlt,{object:()=>Ylt,text:()=>qlt});var qlt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Ylt=({schema:e})=>{const t=jlt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await iae(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await MS({text:n});if(!s.success)throw new TV({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await C5({value:s.value,schema:t});if(!o.success)throw new TV({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Glt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Klt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Jh(this.body),c=await Jh(this.headers),u=await Jh(this.credentials),d={...qd(c),...qd(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?qd(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:NV({"Content-Type":"application/json",...m},`ai-sdk/${IV}`,SV()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Jh(this.body),a=await Jh(this.headers),c=await Jh(this.credentials),u={...qd(a),...qd(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?qd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:NV(h,`ai-sdk/${IV}`,SV()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},N5=class extends Klt{constructor(e={}){super(e)}processResponseStream(e){return Aat({stream:e,schema:Olt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Zlt=class{constructor({generateId:e=Sat,id:t=e(),transport:n=new N5,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Hlt,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await Glt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(C=>iD(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>iD(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:Vlt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Ult({stream:Blt({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function aae({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(iD).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Xlt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Qlt=Xlt;const Jlt=hh(Qlt);var lae=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},gr=(e,t,n)=>(lae(e,t,"read from private field"),n?n.call(e):t.get(e)),Ga=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},au=(e,t,n,r)=>(lae(e,t,"write to private field"),t.set(e,n),n);function ect(e,t){return t!=null?Jlt(e,t):e}var Ri,M1,D1,Xb,Qb,Jb,am,aD,lD,tct=class{constructor(e=[]){Ga(this,Ri,void 0),Ga(this,M1,"ready"),Ga(this,D1,void 0),Ga(this,Xb,new Set),Ga(this,Qb,new Set),Ga(this,Jb,new Set),this.pushMessage=t=>{au(this,Ri,gr(this,Ri).concat(t)),gr(this,am).call(this)},this.popMessage=()=>{au(this,Ri,gr(this,Ri).slice(0,-1)),gr(this,am).call(this)},this.replaceMessage=(t,n)=>{au(this,Ri,[...gr(this,Ri).slice(0,t),this.snapshot(n),...gr(this,Ri).slice(t+1)]),gr(this,am).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ect(t,n):t;return gr(this,Xb).add(r),()=>{gr(this,Xb).delete(r)}},this["~registerStatusCallback"]=t=>(gr(this,Qb).add(t),()=>{gr(this,Qb).delete(t)}),this["~registerErrorCallback"]=t=>(gr(this,Jb).add(t),()=>{gr(this,Jb).delete(t)}),Ga(this,am,()=>{gr(this,Xb).forEach(t=>t())}),Ga(this,aD,()=>{gr(this,Qb).forEach(t=>t())}),Ga(this,lD,()=>{gr(this,Jb).forEach(t=>t())}),au(this,Ri,e)}get status(){return gr(this,M1)}set status(e){au(this,M1,e),gr(this,aD).call(this)}get error(){return gr(this,D1)}set error(e){au(this,D1,e),gr(this,lD).call(this)}get messages(){return gr(this,Ri)}set messages(e){au(this,Ri,[...e]),gr(this,am).call(this)}};Ri=new WeakMap;M1=new WeakMap;D1=new WeakMap;Xb=new WeakMap;Qb=new WeakMap;Jb=new WeakMap;am=new WeakMap;aD=new WeakMap;lD=new WeakMap;var lm,DV=class extends Zlt{constructor({messages:e,...t}){const n=new tct(e);super({...t,state:n}),Ga(this,lm,void 0),this["~registerMessagesCallback"]=(r,s)=>gr(this,lm)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>gr(this,lm)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>gr(this,lm)["~registerErrorCallback"](r),au(this,lm,n)}};lm=new WeakMap;function cae({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new DV(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DV(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function nct(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function rct(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function sct(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function oct(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function uae(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:oct(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function dae(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function yE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function fae(e,t,n){const r=yE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>ZN(o)).filter(o=>o!==void 0).map(s)}function hae(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function ict(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function bm(e){return(e||[]).map(ict)}function mae(e){return bm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function j5(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function act(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...j5(s)}})}function lct(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...j5(t)}))}function pae(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function M_(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>pae(s,`${t}:${r}:${o}`)))}function cct(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function uct(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function dct(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(uct).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...j5(r)})),n=e.filter(cct).map((r,s)=>pae(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function fct({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=kD(e.id,t),s=t[xa],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>M_(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>M_(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>M_(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function gae(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>gae(t)).filter(Boolean)}:null}function bae(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==ID.trim()}function hct(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":bae(e)?"custom-python":"config"}function xae({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=yE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=y0({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=x0({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=dct(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:act(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:lct(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:fct({card:t,interactionStates:i,currentDashboardId:r.id})}}function mct({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=xae({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:bm(c.metricColumns),dimensions:mae(c),selectedEntities:hae(t)}}function pct({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function AV({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=yE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:BC(e.filters,n,r)}}function gct({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=yE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=fae(e,t.selectedSheetId,s),c=Gc(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>mct({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:pct({activeFilters:t.activeFilters})}}function bct({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var v,C;const c=fae(e,t.selectedSheetId,i).find(({sourceCard:S,visibleCard:N})=>S.id===n||N.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:p,interactionFilterValues:g}=xae({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:b,targetValue:x}=Gne(h,d.type),y=hct(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:y,...(v=d.sql)!=null&&v.trim()?{sql:d.sql.trim()}:{},...bae(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:hae(d),metrics:bm(h.metricColumns),dimensions:mae(h),comparison:b!=="none"?{type:b,...x!==void 0?{targetValue:x}:{}}:null,cardFilters:gae(h.filters),effectiveDashboardFilters:m,activeInlineFilters:p,activeInteractionFilters:g,sortingOrGroupingSummary:{groupBy:bm(h.groupByColumns),pivotBy:bm(h.pivotByColumns),sortBy:bm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...y==="custom-sql"?["This card runs custom SQL."]:y==="custom-python"?["This card runs custom Python."]:[]]}}function bb(e,t,n){const r=e.getPropertyValue(t).trim();return r?`hsl(${r})`:n}function xct(){if(typeof document>"u")return{mode:"light",background:"hsl(0 0% 100%)",foreground:"hsl(240 10% 3.9%)",muted:"hsl(240 3.8% 46.1%)",border:"hsl(240 5.9% 90%)",accent:"hsl(240 5.9% 10%)"};const e=document.documentElement,t=window.getComputedStyle(e);return{mode:e.classList.contains("dark")?"dark":"light",background:bb(t,"--semaphor-background","hsl(0 0% 100%)"),foreground:bb(t,"--semaphor-foreground","hsl(240 10% 3.9%)"),muted:bb(t,"--semaphor-muted-foreground","hsl(240 3.8% 46.1%)"),border:bb(t,"--semaphor-border","hsl(240 5.9% 90%)"),accent:bb(t,"--semaphor-primary","hsl(240 5.9% 10%)")}}async function yct({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",os.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>dr(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=zK(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function vct({dynamicVisualMode:e="auto"}={}){var N;const{authToken:t,tokenProps:n}=it(),r=ps(),s=te(j=>j.dashboard.aiScopeTables),o=(N=ZS().data)==null?void 0:N.assistantProfileId,i=w.useRef(null),a=w.useRef(e);a.current=e;function c(){const j=Cs.getState(),k=te.getState(),_=BK({overrides:j.dashboardEntitySelectionOverrides,dashboardId:k.dashboard.id,draftScopeKey:k.dashboardAssistantDraftScopeKey});return WD(dTe({currentAIContext:j.currentAIContext,manualSelectedEntities:_.selectedEntities,hasManualOverride:_.hasManualOverride,dashboardAIContext:k.dashboard.aiContext,derivedSelectedSheetEntities:VK(k.dashboard,k.selectedSheetId)}))}function u(){const j=te.getState();return{aiContext:c(),dashboardViewState:AV({dashboard:j.dashboard,selectedSheetId:j.selectedSheetId,activeFilters:j.filterValues})}}const{sendMessage:d,messages:f,setMessages:h,regenerate:m,status:p,addToolResult:g,error:b,stop:x,clearError:y}=cae({transport:new N5({api:`${n.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${t==null?void 0:t.accessToken}`}),body:()=>{const j=Cs.getState();i.current||(i.current=u());const{aiContext:k,dashboardViewState:_}=i.current;return{assistantId:"dashboard-assistant",assistantProfileId:o,aiContext:k,dashboardViewState:_,dynamicVisualMode:a.current,dynamicVisualTheme:xct(),reasoningEffort:j.reasoningEffort,showReasoning:j.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:j,body:k})=>({body:{...k,messages:o7(j)}})}),onToolCall:v,sendAutomaticallyWhen:aae,onFinish({message:j,isAbort:k,isDisconnect:_,isError:E}){var T;j!=null&&j.id&&((T=i.current)!=null&&T.aiContext)&&Cs.getState().actions.setAssistantMessageContext(j.id,i.current.aiContext),console.log(k?"[Dashboard Assistant] Stream aborted by user":_?"[Dashboard Assistant] Stream disconnected (network error)":E?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),i.current=null},onError(j){var k;if(j.name==="AbortError"||(k=j.message)!=null&&k.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),i.current=null;return}console.error("[Dashboard Assistant] Stream error:",j),i.current=null}});async function v({toolCall:j}){var P,D;if(j.toolName==="getCurrentTableScope"){g({tool:j.toolName,toolCallId:j.toolCallId,output:{tables:uae(s||[])}});return}const k=te.getState().dashboard,_=te.getState().inlineFilterValuesMap,E=Vt.getState(),T=E.interactionStates,M=await yct({replacedCards:E.replacedCards,apiServiceUrl:n.apiServiceUrl,accessToken:(t==null?void 0:t.accessToken)||"",queryClient:r}),F=AV({dashboard:k,selectedSheetId:te.getState().selectedSheetId,activeFilters:te.getState().filterValues});if(j.toolName==="getDashboardSynopsis"){g({tool:j.toolName,toolCallId:j.toolCallId,output:gct({dashboard:k,viewState:F,interactionStates:T,inlineFilterValuesMap:_,replacedCards:M})});return}if(j.toolName==="getCardContext"){const L=((P=j.input)==null?void 0:P.cardId)||((D=j.args)==null?void 0:D.cardId)||"";g({tool:j.toolName,toolCallId:j.toolCallId,output:bct({dashboard:k,viewState:F,cardId:L,runtimeFilterValues:te.getState().filterValues,interactionStates:T,inlineFilterValuesMap:_,replacedCards:M})})}}const C=!["ready","error"].includes(p),S=dae(b);return{sendMessage:d,regenerate:m,isLoading:C,messages:f,setMessages:h,status:p,stop:x,errorMessage:S,clearError:y}}function yae(){var u;const{authToken:e,tokenProps:t}=it(),n=(u=ZS().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=Xt({queryKey:["assistant-profile",n],queryFn:()=>dr(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function vae({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(G7,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(ne,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function wct({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ac-n;if(c.length>u){Ge.error(`You can only attach ${ac} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=eie(c);if(f.forEach(({file:h,error:m})=>{Ge.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>m5(m)));e(h)}catch(h){console.error("Failed to process files:",h),Ge.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ac}),l.jsx(ne,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ac,title:n>=ac?`Maximum ${ac} files allowed`:"Attach files",children:l.jsx(yA,{className:"h-4 w-4 text-muted-foreground"})})]})}function Cct({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=ac-r;if(h.length>m){Ge.error(`You can only attach ${ac} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=eie(h);if(g.forEach(({file:b,error:x})=>{Ge.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>m5(x)));t(b),Ge.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Ge.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:Q("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(_A,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ac-r," slot(s) available"]})]})})]})}function wae(e){return e.type==="dataset"&&e.label||e.name}function Sct(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function Nct({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(pe,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(tt,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),wae(n),l.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:l.jsx(Tt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function jct(e){const{tokenProps:t}=it(),n=te(c=>c.authToken)||e;ze(c=>c.selectedConnectionId),ze(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=Xt({queryKey:["semantic-domains"],queryFn:()=>dr(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function Ect(e,t){const{tokenProps:n}=it(),r=te(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=Xt({queryKey:["datasets",e],queryFn:()=>dr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function kct(e){var g,b;const{tokenProps:t}=it(),n=te(x=>x.authToken)||e,{connections:r}=ra(e),s=ze(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=Xt({queryKey:["databases",s],queryFn:()=>dr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function _ct(e){var g;const{tokenProps:t}=it(),n=te(b=>b.authToken)||e,{connections:r}=ra(e),s=ze(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ze(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=Xt({queryKey:["schemas",s,o],queryFn:()=>dr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function Cae(e){const{tokenProps:t}=it(),n=te(h=>h.authToken)||e,{connections:r}=ra(e),s=ze(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:c,error:u,refetch:d}=Xt({queryKey:["dataModels",s],queryFn:()=>dr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:c,error:u,dataModels:f||[],refetch:d}}function Tct(){var S,N,j;const e=ze(k=>k.card.dataSource);ze(k=>k.actions.updateDirectSource);const t=ze(k=>k.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=ra(),{databases:i,isPending:a,error:c,label:u}=kct(),{schemas:d,isPending:f,error:h,label:m}=_ct(),{error:p}=Cae(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=k=>{e&&t({...e,dbSelection:{database:k,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},C=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(ne,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[b&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:u}),l.jsxs(xt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(In,{className:"h-4 w-4 animate-spin"}),l.jsx(vt,{placeholder:c?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),l.jsx(gt,{children:i.map(k=>l.jsx(_e,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:m}),l.jsxs(xt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:C,disabled:f,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(In,{className:"h-4 w-4 animate-spin"}),l.jsx(vt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(gt,{children:d.map(k=>l.jsx(_e,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function Ict(){const e=ze(c=>c.card.dataSource),t=ze(c=>c.actions.updateDataSource),[n,r]=w.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:"Upload Files"}),l.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(_A,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(ne,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(pe,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(Ma,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Tt,{className:"h-3 w-3"})})]},c.id))})]})]})}function Mct(){const e=ze(f=>f.card.dataSource),t=ze(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),c=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(Pt,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(Pt,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"Type"}),l.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(ne,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(qr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(pe,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(tN,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Tt,{className:"h-3 w-3"})})]},f.id))})]})]})}function Dct(e,t){var y,v;const{tokenProps:n}=it(),r=te(C=>C.authToken)||t,{connections:s}=ra(t),o=ze(C=>{var S,N;return(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.connectionId}),i=ze(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.database}),a=ze(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(C=>C.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const C=(u==null?void 0:u.path)||[];return!(C.includes("database")&&!i||C.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=Xt({queryKey:[e,o,i,a],queryFn:()=>dr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(C=>{var S;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(S=C==null?void 0:C.table_type)==null?void 0:S.toLowerCase(),id:C[`${e}_name`],database:i,schema:a,name:C[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function DS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx(Lc,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function Act({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=ra(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=_r(),{entities:p,isLoading:g,error:b}=Dct("table"),{dataModels:x,isPending:y,error:v}=Cae(),C=E=>{const T=s.find(F=>F.id===E);if(!T)return;const M=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},S=E=>{var P,D;const T=n||[],M=T.some(L=>L.name===E.name&&L.type===E.type);let F;if(M)F=T.filter(L=>!(L.name===E.name&&L.type===E.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((P=e.dbSelection)==null?void 0:P.database)||"",schema:((D=e.dbSelection)==null?void 0:D.schema)||"",name:E.name,dialect:E.dialect};F=[...T,L]}t==null||t(F)},N=E=>{const T=n||[],M=T.some(P=>P.type==="model"&&P.name===E.name);let F;M?F=T.filter(P=>!(P.type==="model"&&P.name===E.name)):F=[...T,E],t==null||t(F)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=x.filter(E=>E.name.toLowerCase().includes(c.toLowerCase())),_=w.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const F=j.filter(P=>!E.some(D=>D.name===P.name&&D.type==="table")).map(P=>{var D,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:P.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:P.name,dialect:P.dialect}});T=[...E,...F]}else if(d==="datamodels"){const M=k.filter(F=>!E.some(P=>P.name===F.name&&P.type==="model"));T=[...E,...M]}t(T)},[d,j,k,n,e,t]);return w.useEffect(()=>{r&&r(_)},[r,_]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(xt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:C,disabled:o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(vt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(gt,{children:s.map(E=>l.jsx(_e,{className:"hover:bg-muted",value:E.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:E.name}),l.jsx(tt,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(Ict,{}),e.connectionType==="url"&&l.jsx(Mct,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(Tct,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs($s,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsxs(sn,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(sn,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),l.jsxs(ur,{value:"tables",className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?l.jsx(DS,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const T=n.some(M=>M.name===E.name&&M.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[l.jsx(Qt,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:M=>M.stopPropagation(),disabled:g}),l.jsxs(pe,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&l.jsx(tt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&l.jsx(tt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),l.jsxs(ur,{value:"datamodels",className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search data models...",value:c,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(DS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const T=n.some(M=>M.name===E.name&&M.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[l.jsx(Qt,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>N(E),onClick:M=>M.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(pe,{className:"cursor-pointer",children:E.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function Rct({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=_c.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var C;const[a,c]=w.useState(""),u=w.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);w.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=jct(),m=d.filter(S=>{var N,j;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(S.id))??!1;case"exclude":return!(((j=s.domainIds)==null?void 0:j.includes(S.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:b}=Ect(e==null?void 0:e.semanticDomainId),x=S=>{const N=r||[],j=N.some(_=>_.id===S.id&&_.type==="dataset");let k;if(j)k=N.filter(_=>!(_.id===S.id&&_.type==="dataset"));else{const _={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};k=[...N,_]}n==null||n(k)},y=p.filter(S=>S.name.toLowerCase().includes(a.toLowerCase())),v=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],j=y.filter(_=>!S.some(E=>E.id===_.id&&E.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...S,...j];n(k)},[y,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(xt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(vt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((C=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),l.jsx(gt,{children:m.map(S=>l.jsx(_e,{className:"hover:bg-muted",value:S.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:S.label}),l.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),h&&l.jsx(DS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search datasets...",value:a,onChange:S=>c(S.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):b?l.jsx(DS,{title:"Error loading datasets",message:b.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(S=>{const N=r.some(j=>j.id===S.id&&j.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>x(S),children:[l.jsx(Qt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>x(S),onClick:j=>j.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(pe,{className:"cursor-pointer font-medium",children:S.label||S.name}),l.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function Pct(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Fct({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!Pct(e,t,n):r}function Oct(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function E5({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var V,O;const{tokenProps:a}=it(),c=a.semanticDomainAccess||_c.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[u,d]=w.useState([]),[f,h]=w.useState(void 0),{updateDataSource:m}=_r(),p=te(I=>I.isVisualEditing),g=te(I=>I.dashboard.aiContext),{setAiContext:b}=Jt(),x=w.useRef(null),[y,v]=w.useState(!1),C=c.mode,S=C==="include"||C==="exclude",N=C!=="all",j=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,_=C==="include"&&(((V=c.domainIds)==null?void 0:V.length)||0)===1?(O=c.domainIds)==null?void 0:O[0]:void 0,E=w.useCallback(I=>{const W=I;m({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:W,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...W!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,m]),T=w.useCallback(I=>{m({...n,...I})},[n,m]),M=w.useCallback(I=>{if(r==="aiContext"){"semanticDomainId"in I&&h(I.semanticDomainId);return}T(I)},[r,T]),F=r==="aiContext"?f:n.semanticDomainId,P=r==="aiContext"?{...n,mode:k,semanticDomainId:f}:n;w.useEffect(()=>{if(!N||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){E("semanticDomain");return}if(k!=="semanticDomain")return;const I=F,W=c.domainIds??[],X=r==="aiContext"?u:n.selectedEntities,Z=((X==null?void 0:X.length)??0)>0,$=((u==null?void 0:u.length)??0)>0;Fct({mode:C,currentDomainId:I,scopedDomainIds:W,hasSelectedEntities:Z})&&(r==="dataSource"?T({semanticDomainId:void 0,selectedEntities:[]}):h(void 0),$&&d([]))},[S,N,k,n.mode,F,n.selectedEntities,r,f,u,e,c.domainIds,C,T,E]),w.useEffect(()=>{_&&!F&&M({semanticDomainId:_})},[_,F,M]),w.useEffect(()=>{if(e){d(s||[]);const I=r==="aiContext"?Oct(s):void 0;h(n.semanticDomainId||I)}else x.current=null,v(!1)},[e,n==null?void 0:n.selectedEntities,r,m,s,n]);const D=I=>{const W=u.filter(X=>!yi(X,I));d(W)},L=()=>{d([])},z=w.useCallback(I=>{d(I)},[]),U=w.useCallback(()=>{x.current&&x.current()},[]),B=w.useCallback(I=>{x.current=I,v(!0)},[]);function R(){var I,W;if(r==="aiContext"){if(p&&m(n),i){const X={...g,selectedEntities:u,mode:u.length>0?"fixed":"auto"};b(X)}o==null||o(u),t(!1)}else if(r==="dataSource"){if(n.mode==="semanticDomain"){const X=(I=u==null?void 0:u[0])==null?void 0:I.connectionId,Z=(W=u==null?void 0:u[0])==null?void 0:W.connectionType;m({...n,connectionId:X,connectionType:Z,selectedEntities:u})}else m({...n,selectedEntities:u});t(!1)}}return l.jsx(Yr,{open:e,onOpenChange:t,children:l.jsx(Rr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Pr,{className:"flex-shrink-0",children:[l.jsx(Fr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(us,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[j&&l.jsx("div",{className:"space-y-2",children:l.jsx($s,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:E,className:"w-full",children:l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsx(sn,{value:"database",children:"Direct Source"}),l.jsx(sn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(Rct,{dataSource:P,onDataSourceUpdate:M,selectedEntities:u,onSelectionChange:z,domainAccess:c,autoSelectedDomainId:_,onRegisterSelectAll:B}),k==="database"&&j&&l.jsx(Act,{dataSource:n,onDataSourceUpdate:T,selectedEntities:u,onSelectionChange:z,onRegisterSelectAll:B})]})}),l.jsx(Nct,{selectedEntities:u,onDeselectEntity:D}),l.jsx(Ls,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(ne,{variant:"outline",onClick:U,disabled:!y,children:"Select All"}),l.jsx(ne,{variant:"outline",onClick:L,disabled:u.length===0,children:"Clear All"}),l.jsxs(ne,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Tt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(ne,{onClick:R,children:[l.jsx(es,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function AS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(NA,{className:r});case"view":return l.jsx(Uu,{className:r});case"materialized view":return l.jsx(Hhe,{className:r});case"model":return l.jsx(rN,{className:r});case"file":return l.jsx(Ma,{className:r});case"dataset":return l.jsx(pl,{className:r});case"upload":return l.jsx(_A,{className:r});case"url":return l.jsx(eU,{className:r});default:return l.jsx(tN,{className:r})}}const cD=e=>e.name||e.name,Lct=e=>{const t=cD(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function $ct({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=w.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(wr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsxs(tt,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[AS(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:cD(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Tt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-w-xs",children:Lct(f)})]},m)}),d&&l.jsxs(yn,{open:o,onOpenChange:i,children:[l.jsx(vn,{asChild:!0,children:l.jsxs(tt,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(X7,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Tt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:AS(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:cD(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Tt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Sae=A.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Zs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(vo.Input,{ref:n,className:Q("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Sae.displayName=vo.Input.displayName;const Xw=e=>e.label||(e==null?void 0:e.name),RV=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function zct({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=it(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(N=>{if(!h)return!0;const j=Xw(N).toLowerCase(),k=RV(N).toLowerCase(),_=h.toLowerCase();return j.includes(_)||k.includes(_)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(Xw(b[0]))},[b,p]);const x=()=>{if(!p)return;const N=b.find(j=>Xw(j)===p);N&&(o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),x())};if(!e)return null;const v=N=>o.some(j=>"id"in N&&"id"in j?N.id===j.id:N.name===j.name&&N.connectionId===j.connectionId),C=o.length===s.length,S=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(gg,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Sae,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(qr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Tt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(bg,{className:"min-h-60",children:[l.jsx(xg,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(qr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(yg,{children:b.map((N,j)=>{const k=v(N),_="id"in N?N.id:`${N.connectionId}-${N.name}`,E=Xw(N);return l.jsxs(vg,{value:E,onSelect:()=>{k?n==null||n(N):t(N)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:Q("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:AS(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:E}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:RV(N)})]}),k&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(es,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}function uD({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0,assistantType:b}){const[x,y]=w.useState(!1),[v,C]=w.useState(!1),S=o??x,N=o!==void 0,j=w.useRef(!1),_=ze(q=>q.card.dataSource)??pE,{selectedEntities:E,availableEntities:T,syncWithGlobalContext:M,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:D}=XN(b),L=e==="full"||e==="display",z=e==="full"||e==="trigger",U=w.useMemo(()=>g&&E.length>0?`Add entity (${E.length})`:p,[E.length,g,p]);w.useEffect(()=>{S&&!j.current&&s&&M(),j.current=S},[S,s,M]);const B=w.useCallback(q=>{N||y(q),i==null||i(q)},[N,i]),R=w.useCallback(q=>{const H=E.filter(K=>!yi(K,q));F(H),c==null||c(q),d==null||d(H)},[c,d,E,F]),V=w.useCallback(q=>{if(q.length===0)return;const H=E.filter(K=>!q.some(G=>yi(K,G)));F(H),u==null||u(q),d==null||d(H)},[u,d,E,F]),O=w.useCallback(q=>{const H=D(q)?E.filter(K=>!yi(K,q)):[...E,q];F(H),d==null||d(H)},[D,d,E,F]),I=w.useCallback(()=>{F(T),d==null||d(T)},[T,d,F]),W=w.useCallback(()=>{F([]),d==null||d([])},[d,F]),X=w.useCallback(q=>{b==="dashboard"?P():F(q),d==null||d(q)},[P,b,d,F]),Z=w.useCallback(q=>{const H=E.some(K=>yi(K,q))?E:[...E,q];F(H),a==null||a(q),d==null||d(H),B(!1)},[a,d,E,B,F]),$=L?l.jsx($ct,{className:Q(n?"contents":"space-y-2"),entities:E,availableEntities:T,onRemoveEntity:R,onRemoveEntities:V}):null,Y=z?l.jsxs(l.Fragment,{children:[l.jsxs(ns,{open:S,onOpenChange:B,children:[l.jsx(rs,{asChild:!0,children:l.jsxs(ne,{variant:m,size:"sm",className:Q(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx($he,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:U})]})}),l.jsx(ss,{className:Q("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:q=>q.preventDefault(),children:l.jsx(zct,{isOpen:!0,onSelect:O,onDeselect:O,onClose:()=>B(!1),availableEntities:T,selectedEntities:E,onTabComplete:Z,onSelectAll:I,onRemoveAll:W,onAddContext:()=>{B(!1),C(!0)}})})]}),l.jsx(E5,{incomingSelectedEntities:E,open:v,onOpenChange:C,dataSource:_,dialogMode:"aiContext",onSaveSelectedEntities:X,saveAsDashboardDefault:b==="dashboard"})]}):null;return l.jsx("div",{className:Q(n?"flex flex-wrap items-center gap-1":"",!n&&L?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[Y,$]}):l.jsxs(l.Fragment,{children:[$,Y]})})}const k5=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),h=w.useRef(null),{queueMessage:m}=zp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:b}=KD(),x=GD(c);w.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=w.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const T=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${T}px`}},[e]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{const E=setTimeout(()=>{y()},0);return()=>clearTimeout(E)},[y]);const v=()=>{const E=e.trim();!E&&x.length===0||(a!=="ready"?(m(c,E,x),t(""),b(c)):r({preventDefault:()=>{}}))},C=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),v()),E.key==="@"&&f(!0)},S=w.useCallback(E=>{const T=Wnt(E.nativeEvent);T.length>0&&(E.preventDefault(),T.forEach(async M=>{const F=await m5(M);p(c,F)}))},[p,c]),N=w.useCallback(E=>{E.forEach(T=>{p(c,T)})},[p,c]),j=w.useCallback(E=>{E.forEach(T=>{p(c,T)})},[p,c]),k=w.useCallback(E=>{g(c,E)},[g,c]),_=w.useCallback(E=>{const T=`@${E}`;e.includes(T)&&t(e.replace(T,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(Cct,{onFilesDropped:N,currentFileCount:x.length,disabled:s,className:"space-y-4",children:[l.jsx(uD,{mode:"display",assistantType:c,onEntityRemoved:E=>{const T="label"in E?E.label:E.name;_(T)},onEntitiesRemoved:E=>{let T=e;E.forEach(M=>{const F="label"in M?M.label:M.name;T=T.replace(`@${F}`,"")}),T!==e&&t(T.replace(/\s{2,}/g," ").trim())}}),x.length>0&&l.jsx(qnt,{files:x,onRemove:k,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-xl border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:S,onFocus:()=>{y(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pt-3 pb-1 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(uD,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var M;const T="label"in E?E.label:E.name;t(`${e}@${T} `),(M=h.current)==null||M.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(wct,{onFilesSelected:j,disabled:s,currentFileCount:x.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(ne,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(nme,{className:"size-3.5"})}),!s&&l.jsx(ne,{disabled:!e.trim()&&x.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(CA,{className:"size-3.5"})})]})]})]})]})});k5.displayName="ChatInputWithContext";function Nae({assistantType:e,className:t}){const n=i7(e),{removeFromQueue:r}=zp();return n.length===0?null:l.jsxs("div",{className:Q("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Bu,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(Tt,{className:"h-3 w-3"})})]})},s.id))})]})}function jae({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=i7(e),{dequeueMessage:o}=zp();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Vct(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Bct(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Vct(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Eae(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!0),[d,f]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(0),b=w.useRef(!0),x=w.useRef(!0),y=w.useRef(!1),v=w.useRef(!1),C=w.useRef(0),S=w.useRef({count:0,signature:"none"}),N=w.useCallback(()=>{if(i.current)return i.current;const D=a.current;if(!D)return null;const L=D.closest("[data-radix-scroll-area-viewport]");if(L)return i.current=L,L;const z=D.parentElement;return z?(i.current=z,z):null},[]),j=w.useCallback(()=>{const D=N();return D?D.scrollHeight-D.scrollTop-D.clientHeight:0},[N]),k=w.useCallback(()=>j()<=n,[j,n]),_=w.useCallback(D=>{b.current!==D&&(b.current=D,u(D))},[]),E=w.useCallback(D=>{x.current!==D&&(x.current=D,f(D))},[]),T=w.useCallback(()=>{m(D=>D&&!1),g(D=>D===0?D:0)},[]),M=w.useCallback((D={})=>{const L=N();if(!L)return;const{force:z=!1,instant:U=!1}=D;if(!z&&y.current)return;const B=U||r==="auto"||r==="instant"?"auto":r;v.current=!0,B==="smooth"&&"scrollTo"in L?L.scrollTo({top:L.scrollHeight,behavior:"smooth"}):L.scrollTop=L.scrollHeight,C.current=L.scrollTop,y.current=!1,_(!0),E(!0),T(),requestAnimationFrame(()=>{v.current=!1})},[r,T,N,_,E]),F=w.useCallback(()=>{g(0),m(!1)},[]),P=w.useCallback(()=>{const D=N();if(!D)return;const L=C.current,z=D.scrollTop,U=z-L;C.current=z;const B=k();if(v.current){E(B),B&&(y.current=!1,_(!0));return}if(U<-1&&!B){y.current=!0,_(!1),E(!1);return}if(B){y.current=!1,_(!0),E(!0),T();return}E(!1),y.current&&_(!1)},[T,N,k,_,E]);return w.useEffect(()=>{const D=N();if(!e||e.length===0){S.current={count:0,signature:"none"},D&&(C.current=D.scrollTop),T();return}const L=e[e.length-1],z=Bct(L),U=S.current,B=e.length>U.count,R=z!==U.signature;S.current={count:e.length,signature:z};const V=o||s&&(L==null?void 0:L.role)==="assistant"&&R;if(!y.current){_(!0),D&&k()&&E(!0),(B||R||V)&&M({force:!1,instant:V});return}if(B){const O=e.length-U.count;O>0&&(m(!0),g(I=>I+O))}else R&&(m(!0),g(O=>O>0?O:1))},[T,o,s,N,k,e,M,_,E]),w.useEffect(()=>{M({force:!0,instant:!0})},[M]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const D=a.current;if(!D)return;const L=new ResizeObserver(()=>{y.current||M({force:!1,instant:!0})});return L.observe(D),()=>{L.disconnect()}},[M]),w.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:M,handleScroll:P,resetNewMessageCount:F}}function kae(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const PV={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Uct(e,t){var r;if((r=PV[e])!=null&&r[t])return PV[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function _ae(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Uct(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Hct=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Wct({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(MD),[u,d]=w.useState(!1),[f,h]=w.useState("auto"),[m,p]=w.useState(!1),[g,b]=w.useState(!1),x=n??g,{isLocalDev:y,isConsoleMode:v}=Xp(),C=w.useRef(null);te(ie=>ie.dashboard.aiScopeTables),te(ie=>ie.isDashboardEditing);const S=te(ie=>ie.selectedSheetId),{setDataSource:N}=_r(),{addFrame:j,setSelectedFrameId:k,setIsDashboardEditing:_}=Jt(),{setReasoningEffort:E,setShowReasoning:T,clearAssistantMessageContexts:M}=GS(),{clearQueue:F}=zp(),{clearFileAttachments:P,getFileAttachments:D}=KD(),L=GD("dashboard"),z=ze(ie=>ie.card.dataSource),{assistantProfile:U}=yae(),B=te(ie=>ie.handleOpenAssistantProfile),{selectedEntities:R,applyDashboardDefaultEntities:V}=XN("dashboard"),{sendMessage:O,isLoading:I,messages:W,setMessages:X,status:Z,stop:$,errorMessage:Y,clearError:q}=vct({dynamicVisualMode:f}),H=w.useCallback(ie=>{r==null||r(ie),n===void 0&&b(ie)},[n,r]),K=w.useCallback(()=>{H(!x)},[x,H]);w.useEffect(()=>{if(!x)return;function ie(Te){Te.key==="Escape"&&H(!1)}return window.addEventListener("keydown",ie),()=>{window.removeEventListener("keydown",ie)}},[x,H]);const[G,J]=w.useState(""),re=ie=>{J(ie.target.value)};function me({sql:ie,cardTitle:Te,connectionId:Pe,cardType:Ie,python:Ze,cardConfig:ke,dataSource:We,customVisualPreferences:ct}){if(!S)return;const Be={id:kr(),title:Te||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ie==="horizontalBar"?"y":"x"}},type:Ie,sql:ie,python:Ze,dataSource:We,config:ke,connectionId:Pe,customCardPreferences:ct?{url:ct.url,componentName:ct.componentName,pluginChartType:ct.pluginChartType,settings:ct.settings,type:"component"}:void 0},Je={id:kr(),cards:[Be],activeCardId:Be.id};_(!0),j(S,Je,"end"),k(Je.id)}const ee=ie=>{ie.preventDefault();const Te=G.trim();if(!Te&&L.length===0)return;const Pe=[];Te&&Pe.push({type:"text",text:Te}),L.forEach(Ie=>{Ie.data&&Pe.push({type:"file",mediaType:Ie.type,filename:Ie.name,url:`data:${Ie.type};base64,${Ie.data}`})}),O({role:"user",parts:Pe}),J(""),P("dashboard"),he({force:!0})};w.useEffect(()=>{var ie;e&&((ie=C.current)==null||ie.focus())},[e]),jae({assistantType:"dashboard",status:Z,isLoading:I,sendMessage:O});const{hasActiveTools:xe,activeToolText:oe}=_ae(W),{visibleMessages:de,hasMoreMessages:Ce,totalMessageCount:je,loadMoreMessages:Ae,resetMessageWindow:ge}=kae(W,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Oe,contentRef:Ee,isAtBottom:le,hasNewMessages:se,newMessageCount:Se,scrollToBottom:he,handleScroll:fe,resetNewMessageCount:Fe}=Eae(de,{threshold:40,behavior:"smooth",isStreaming:I});function ye(ie){const Te={role:"user",parts:[{type:"text",text:ie.title+" "+ie.subtitle}]};O(Te)}function Ne(ie){O({role:"user",parts:[{type:"text",text:ie}]})}function $e(ie){O({role:"user",parts:[{type:"text",text:ie}]}),he({force:!0})}const Re=w.useCallback(async()=>{const ie=JSON.stringify(W??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ie),Ge.success("Conversation copied")}catch(Te){console.error("Failed to copy conversation",Te),Ge.error("Unable to copy conversation")}},[W]),Ue=(G==null?void 0:G.length)===0&&(W==null?void 0:W.filter(ie=>ie.role==="user").length)===0;function He(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ye(){return l.jsxs(ud,{children:[l.jsx(dd,{asChild:!0,children:l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(vh,{className:"size-3.5"})})}),l.jsxs(Uc,{align:"end",children:[l.jsx(kf,{children:"Options"}),l.jsx(Wu,{}),l.jsx(lu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(lu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(lu,{checked:u,onCheckedChange:d,children:"System Message"}),(y||v)&&l.jsxs(l.Fragment,{children:[l.jsx(Wu,{}),l.jsx(kf,{children:"Dynamic Visuals"}),l.jsx(lu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(lu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(lu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const et=l.jsxs("div",{"data-role":"dashboard-assistant",className:Q("flex h-full grow flex-col justify-between break-words px-6 py-4",x&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[He(),B&&l.jsx(ne,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:B,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[v&&Ye(),a&&l.jsx(ne,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Re,children:"Copy Conversation"}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:x?"Exit Fullscreen":"Expand",onClick:K,children:x?l.jsx(xA,{className:"size-4"}):l.jsx(sN,{className:"size-4"})}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const ie=W.filter(Te=>Te.role==="assistant").map(Te=>Te.id).filter(Te=>!!Te);X([]),F("dashboard"),q(),M(ie),ge()},children:l.jsx(iN,{className:"size-4"})}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Tt,{className:"size-4"})})]})]}),l.jsxs(Ba,{"data-role":"dashboard-assistant-scroll-area",ref:Oe,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:fe,children:[l.jsxs("div",{ref:Ee,className:"min-w-0 space-y-3 pb-4",children:[Ce&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(ne,{variant:"outline",size:"sm",onClick:Ae,className:"text-xs",children:["Load ",Math.min(5,je-de.length)," ","more messages (",je-de.length," ","hidden)"]})}),l.jsx(nie,{showTools:a,showSystemMessage:u,messages:de,onAddToDashboard:me,onQuickReply:$e,disableQuickReplies:I}),l.jsx(tie,{status:Z,errorMessage:Y,activeToolText:xe?oe:void 0})]}),l.jsx(Ra,{orientation:"horizontal"})]}),e&&!le&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(ne,{onClick:()=>{he({force:!0}),Fe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(vr,{className:"h-4 w-4"}),se&&Se>0&&l.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:Se>9?"9+":Se})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&Ue&&l.jsx(rie,{onClick:ye,placeholders:Hct}),l.jsx("div",{children:Ue&&U&&l.jsx(vae,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:Ne})}),l.jsx(Nae,{assistantType:"dashboard",className:"mb-3"}),l.jsx(k5,{ref:C,setInput:J,stop:$,input:G,handleInputChange:re,handleSubmit:ie=>{ee(ie),he({force:!0})},isLoading:I,status:Z,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(E5,{incomingSelectedEntities:R,open:m,onOpenChange:p,dataSource:z||pE,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ie=>V()})]});return x&&s?yr.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:et})}),s):et}function qct(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Jt(),o=te(d=>d.dashboard.sheets),a=te(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=te(d=>d.isDashboardEditing),u=te(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Ge.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=fne(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Ge.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,c,u,t])}function Yct(e,t){switch(e.interactionMode){case"drillToDetail":Gct(e,t);break;case"drillThrough":Kct(e,t);break;case"drillToURL":Zct(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Gct(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Kct(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Zct(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Xct({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Yr,{open:e,onOpenChange:t,children:l.jsxs(Rr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Pr,{children:[l.jsx(Fr,{children:i||"Insight Detail"}),l.jsx(us,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(nre,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(cre,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Qct(){const e=Vt(C=>C.interactionStates),t=Vt(C=>C.setInteractionState),n=Vt(C=>C.clearLastInteractionEvent),r=Vt(C=>C.replaceCardWithInsight),s=Vt(C=>C.setPendingDrillThrough),o=Vt(C=>C.pendingDrillThrough),i=Vt(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=Jt(),{selectDashboard:u}=Bp(),d=te(C=>C.dashboard),f=te(C=>C.filterValues),{data:h,isLoading:m}=yW((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=ure(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:S,contextMode:N})=>{g({open:!0,insightId:C,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:C,insightId:S,filters:N,contextMode:j})=>{r(C,S,N,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:xa,interactionMode:"clickFilter",filterGroups:[{filters:C}]},T={...Ui(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k};t(xa,T)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([C,S])=>{if(S!=null&&S.lastInteractionEvent){const N=S.lastInteractionEvent,j=`${C}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{Yct(N,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(C),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Xct,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(In,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Jct(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=eut(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function eut(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function tut(e){return e?`Back to ${e}`:"Back"}function nut(){var x,y,v,C,S;const e=Vt(N=>N.interactionStates[xa]),t=te(N=>N.actions.goBackFromDrill),n=te(N=>N.actions.clearDrillContext),{selectDashboard:r}=Bp(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const N=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};Jct(f);const b=tut(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,j)=>{const k=N.field.label||N.field.name,_=String(N.value);return l.jsxs(tt,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",_]},j)})})]}),l.jsx(ne,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Tt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(ne,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(B7,{className:"mr-2 h-4 w-4"}),b]})})]})})}function rut(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Tae(){var je,Ae;const{showAssistant:e,tokenProps:t}=it(),n=rut((je=t.config)==null?void 0:je.showDashboardAssistant,e),{preferences:r,isConsoleMode:s}=Xp(),o=((Ae=r==null?void 0:r.cardDisplay)==null?void 0:Ae.mode)==="print",i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!1),{handleDragStart:d,isDraggingRef:f,getStyle:h,getPositionClasses:m}=FGe({initialPosition:"bottom-right"}),p=Af(ge=>ge.setFullscreen),g=Af(ge=>ge.setPanelOpen),b=Af(ge=>ge.setContainer),x=aQ("dashboard"),y=lQ(),v=cQ("dashboard"),C=x.isOpen,S=y==="dashboard",N=te(ge=>ge.isVisualEditing),j=te(ge=>ge.themeStyle),k=te(ge=>{var Oe;return(Oe=ge.dashboard)==null?void 0:Oe.sheets}),_=te(ge=>ge.showFilters),E=te(ge=>ge.isDashboardEditing),T=te(ge=>ge.selectedSheetId),M=te(ge=>{var Oe,Ee;return((Ee=(Oe=ge.dashboard)==null?void 0:Oe.summary)==null?void 0:Ee.position)||"top"}),F=te(ge=>{var Oe;return(Oe=ge.dashboard)==null?void 0:Oe.id}),P=te(ge=>ge.isDashboardPanelOpen),D=te(ge=>ge.actions.setIsDashboardPanelOpen),L=j==null?void 0:j.controlInputRadius,{getDefaultSheetId:z,setDefaultSheetId:U,clearDefaultSheetId:B}=O7(F),[R,V]=w.useState(null);vN(os.DASHBOARD);const{setSelectedSheetId:O,setSheetTitle:I,addSheet:W,setSheets:X}=Jt();qct(a);const{setActiveAssistantType:Z}=GS();w.useEffect(()=>{if(F){const ge=z();V(ge)}},[F,z]),w.useEffect(()=>{C?Z("dashboard"):y==="dashboard"&&p(null)},[C,Z,y,p]),w.useEffect(()=>{var ge;C||(ge=i.current)==null||ge.resize(0)},[C]);function $(ge){var Oe,Ee;ge?((Oe=i.current)==null||Oe.resize(40),g("dashboard",!0),p("dashboard"),Z("dashboard")):(g("dashboard",!1),p(null),(Ee=i.current)==null||Ee.resize(0),Z(null))}function Y(){const ge={id:kr(),title:"New Sheet"};W(ge),O(ge.id)}function q(ge,Oe){if(!F)return;R===ge?(B(),V(null),Ge.success("Default sheet cleared")):(U(ge),V(ge),Ge.success(`"${Oe}" set as default sheet`))}function H(ge){var Oe;ge<1?(g("dashboard",!1),p(null),Z(null),(Oe=i.current)==null||Oe.resize(0)):(C||g("dashboard",!0),Z("dashboard"))}function K(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const G=(ge,Oe)=>{ge.dataTransfer.setData("tabIndex",Oe.toString())},J=ge=>{ge.preventDefault()},re=(ge,Oe)=>{const Ee=ge.dataTransfer.getData("tabIndex");if(Ee===Oe.toString())return;const le=Array.from(k||[]),[se]=le.splice(parseInt(Ee),1);le.splice(Oe,0,se),X(le)},me=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ee=n===!0&&!o&&!C&&!N&&!_;function xe(){if(k&&k.length>1||E)return l.jsxs(js,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[s&&me&&!P&&l.jsx(ne,{style:{borderRadius:L},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!P)},className:"h-9 shrink-0 px-3",children:l.jsx(rU,{className:"h-4 w-4"})}),k==null?void 0:k.map((ge,Oe)=>{const Ee=T===ge.id,le=R===ge.id;return l.jsxs(sn,{draggable:!0,onDragStart:se=>G(se,Oe),onDragOver:J,onDrop:se=>re(se,Oe),style:{borderRadius:L},onClick:()=>O(ge.id),className:"flex h-9 shrink-0 items-center gap-1 border border-border/70 bg-background/70 px-3 py-1 text-muted-foreground transition-colors hover:text-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none data-[state=active]:shadow-[inset_0_-2px_0_0_hsl(var(--foreground))]",value:ge.id,children:[l.jsx(oS,{enabled:E&&Ee,text:ge.title,onSave:se=>I(ge.id,se),children:ge.title},ge.id),!E&&Ee&&l.jsx("div",{title:le?"Clear default sheet":"Set as default sheet",children:l.jsx(SA,{className:Q("ml-1 size-3 cursor-pointer transition-all",le?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),q(ge.id,ge.title||"Sheet")}})}),E&&Ee&&k.length>1&&l.jsx(Tt,{className:"ml-1 size-3",onClick:()=>u(!0)})]},ge.id)}),E&&l.jsx(ne,{style:{borderRadius:L},variant:"outline","aria-label":"Add sheet",className:"h-9 shrink-0 border-border/70 bg-background/70 px-3 text-muted-foreground hover:bg-background/80 hover:text-foreground",onClick:Y,children:l.jsx(qr,{className:"size-4"})})]})}function oe(){return l.jsx("div",{ref:a,style:{},className:"grow",children:k==null?void 0:k.map(ge=>l.jsx(ur,{style:{backgroundColor:K()},className:Q("mt-0",{}),value:ge.id,children:l.jsx(iGe,{sheet:ge})},ge.id))})}function de(){var ge;return l.jsxs($s,{"data-role":"dashboard-tabs-container",className:Q("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:Oe=>{O(Oe)},value:T||((ge=k==null?void 0:k[0])==null?void 0:ge.id),children:[xe(),M==="top"&&l.jsx(_M,{}),l.jsx(Ba,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:oe()}),M==="bottom"&&l.jsx(_M,{}),l.jsx(OGe,{open:c,setOpen:u})]})}const Ce=w.useCallback(ge=>{b("dashboard",ge)},[b]);return k?l.jsxs(l.Fragment,{children:[l.jsx(Qct,{}),l.jsx(nut,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Lse,{className:Q("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx($M,{children:de()}),n===!0&&l.jsxs(l.Fragment,{children:[l.jsx(PGe,{open:C,onTabClick:$,withHandle:!0,disabled:!C}),l.jsx($M,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:H,defaultSize:C?40:0,ref:i,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Wct,{open:C,setOpen:$,isFullscreen:S,onFullscreenChange:ge=>p(ge?"dashboard":null),fullscreenContainer:v})})})]})]}),l.jsx("div",{ref:Ce,className:Q("absolute inset-0",!S&&"pointer-events-none")}),ee&&l.jsx("div",{className:Q("absolute z-50 transition-all duration-300 ease-in-out",m().horizontal,m().vertical),style:h(),children:l.jsx(ne,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{f.current||$(!0)},onMouseDown:d,onTouchStart:d,title:"Open Assistant (drag to move)",children:l.jsx(Xhe,{className:"h-5 w-5"})})})]})]}):null}function _5({children:e}){return l.jsx(ta,{style:{height:"100%",width:"100%"},children:l.jsx(qfe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(wr,{delayDuration:0,children:e})})})}function Iae({children:e,preferences:t}){const{currentUser:n}=Vo(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(QH.Provider,{value:r,children:l.jsx(EO,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function sut(e=2e3,t=500){const n=whe(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function T5({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=sut(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function Mae(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Fa,{FallbackComponent:zj,children:l.jsxs(sA,{dashboardProps:e,children:[l.jsx(T5,{componentType:"dashboard",componentId:e.id}),l.jsx(_5,{children:l.jsx(Iae,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(TP,{...e,type:"dashboard",children:l.jsx(Tae,{})})})})})]})})}function out(e){return!!e.expression}function iut(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function aut(e){const t=iut(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function lut(e){return e.fieldScope==="domain"||e.entityName===Ao||e.qualifiedEntityName===Ao}function cut(e){return e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Ei||aut(e.id)}function RS(e){return out(e)?lut(e)?"domain_calculated":cut(e)?"user_calculated":"inline_expression":"none"}function FV(e,t){return e.map(n=>({...n,fieldScope:t}))}function uut(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function OV(e){if(Eh(e)||KN(e))return e.expression}function I5(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=LO(),i=ze(g=>g.frame.calculatedFields),a=ze(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?FV(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(v=>v.role==="metric"&&RS(v)==="user_calculated"),b=((a==null?void 0:a.groupByColumns)||[]).filter(v=>v.role==="groupby"&&RS(v)==="user_calculated"),y=uut([...g,...b]).filter(v=>{const C=`${v.name}-${v.role||"unknown"}`,S=f.get(C);if(!S)return!0;const N=OV(v),j=OV(S);return N&&j?N!==j:!0});return FV(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==qB),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function M5(e){const{tokenProps:t,authToken:n}=it(),r=t==null?void 0:t.apiServiceUrl;return Xt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return dr(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Dae(e,t,n){if(t==="source")return{isValid:!0};const r=Nn(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Aae(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function dut(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const fut=new Set(["COUNT","DISTINCT"]),hut=new Set(["running_total","moving_average","previous_period_delta"]);function mut(e){return Nn(e.dataType||"")==="number"?!0:e.aggregate?fut.has(e.aggregate.toUpperCase()):!1}function put(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function D5(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Rae({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!mut(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||D5(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:hut.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function gut(e){return e.find(t=>Nn(t.dataType||"")==="date")}function but(e){return e}function kx({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||D5(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function xut({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=gut(n.groupByColumns||[]))==null?void 0:i.id),o=kx({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const yut=new Set(["table","aggregateTable","pivotTable","detailTable"]);function vut(e){return e.alias||e.label||e.name}function Pae(e,t,n){var a,c,u;if(!e)return null;const r=Mi(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(yut.has(e.type)){const d=c7(r),f=vut(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=Ys();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=Nfe(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Fae=e=>{var X;const t=(X=e==null?void 0:e.dataSource)==null?void 0:X.semanticDomainId,{data:n}=M5(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=_r(),m=ze(Z=>Z.card.type),p=e==null?void 0:e.id,g=(Z,$)=>{if(Z.id)return Z.id;const Y=Z.qualifiedEntityName||Z.entityName||$;return`${$}-${Y}-${Z.name}`},b=w.useCallback(Z=>{if(!(e!=null&&e.config))return[];switch(Z){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:g($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:g($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:g($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:g($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return dut(e.config.detailColumns,$=>g($,"detailColumns"));case"source":return[];default:return[]}},[e]),x=w.useCallback((Z,$)=>{if(p)switch(Z){case"groupBy":{r(p,{groupByColumns:$});break}case"metrics":{r(p,{metricColumns:$});break}case"pivotBy":{r(p,{pivotByColumns:$});break}case"sortBy":{r(p,{sortByColumns:$});break}case"detailColumns":{r(p,{detailColumns:$});break}}},[p,r]),y=w.useCallback((Z,$,Y)=>{if(!p)return;const q=b(Z),H=q[$];if(H)switch(Z){case"groupBy":s(p,H.id,{label:Y});break;case"metrics":o(p,H.id,{label:Y});break;case"pivotBy":i(p,H.id,{label:Y});break;case"sortBy":a(p,H.id,{label:Y});break;case"detailColumns":{const K=q.map((G,J)=>J===$?{...G,label:Y}:G);r(p,{detailColumns:K});break}}},[p,b,s,o,i,a,r]),v=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{aggregate:$,label:RK(q.name,$)})},[p,b,o]),C=w.useCallback((Z,$,Y,q="groupBy")=>{if(!p)return;const H=b(q),K=H[Z];if(!K)return;const G={dateFormat:$,customFormat:$==="custom"&&Y?Y:void 0};if(q==="detailColumns"){const J=H.map((re,me)=>me===Z?{...re,...G}:re);r(p,{detailColumns:J});return}s(p,K.id,G)},[p,b,r,s]),S=w.useCallback((Z,$)=>{if(!p)return;const q=b("groupBy")[Z];q&&s(p,q.id,{granularity:$})},[p,b,s]),N=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{aliasTemplate:$})},[p,b,o]),j=w.useCallback((Z,$)=>{if(console.log("handleValueAliasesChange",Z,$),!p)return;console.log("handleValueAliasesChange",Z,$);const q=b("metrics")[Z];q&&(console.log("handleValueAliasesChange",$),o(p,q.id,{valueAliases:$}))},[p,b,o]),k=w.useCallback((Z,$)=>{var H,K;if(!p)return;const q=b("metrics")[Z];q&&(o(p,q.id,{format:$}),m==="kpi"&&((K=(H=e==null?void 0:e.preferences)==null?void 0:H.kpiVisualOptions)!=null&&K.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,p,m,b,h,o]),_=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=$!=="none"&&((K=q.parameters)==null?void 0:K.windowTransform);o(p,q.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{},...H?{parameters:{...q.parameters||{},windowTransform:void 0}}:{}})},[p,b,o]),E=w.useCallback((Z,$)=>{var me,ee,xe;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;if($==="none"){o(p,q.id,{parameters:{...q.parameters||{},windowTransform:void 0}});return}const H=Rae({cardType:m,cardConfig:e.config,metric:q,transformMode:$});if(!H.supported){Ge.error(H.reason||"Metric transform is not supported here.");return}const K=new Set((e.config.groupByColumns||[]).map(oe=>oe.id)),G=(xe=(ee=(me=q.parameters)==null?void 0:me.windowTransform)==null?void 0:ee.orderBy)==null?void 0:xe.fieldId,J=G&&K.has(G)?G:void 0,re=xut({transformMode:$,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:J});o(p,q.id,{comparisonType:"none",targetValue:void 0,parameters:{...q.parameters||{},windowTransform:re}})},[e,p,m,b,o]),T=w.useCallback((Z,$)=>{var re,me;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(re=q.parameters)==null?void 0:re.windowTransform;if(!H||!["running_total","moving_average","previous_period_delta"].includes(H.function))return;const K=kx({cardType:m,cardConfig:e.config,orderByFieldId:$}),J=(H.partitionByFieldIds||K).filter(ee=>ee!==$);o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,orderBy:{fieldId:$,direction:((me=H.orderBy)==null?void 0:me.direction)||"asc"},partitionByFieldIds:J}}})},[e,p,m,b,o]),M=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||!["running_total","moving_average","previous_period_delta"].includes(H.function)||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,orderBy:H.orderBy?{...H.orderBy,direction:$}:H.orderBy}}})},[p,b,o]),F=w.useCallback((Z,$)=>{var J,re;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(J=q.parameters)==null?void 0:J.windowTransform;if(!H)return;const K=kx({cardType:m,cardConfig:e.config,orderByFieldId:(re=H.orderBy)==null?void 0:re.fieldId}),G=new Set(H.partitionByFieldIds||K);G.has($)?G.delete($):G.add($),o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,partitionByFieldIds:Array.from(G)}}})},[e,p,m,b,o]),P=w.useCallback((Z,$)=>{var re,me;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(re=q.parameters)==null?void 0:re.windowTransform;if(!H||H.function!=="moving_average")return;const K=Math.max(1,Math.floor($||1)),G=((me=H.movingAverage)==null?void 0:me.minPeriods)||1,J=Math.min(G,K);o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,movingAverage:{windowSize:K,minPeriods:J}}}})},[p,b,o]),D=w.useCallback((Z,$)=>{var J,re;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(J=q.parameters)==null?void 0:J.windowTransform;if(!H||H.function!=="moving_average")return;const K=((re=H.movingAverage)==null?void 0:re.windowSize)||7,G=Math.max(1,Math.min(Math.floor($||1),K));o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,movingAverage:{windowSize:K,minPeriods:G}}}})},[p,b,o]),L=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||H.function!=="previous_period_delta"||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,previousPeriodDelta:{mode:$}}}})},[p,b,o]),z=w.useCallback((Z,$)=>{var G;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(G=q.parameters)==null?void 0:G.windowTransform;if(!H||H.function!=="percent_of_total")return;const K=$==="grand_total"?[]:(H.partitionByFieldIds||[]).length>0?H.partitionByFieldIds||[]:kx({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,partitionByFieldIds:K,percentOfTotal:{...H.percentOfTotal||{},scope:$}}}})},[e,p,m,b,o]),U=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||H.function!=="percent_of_total"||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,percentOfTotal:{...H.percentOfTotal||{},output:$}}}})},[p,b,o]),B=w.useCallback(Z=>{p&&r(p,{showTrendline:Z})},[p,r]),R=w.useCallback(Z=>{p&&r(p,{trendlineWindow:Z})},[p,r]),V=w.useCallback(Z=>{p&&r(p,{trendlineGranularity:Z})},[p,r]),O=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{targetValue:$})},[p,b,o]),I=w.useCallback(async Z=>{var re;if(!p)return;const $=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy"),...b("detailColumns")],Y=Z,q=K_e(Y,$,{joinPlan:(re=e==null?void 0:e.config)==null?void 0:re.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!q.isValid){q.showError&&TK();return}const H=sTe(Y,$,m);if(!H){Ge.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const K=Dae(Y,H,m);if(!K.isValid){Ge.error("Invalid Field Type",{description:K.reason,position:"top-center",duration:3e3});return}const G=b(H);if(IK(Y,G))return;const J=PK(Y,H,G);if(J){const me=[...G,J];if(x(H,me),H==="metrics"){const ee=Pae(e,J,e==null?void 0:e.preferences);ee&&h(ee),Aae(m,e==null?void 0:e.config,r,p,me)}}},[p,e,b,x,t,n,m,r,h]),W=w.useCallback((Z,$)=>{if(!p)return;const q=b(Z)[$];if(q){if(Z!=="sortBy"){const H=b("sortBy"),K=H.filter(G=>!(G.name===q.name&&G.qualifiedEntityName===q.qualifiedEntityName));K.length!==H.length&&r(p,{sortByColumns:K})}switch(Z){case"groupBy":c(p,q.id);break;case"metrics":u(p,q.id);break;case"pivotBy":d(p,q.id);break;case"sortBy":f(p,q.id);break;case"detailColumns":{r(p,{detailColumns:(b("detailColumns")||[]).filter((H,K)=>K!==$)});break}}}},[p,b,c,u,d,f,r]);return{getFieldsForContainer:b,setFieldsForContainer:x,updateLabel:y,handleAggregationChange:v,handleDateFormatChange:C,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:j,handleMetricFormatChange:k,removeField:W,handleFieldClick:I,handleMetricComparisonChange:_,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:M,handleMetricWindowPartitionToggle:F,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:D,handleMetricPreviousPeriodDeltaModeChange:L,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:B,handleKpiTrendlineWindowChange:R,handleKpiTrendlineGranularityChange:V,handleMetricTargetValueChange:O,cardType:m}};function vE(e,t){var ye,Ne,$e,Re,Ue,He,Ye,et;const{tokenProps:n}=it(),r=ps(),s=it().authToken||e,o=ze(ie=>ie.selectedConnectionId),i=ze(ie=>ie.card),{queryKey:a}=pve(i),c=ze(ie=>ie.selectedDatamodelId),u=ze(ie=>ie.isDevMode),d=ze(ie=>ie.selectedDatabaseName),f=ze(ie=>ie.selectedSchemaName),h=ze(ie=>ie.selectedTableName),m=ze(ie=>ie.actions.setSelectedConnectionId),p=ze(ie=>ie.actions.setSelectedDatamodelId),g=ze(ie=>ie.actions.setSelectedDatabaseName),b=ze(ie=>ie.actions.setSelectedSchemaName),x=ze(ie=>ie.actions.setSelectedTableName);ze(ie=>ie.actions.setCardSql);const{setQueryConfig:y}=_r();function v(ie){var ke;if(!o||!ie)return!1;const Te=((ke=_==null?void 0:_.capabilities)==null?void 0:ke.path)||[],Pe=Te.includes("database"),Ie=Te.includes("schema");return!(!Te.includes("table")||Pe&&(!d||d==="NA")||Ie&&!f)}function C(ie){var Te;return!o||!ie?!1:!!((Te=_==null?void 0:_.capabilities)!=null&&Te.path.includes("database"))}const{refetchConnections:S,connectionsData:N,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:_}=ra(e),{refetch:E,data:T,isLoading:M,isError:F}=Xt({queryKey:["models",o],queryFn:()=>dr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=_==null?void 0:_.type,D=((ye=_==null?void 0:_.capabilities)==null?void 0:ye.path.includes("schema"))??!1,L=((Ne=_==null?void 0:_.capabilities)==null?void 0:Ne.path.length)===1&&(($e=_==null?void 0:_.capabilities)==null?void 0:$e.path[0])==="table",z=L,{data:U,isLoading:B,isFetching:R,isError:V,refetch:O}=Xt({queryKey:["databases",o],queryFn:()=>dr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:I,isLoading:W,isFetching:X,isError:Z,refetch:$}=Xt({queryKey:["schemas",o,d],queryFn:()=>dr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&D&&d!=="NA"}),{data:Y,isLoading:q,isFetching:H,isError:K,refetch:G}=Xt({queryKey:["tables",o,d,f],queryFn:()=>dr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(P)}),{columns:J,isColumnsLoading:re,isColumnsFetching:me,isColumnsError:ee,refetchColumns:xe}=OK(e);w.useEffect(()=>{L&&(g(""),b(""),p(""),P==="API"&&x("api"))},[P,x,g,b,p,L]);const oe=(_==null?void 0:_.type)==="API"?(Re=_==null?void 0:_.type)==null?void 0:Re.toLowerCase():h||"",de=D&&f||"";function Ce(ie){x(ie),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function je(ie){b(ie),x("")}function Ae(ie){g(ie==="none"?"":ie),b(""),x(""),ie!=="none"&&ie!==""&&p("")}function ge(ie){m(ie)}function Oe(ie){p(ie==="none"?"":ie),ie!=="none"&&ie!==""&&g("")}U&&((Ue=U==null?void 0:U.databases)==null?void 0:Ue.length)>0,I&&((He=I==null?void 0:I.schemas)==null?void 0:He.length)>0;const Ee=N==null?void 0:N.connections.map(ie=>({id:ie.id,name:ie.name,type:ie.type})),le=(Ye=T==null?void 0:T.datamodels)==null?void 0:Ye.map(ie=>({id:ie.id,name:ie.name})),se=U==null?void 0:U.databases.map(ie=>({id:ie.database_name,name:ie.database_name})),Se=I==null?void 0:I.schemas.map(ie=>({id:ie.schema_name,name:ie.schema_name})),he=Y==null?void 0:Y.tables.map(ie=>({id:ie.table_name,name:ie.table_name})),fe=(et=T==null?void 0:T.datamodels.find(ie=>ie.id===c))==null?void 0:et.name,Fe=_!=null&&_.capabilities?z1({schemaName:de,tableName:oe,modelName:fe,databaseName:d||"",capabilities:_.capabilities}):oe;return{connectionItems:Ee,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:k,modelItems:le,selectedDatamodelId:c,selectedDatamodelName:fe,isModelsLoading:M,isModelsError:F,selectedDatabaseName:d,databaseItems:se,isDatabasesLoadingOrFetching:B||R,isDatabaseError:V,schemaItems:Se,selectedSchemaName:f,isSchemaLoadingOrFetching:W||X,isSchemaError:Z,tableItems:he,selectedTableName:h,isTableLoadingOrFetching:q||H,isTableError:K,columns:J,isColumnsLoadingOrFetching:re||me,isColumnsError:ee,isNonDbConnection:z,connectionType:P,tableName:oe,formattedTableName:Fe,schemaName:de,refetchConnections:S,refetchModels:E,refetchDatabases:O,refetchSchemas:$,refetchTables:G,refetchColumns:xe,handleConnectionChange:ge,handleDatamodelChange:Oe,handleDatabaseChange:Ae,handleSchemaChange:je,handleTableChange:Ce}}function Qw(e){return`${e}-${kr()}`}function LV(e,t){const n=Al(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function wut(e,t){const n=Al(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function A5(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Oae(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lae(){const e=ze(j=>j.sqlGen),t=ze(j=>j.isDevMode),n=ze(j=>j.card.dataSource),r=ze(j=>{var k,_;return(_=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=A5(n),a=Oae(n),c=ze(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=_r(),{modelItems:g,selectedDatamodelName:b}=vE(),{selectedConnection:x}=ra(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var _;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=FD(k,e);m(E);const T=(_=g==null?void 0:g.find(F=>F.id===c))==null?void 0:_.name,M=PD(E,o||"",s,T||"",i||"",y,j.qualifiedEntityName);M&&(f(M),h(!0))}else if(!t){if(Ky(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:Qw(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:Qw(k.column_name),name:k.column_name,label:LV(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(ka(k.data_type)){const E={...k,role:"groupby",id:Qw(k.column_name),name:k.column_name,type:k.data_type,label:wut(k.column_name,"month"),granularity:"month"};d(E)}if(Ea(k.data_type)){const E={...k,role:"metric",id:Qw(k.column_name),name:k.column_name,label:LV(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=z1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=z1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>Ea(j.dataType)}}function Cut(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>Px(o)).join("."),s=Px(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function $ae(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function zae(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function Vae(e){var t,n;return e?!!(e.entityName===Ei||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function Bae(){const e=te(c=>c.dashboard.filters)||[],t=te(c=>c.selectedSheetId),n=te(c=>c.actions.addFilter),r=te(c=>c.actions.removeFilter),{removeFilterValues:s}=Jt(),o=ze(c=>c.card.dataSource),{selectedConnection:i}=ra();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Cut(c);let m;if(u==="sheet"&&t?m=zRe(e,d,f,t):m=e==null?void 0:e.find(p=>Sp(p.column)===Sp(d)),m)s(m.id),r(m.id);else{const p=kr(),g=$ae(c),b=zae(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=Vae(g),y=u==="sheet"&&t?[t]:void 0,v=Nn(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:x?"":ote(c.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function Sut({column:e}){const[t,n]=w.useState(!1),r=ze(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=A5(r),a=ze(y=>y.selectedDatamodelId),c=ze(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=vE(),f=d==null?void 0:d.capabilities,h=ze(y=>y.actions.setSqlGen),m=ze(y=>y.actions.setCardSql),p=ze(y=>y.actions.setRunSql),g=Oae(r);function b(y,v){var k,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=FD(y,c,v),S=(k=u==null?void 0:u.find(E=>E.id===a))==null?void 0:k.name;if(h(C),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const N=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),j=PD(C,o||"",s,S||"",i||"",f,N);j&&(m(j),p(!0)),n(!1)}function x(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?l.jsxs(Qp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Jp,{asChild:!0,children:l.jsx(vh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(eg,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}const Uae="absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 font-mono text-[7px] font-semibold leading-none shadow-sm",$V="bg-emerald-500/90 text-white",Nut="bg-blue-500/90 text-white";function Hae(e){const t=RS(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:$V}:{label:"fx",badgeClassName:e.role==="metric"?$V:Nut}}function jut(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function Eut(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function kut({field:e,fieldState:t}){const n=Eut(e),r=jut(e.format);return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-xs text-foreground",children:n})]}),r.length>0&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Format"}),l.jsx("div",{className:"space-y-0.5",children:r.map(s=>l.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[l.jsx("span",{className:"text-muted-foreground",children:s.label}),l.jsx("span",{className:"font-mono text-foreground",children:s.value})]},`${s.label}-${s.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function zV({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=ze(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=te(K=>K.dashboard.filters),d=te(K=>K.selectedSheetId),f=te(K=>K.actions.removeFilter),{removeFilterValues:h}=Jt(),{assignFilter:m}=Bae(),p=t==="filter"?Gc(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const G=Sp(K.column||""),J=Sp(e.name);return G.endsWith(`.${J}`)||G===J}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,C=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:C,selectedSheetId:d});const[S,N]=w.useState(!1),[j,k]=w.useState(null),{attributes:_,listeners:E,setNodeRef:T,transform:M,transition:F,isDragging:P}=Lg({id:e.id,disabled:c}),[D,L]=w.useState(!1),z=ze(K=>K.card),{handleFieldClick:U}=Fae(z),{handleDevModeFieldClick:B,isNumberField:R}=Lae(),V=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),N(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&C?(k(e),N(!0)):m(e,"sheet"):i?B(e):U(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},W={transform:Ti.Transform.toString(M),transition:F},X=()=>{if(!n||a)return{};const G={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...G},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...G},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...G}}[n.state]||G};function Z(K){return K==="domain"?{label:"Semantic domain",Icon:tme,className:"text-foreground/55 hover:text-foreground/85"}:K==="dashboard"?{label:"Dashboard",Icon:pA,className:"text-foreground/55 hover:text-foreground/85"}:{label:"Card",Icon:aU,className:"text-foreground/55 hover:text-foreground/85"}}const $=X(),Y=e.fieldScope,q=Y?Z(Y):null,H=Hae(e);return l.jsxs("div",{ref:T,style:W,...c?{}:_,...c?{}:E,className:Q("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",P&&"scale-95 opacity-50",!P&&"border",$.borderColor||"border-transparent",$.bgColor||"",$.hoverBorderColor,$.hoverBgColor||"hover:bg-muted",$.opacity,$.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(e.dataType),H&&l.jsx("span",{className:Q(Uae,H.badgeClassName),children:H.label})]}),l.jsx(wr,{children:l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${D?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),l.jsx(Tn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(kut,{field:e,fieldState:n})})]})}),i&&!a&&R(e)&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(Sut,{column:I})}),t==="editor"&&q&&l.jsxs("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:[o&&l.jsx("div",{className:"mr-1 flex items-center opacity-0 transition-opacity pointer-events-none group-hover/container:opacity-100 group-hover/container:pointer-events-auto group-focus-within/container:opacity-100 group-focus-within/container:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto",children:o}),l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsx("span",{"aria-label":`${q.label} calculated field`,title:"",className:Q("block p-0.5 transition-colors",q.className),children:l.jsx(q.Icon,{className:"h-3.5 w-3.5"})})}),l.jsxs(Tn,{side:"top",align:"end",children:[q.label," calculated field"]})]})]}),o&&(!q||t!=="editor")&&l.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),D&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Ni,{className:"",children:l.jsxs(Ia,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lU,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lme,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(tt,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(Wc,{open:S,onOpenChange:N,children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Vl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs($l,{children:[l.jsx(Ul,{children:"Cancel"}),l.jsx(Bl,{onClick:V,children:"Remove Filter"})]})]})})]})}var Wa="Accordion",_ut=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[R5,Tut,Iut]=o0(Wa),[wE]=gs(Wa,[Iut,GZ]),P5=GZ(),Wae=w.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(R5.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Rut,{...o,ref:t}):l.jsx(Aut,{...s,ref:t})})});Wae.displayName=Wa;var[qae,Mut]=wE(Wa),[Yae,Dut]=wE(Wa,{collapsible:!1}),Aut=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=Os({prop:n,defaultProp:r??"",onChange:s,caller:Wa});return l.jsx(qae,{scope:e.__scopeAccordion,value:w.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:w.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(Yae,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(Gae,{...i,ref:t})})})}),Rut=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Os({prop:n,defaultProp:r??[],onChange:s,caller:Wa}),c=w.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=w.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(qae,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(Yae,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(Gae,{...o,ref:t})})})}),[Put,CE]=wE(Wa),Gae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=w.useRef(null),c=jt(a,t),u=Tut(n),f=ld(s)==="ltr",h=Xe(e.onKeyDown,m=>{var k;if(!_ut.includes(m.key))return;const p=m.target,g=u().filter(_=>{var E;return!((E=_.ref.current)!=null&&E.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,C=x-1,S=()=>{y=b+1,y>C&&(y=v)},N=()=>{y=b-1,y<v&&(y=C)};switch(m.key){case"Home":y=v;break;case"End":y=C;break;case"ArrowRight":o==="horizontal"&&(f?S():N());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?N():S());break;case"ArrowUp":o==="vertical"&&N();break}const j=y%x;(k=g[j].ref.current)==null||k.focus()});return l.jsx(Put,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(R5.Slot,{scope:n,children:l.jsx(dt.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),PS="AccordionItem",[Fut,F5]=wE(PS),Kae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=CE(PS,n),i=Mut(PS,n),a=P5(n),c=Wr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(Fut,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(XZ,{"data-orientation":o.orientation,"data-state":tle(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Kae.displayName=PS;var Zae="AccordionHeader",Xae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(Zae,n);return l.jsx(dt.h3,{"data-orientation":s.orientation,"data-state":tle(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Xae.displayName=Zae;var dD="AccordionTrigger",Qae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(dD,n),i=Dut(dD,n),a=P5(n);return l.jsx(R5.ItemSlot,{scope:n,children:l.jsx(qIe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Qae.displayName=dD;var Jae="AccordionContent",ele=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(Jae,n),i=P5(n);return l.jsx(YIe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});ele.displayName=Jae;function tle(e){return e?"open":"closed"}var Out=Wae,Lut=Kae,$ut=Xae,nle=Qae,rle=ele;const SE=Out,Rp=A.forwardRef(({className:e,...t},n)=>l.jsx(Lut,{ref:n,className:Q("border-b",e),...t}));Rp.displayName="AccordionItem";const Pp=A.forwardRef(({className:e,children:t,...n},r)=>l.jsx($ut,{className:"flex",children:l.jsxs(nle,{ref:r,className:Q("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(vr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Pp.displayName=nle.displayName;const Fp=A.forwardRef(({className:e,children:t,...n},r)=>l.jsx(rle,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:Q("pb-4 pt-0",e),children:t})}));Fp.displayName=rle.displayName;let sle=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Oy=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],rc=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Jd=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e,VV="calculated_fields";function zut(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function Vut(e){return e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Ei||e.entityName===VV||e.qualifiedEntityName===VV||zut(e.id)}function But(e){return e.aggregate?e.aggregate:DK(e.dataType)}function Uut(e,t){const n=But(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function Hut(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||Vut(o)||typeof o.expression=="string"&&MK(o.expression)?n:Uut(n,o)})}function BV(e,t,n,r,s,o,i,a,c,u){const d=Oy.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}t!=="custom"&&(f=Hut(f,h));const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=rc(e);return{id:i||`calc_${sle(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",expression:f,calculatedFormula:p,entityId:o,entityName:Ei,entityType:"table",description:`Calculated field: ${e}`}}function Wut(e){var r,s;const t=Oy.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function qut(e,t,n,r,s,o){const i=rc(e);return{id:o||`calc_dim_${sle(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Ei,entityType:"table",description:`Calculated field: ${e.trim()}`}}function Yut(){const{domainCalculatedFields:e}=I5(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function Gut({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx($s,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(js,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(sn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function Kut({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Hn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:l.jsx(Tt,{className:"size-3.5"})})]}),l.jsx(Ba,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(SE,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(Rp,{value:f.id,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:Q("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(h.dataType),h.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:Q("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&l.jsx(tt,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function Zut({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Oy.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Oy.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(xt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(pt,{children:l.jsx(vt,{})}),l.jsx(gt,{children:l.jsxs(NP,{children:[l.jsx(cj,{children:"OPERATIONS"}),i.map(c=>l.jsx(_e,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const Xut={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function Qut({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Nn(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(xt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(pt,{className:"h-9",children:l.jsx(vt,{})}),l.jsx(gt,{children:c.map(u=>l.jsx(_e,{value:u,children:Xut[u]},u))})]})}const Jut=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function UV({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return l.jsxs("div",{className:Q("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(xt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(pt,{className:"h-9 flex-1",children:l.jsx(vt,{placeholder:"Select field"})}),l.jsx(gt,{children:f.map(h=>l.jsx(_e,{value:h.id,children:Jut(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(Qut,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:c})})]}),t&&l.jsx(ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Tt,{className:"h-3.5 w-3.5"})})]})}const HV=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,docsUrl:o,placeholder:i,disabled:a},c){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),l.jsxs("div",{className:"flex items-center gap-2",children:[o&&l.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:["Docs",l.jsx(ep,{className:"h-3 w-3"})]}),s&&l.jsxs(ne,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:a,className:"h-7 gap-2 text-xs",children:[l.jsx(X1,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]})]}),l.jsx(ah,{ref:c,value:t,onChange:u=>n(u.target.value),disabled:a,rows:3,placeholder:i||"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-0 resize-none overflow-y-auto font-mono text-xs leading-5"})]})}),O5=A.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(Nye,{children:l.jsx(ta,{children:l.jsx(g0,{ref:r,sideOffset:t,className:Q("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));O5.displayName="ValidationTooltipContent";const ole=JA;function D_(e,t){return`${e} ${t}${e===1?"":"s"}`}function edt({result:e}){const t=e.errors.length>0,n=D_(e.tokens.length,"token"),r=e.errors.length>0?D_(e.errors.length,"error"):null,s=e.warnings.length>0?D_(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
1196
- `);return l.jsxs(yn,{delayDuration:120,children:[l.jsx(vn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:Q("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Tt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(es,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(O5,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:Q("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(oA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(rd,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(ole,{className:"fill-popover"})]})]})}function WV({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(ne,{type:"button",variant:"outline",onClick:e,disabled:t||s,className:"h-8",children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(edt,{result:n}),!n&&r&&l.jsxs(yn,{delayDuration:120,children:[l.jsx(vn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Tt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(O5,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(rd,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(ole,{className:"fill-popover"})]})]})]})}function tdt({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Availability"}),l.jsxs(Po,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-card",value:"card"}),l.jsx(pe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(pe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-domain",value:"domain"}),l.jsx(pe,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function ndt({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-2 rounded-md border border-muted bg-muted/30 p-2.5",children:[l.jsxs("div",{className:"grid gap-2 sm:grid-cols-[minmax(0,1fr)_220px] sm:items-end",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(pe,{htmlFor:"domain-description",children:"Description"}),l.jsx(ah,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:Q("min-h-0 resize-none overflow-y-auto text-sm",s&&"border-red-500"),rows:2,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(pe,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(Pt,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o,className:"h-9"})]})]}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function rdt(e){var r;const t=Jy(e,"AI generation failed"),n=(r=Ffe(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function sdt({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=it(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await Ur(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c(rdt(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function ile(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei}function odt(e){return ile(e)?Ao:e.qualifiedEntityName||e.entityName||"Other"}function idt(e){return ile(e)?"Calculated Fields":e.qualifiedEntityName?Uf(e.entityName||e.qualifiedEntityName):Uf(e.entityName||"Other")}function adt({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),[m,p]=w.useState([]),g=w.useRef(null),{generateExpression:b,isGenerating:x,error:y}=sdt({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=w.useMemo(()=>{const M=f.trim().toLowerCase();return M?n.filter(F=>[F.label,F.baseLabel,F.name,F.tokenLabel,F.entityName,F.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(M)):n},[n,f]),C=w.useMemo(()=>{const M=new Map;return v.forEach(F=>{var L;const P=odt(F),D=idt(F);M.has(P)||M.set(P,{id:P,label:D,fields:[]}),(L=M.get(P))==null||L.fields.push(F)}),Array.from(M.values())},[v]),S=w.useMemo(()=>C.map(M=>M.id),[C]);w.useEffect(()=>{e&&p(S)},[e,S]),w.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(M=>{const F=M.filter(P=>S.includes(P));return F.length>0?F:S})}},[e,f,S]);const N=M=>{const P=(M.name||M.baseLabel||M.label||M.tokenLabel||"").trim();return P.includes(".")&&P.split(".").pop()||P},j=M=>{const F=`{${M}}`,P=g.current;if(!P){c(z=>z+F);return}const D=P.selectionStart||0,L=P.selectionEnd||0;c(z=>`${z.slice(0,D)}${F}${z.slice(L)}`),requestAnimationFrame(()=>{P.focus();const z=D+F.length;P.setSelectionRange(z,z)})},k=M=>{const F=M.tokenLabel||M.name||M.baseLabel||M.label||"";F.trim()&&j(F.trim())},_=async()=>{const M=await b(a.trim());M&&d(M)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},T=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(Yr,{open:e,onOpenChange:M=>{M?t(!0):T()},children:l.jsxs(Rr,{className:"max-w-3xl",children:[l.jsxs(Pr,{children:[l.jsx(Fr,{children:"Generate Expression with AI"}),l.jsx(us,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(ah,{id:"ai-prompt",ref:g,value:a,onChange:M=>c(M.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(ne,{size:"sm",onClick:_,disabled:x||!a.trim(),children:x?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(Pt,{value:f,onChange:M=>h(M.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(Ba,{className:"h-64",children:C.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(SE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:C.map(M=>l.jsxs(Rp,{value:M.id,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:M.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:M.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:M.fields.map(F=>l.jsxs("button",{type:"button",onClick:()=>k(F),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(F.dataType),F.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",F.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(F)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:F.tokenLabel})]}),l.jsx(tt,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:F.dataType})]},F.id))})})]},M.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Generated expression"}),l.jsx(ah,{value:u,onChange:M=>d(M.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Ls,{className:"gap-2",children:[l.jsx(ne,{variant:"ghost",onClick:T,children:"Cancel"}),l.jsx(ne,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const ldt=/\{([^}]+)\}/g;function NE(e){return e.trim().toLowerCase()}function ale(e){return Array.from(e.matchAll(ldt)).map(t=>t[1]).filter(Boolean)}function cdt(e){const t=new Set,n=[];return e.forEach(r=>{const s=NE(r);t.has(s)||(t.add(s),n.push(r))}),n}function L5(e){const t=new Map,n=(r,s)=>{const o=NE(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function A1(e,t){const n=ale(e),r=cdt(n),s=L5(t),o=r.map(a=>{const c=s.get(NE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function fD(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${udt(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function udt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const ddt=e=>e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei?"Calculated Fields":e.qualifiedEntityName?Uf(e.entityName||e.qualifiedEntityName):Uf(e.entityName||"Other");function fdt(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei?Ao:e.qualifiedEntityName||e.entityName||"Other"}const hdt=e=>Nn(e.dataType||"")==="number";function mdt(e,t,n){const r=new Set((n||[]).map(s=>Jd(s)));return e.filter(s=>{const o=Jd(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function pdt(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Ei?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function gdt(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||hdt(o);return{...o,isCompatible:i}}).filter(o=>r)}function bdt(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function xdt(e){const t=new Map;return e.forEach(n=>{var s;const r=fdt(n);t.has(r)||t.set(r,{id:r,label:ddt(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function ydt({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>mdt(e,t,r),[e,t,r]),a=w.useMemo(()=>pdt(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Eh(m)||m.role==="groupby"&&KN(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>L5(c),[c]),d=w.useMemo(()=>gdt(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>bdt(d,n),[d,n]),h=w.useMemo(()=>xdt(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const vdt=e=>Nn(e.dataType||"")==="number",qV=e=>vdt(e)?"SUM":"COUNT",wdt=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||qV(e)}}const t=qV(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},Cdt=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}}};function Sdt({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=it(),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),g=w.useMemo(()=>L5(t),[t]),b=w.useMemo(()=>ale(e).map(S=>{const N=g.get(NE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),x=w.useCallback((C,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:b,errors:N,warnings:[]}},[b]),y=w.useCallback(async()=>{var P;p(null);const C=n==null?void 0:n.trim();if(!C){const D=x("Validation endpoint is not configured");return d(D),D}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const D=x("Validation context is incomplete for server-side validation");return d(D),D}const{orderedTokens:N,orderedFields:j}=A1(e,t),k=[],_=[];N.forEach((D,L)=>{const z=j[L];z&&(k.push(D),_.push(z))});const E=o==="metric"?_.map(wdt):_,T=Cdt(e,_),M=fD(e,k),F={type:"calculated-field-expression",fieldType:o,expression:M,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const D=await Ur(C,(c==null?void 0:c.accessToken)||"",F),L=D==null?void 0:D.status,z=D==null?void 0:D.error,U=D==null?void 0:D.errorCode,B=[],R=[];L==="invalid"?B.push({code:"SQL_VALIDATION_ERROR",message:z||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):L==="unverified"?R.push({code:"EXECUTION_UNVERIFIED",message:z||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&B.push({code:"SQL_VALIDATION_ERROR",message:z||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const V={isValid:(L==="valid"||L==="unverified")&&B.length===0,tokens:b,errors:B,warnings:R,inferredDataType:(D==null?void 0:D.inferredDataType)??((P=D==null?void 0:D.metadata)==null?void 0:P.inferredDataType)??T??i??void 0};return d(V),V}catch(D){const L=(D==null?void 0:D.error)||(D==null?void 0:D.message)||"Expression validation failed";p(L);const z=x(L);return d(z),z}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,x,b]),v=w.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function YV(e,t){const{aggregate:n,...r}=e;return{...r,...t}}const GV=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],Ndt=[],jdt="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",Edt="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",kdt="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",_dt="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",A_=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},lle=e=>Nn(e.dataType||"")==="number",cm=e=>lle(e)?"SUM":"COUNT",R_=(e,t)=>lle(e)||t==="COUNT"||t==="DISTINCT"?t:cm(e);function P_(e,t){if(e.role==="metric"){const n=e;return Eh(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function em(e,t){const n=e.role==="metric"&&Eh(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function cle({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Es;const{tokenProps:m}=it(),{selectedConnection:p}=FK(),g=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.config}),b=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.dataSource}),x=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.type}),v=ze(ue=>ue.filterValues)??Ndt,C=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[S,N]=w.useState(f),[j,k]=w.useState(""),[_,E]=w.useState("ratio"),[T,M]=w.useState(null),[F,P]=w.useState(null),[D,L]=w.useState(1),[z,U]=w.useState(""),[B,R]=w.useState(null),[V,O]=w.useState("card"),[I,W]=w.useState(""),[X,Z]=w.useState(""),[$,Y]=w.useState({}),[q,H]=w.useState("A"),[K,G]=w.useState(""),[J,re]=w.useState(!1),[me,ee]=w.useState(null),[xe,oe]=w.useState(!1),[de,Ce]=w.useState(!1),je=w.useRef(null),Ae=w.useRef(!1),ge=w.useRef(null),{userContext:Oe}=Vo(),{metrics:Ee,dimensions:le}=Yut(),se=(Oe==null?void 0:Oe.type)==="organization",Se=!se,he=!!d&&se,fe=he&&!!a,Fe=he&&!!c,ye=!!(i||fe||Fe),Ne=!!i,$e=S==="metric"?fe:Fe,Re=(Es=m==null?void 0:m.apiServiceUrl)==null?void 0:Es.replace(/\/$/,""),Ue=Re?`${Re}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",He=Re?`${Re}/v1/ai/generate`:"/v1/ai/generate",Ye=w.useMemo(()=>{var ot;const ue=[...n];return(((ot=r==null?void 0:r.calculatedFormula)==null?void 0:ot.inputFields)||[]).forEach(mt=>{ue.some(Lt=>Lt.id===mt.id||Lt.qualifiedFieldName===mt.qualifiedFieldName||Lt.name===mt.name)||ue.push(mt)}),ue},[n,r]),et=q==="A"?T:F,ie=S==="metric"&&_!=="custom"?et==null?void 0:et.aggregate:void 0,{allFields:Te,groups:Pe}=ydt({fields:Ye,mode:S,searchTerm:K,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:ie,showIncompatible:!0}),Ie=Te,{validationResult:Ze,validateExpression:ke,isValidating:We,serverError:ct,resetValidation:Be}=Sdt({expression:z,availableFields:Ie,validationEndpoint:Ue,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect,fieldType:S,outputType:B||void 0,validationContext:{connectionId:(p==null?void 0:p.id)||(b==null?void 0:b.connectionId),cardId:u,cardConfig:g||{},cardDataSource:b||null,activeFilters:v,cardType:x}}),Je=Ze==null?void 0:Ze.inferredDataType,ft=B||Je||"string",kt=Oy.find(ue=>ue.id===_),en=w.useMemo(()=>{if(!j.trim())return!1;const ue=rc(j),qe=s==="domain"&&(r!=null&&r.name)?rc(r.name):null;return(S==="metric"?Ee:le).some(mt=>{const ut=rc(mt.name);return qe&&ut===qe?!1:ut===ue})},[le,Ee,r,s,S,j]),Bn=w.useMemo(()=>{if(S==="metric"&&_==="custom"){const{orderedFields:qe}=A1(z,Ie);return qe.filter(ot=>!!ot).map(ot=>ot.id)}const ue=[];return T!=null&&T.field.id&&ue.push(T.field.id),F!=null&&F.field.id&&ue.push(F.field.id),ue},[Ie,z,S,T,F,_]),ar=ue=>{Se||(N(ue),ue==="dimension"&&V==="domain"&&!Fe&&O("card"),ue==="metric"&&V==="domain"&&!fe&&O("card"))},qn=ue=>{Se||(E(ue),ue==="scale"&&P(null),ue==="custom"&&(M(null),P(null)))},Yn=()=>{k(""),E("ratio"),M(null),P(null),L(1),U(""),R(null),O("card"),W(""),Z(""),Y({}),G(""),re(!1),ee(null),oe(!1),Be(),t(!1)},Zr=w.useCallback(ue=>Ye.find(qe=>qe.qualifiedFieldName===ue.qualifiedFieldName||qe.name===ue.name)||ue,[Ye]),zs=w.useCallback(ue=>{if(!ue.calculatedFormula)return;const qe=ue.calculatedFormula;if(E(qe.operation),U(""),qe.operation==="scale"){const ut=qe.inputFields[0];ut&&M(em(Zr(ut),ut.aggregate||"SUM")),L(qe.constant===void 0?1:qe.constant);return}if(qe.operation==="custom"){U(ve(ue.expression||"",qe.inputFields||[])),M(null),P(null);return}const[ot,mt]=qe.inputFields;ot&&M(em(Zr(ot),ot.aggregate||"SUM")),mt&&P(em(Zr(mt),mt.aggregate||"SUM"))},[Zr]),ve=w.useCallback((ue,qe)=>ue.replace(/\{field_(\d+)\}/g,(ot,mt)=>{var Mn;const ut=qe[Number(mt)];return ut?`{${((Mn=Ie.find(Gn=>Gn.id===ut.id))==null?void 0:Mn.tokenLabel)||ut.label||ut.name}}`:ot}),[Ie]);w.useEffect(()=>{var ot;if(!e){Ae.current=!1,ge.current=null;return}const ue=r?`${r.role}-${r.id||r.name}`:"new";if(Ae.current&&ge.current===ue)return;if(Ae.current=!0,ge.current=ue,Y({}),G(""),Be(),r){const mt=r.tags||[];if(r.role==="metric"){N("metric"),k(r.label||r.name),O(s||"card"),W(r.description||""),Z(mt.join(", ")),zs(r);return}N("dimension");const ut=r;k(ut.label||ut.name),O(s||"card"),U(ve(ut.expression||"",((ot=ut.calculatedFormula)==null?void 0:ot.inputFields)||[]));const Lt=GV.some(Mn=>Mn.value===ut.dataType)?ut.dataType:"string";R(Lt),W(ut.description||""),Z(mt.join(", "));return}const qe=h&&h.length>0?h.includes(f)?f:h[0]:f;N(qe),k(""),E("ratio"),M(null),P(null),L(1),U(""),R(null),O("card"),W(""),Z("")},[e,r,s,f,h,zs,ve,Be]);const Ke=ue=>{const qe=`{${ue}}`,ot=je.current;if(!ot){U(Mn=>Mn+qe);return}const mt=ot.selectionStart||0,ut=ot.selectionEnd||0,Lt=`${z.slice(0,mt)}${qe}${z.slice(ut)}`;U(Lt),requestAnimationFrame(()=>{ot.focus();const Mn=mt+qe.length;ot.setSelectionRange(Mn,Mn)})},wt=ue=>{if(Se)return;if(S==="dimension"||_==="custom"){Ke(ue.tokenLabel||ue.label||ue.name);return}const qe=R_(ue,q==="A"?(T==null?void 0:T.aggregate)||cm(ue):(F==null?void 0:F.aggregate)||cm(ue)),ot=em(ue,qe);if(q==="A"){M(ot),F||H("B");return}P(ot),T||H("A")},wn=(ue,qe)=>{if(!Se){if(ue==="A"&&T){M({...T,aggregate:qe});return}ue==="B"&&F&&P({...F,aggregate:qe})}},mr=async()=>{const ue={};if(j.trim()||(ue.name="Name is required"),_==="custom")z.trim()||(ue.expression="Expression is required"),ue.expression||(await ke()).isValid||(ue.expression="Fix validation errors before saving");else if(_==="scale")T||(ue.inputA="Please select a metric for input A"),Number.isNaN(D)&&(ue.constant="Please enter a valid multiplication factor");else{if(T||(ue.inputA="Please select a metric for input A"),F||(ue.inputB="Please select a metric for input B"),T&&F){const qe=T.field.id===F.field.id,ot=T.aggregate===F.aggregate;qe&&ot&&(ue.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const qe=Jd(r.id);(Jd(T==null?void 0:T.field.id)===qe||Jd(F==null?void 0:F.field.id)===qe)&&(ue.inputs="Cannot reference the field being edited")}}return ye&&(V==="domain"&&!fe&&(ue.scope="You do not have permission to save to domain"),V==="domain"&&!I.trim()&&(ue.description="Description is required for domain fields"),V==="domain"&&en&&(ue.name="A domain field with this name already exists")),Y(ue),Object.keys(ue).length===0},Xs=async()=>{const ue={};return j.trim()||(ue.name="Name is required"),z.trim()||(ue.expression="Expression is required"),ue.expression||(await ke()).isValid||(ue.expression="Fix validation errors before saving"),ye&&(V==="domain"&&!Fe&&(ue.scope="You do not have permission to save to domain"),V==="domain"&&!I.trim()&&(ue.description="Description is required for domain fields"),V==="domain"&&en&&(ue.name="A domain field with this name already exists")),Y(ue),Object.keys(ue).length===0},Uo=()=>{const{orderedTokens:ue,orderedFields:qe}=A1(z,Ie),ot=qe.filter(Lt=>!!Lt),mt=fD(z,ue),ut=qut(j,mt,ot,ft,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...ut}:ut},yt=()=>{var mt;if(_==="custom"){const{orderedTokens:ut,orderedFields:Lt}=A1(z,Ie),Mn=Lt.filter($t=>!!$t),Gn=(r==null?void 0:r.role)==="metric"?((mt=r.calculatedFormula)==null?void 0:mt.inputFields)||[]:[],tr=new Map;Gn.forEach($t=>{const Lr=Jd($t.id);Lr&&tr.set(Lr,$t),$t.qualifiedFieldName&&tr.set($t.qualifiedFieldName,$t),$t.name&&tr.set($t.name,$t)});const Ho=Mn.map($t=>{const Lr=Jd($t.id),Wo=Lr&&tr.get(Lr)||$t.qualifiedFieldName&&tr.get($t.qualifiedFieldName)||tr.get($t.name),Hg=((Wo==null?void 0:Wo.role)==="metric"?Wo.aggregate:void 0)||($t.role==="metric"?$t.aggregate:void 0)||cm($t);return P_($t,Hg)}),kn=fD(z,ut),hn=BV(j,_,null,null,{},u,r==null?void 0:r.id,kn,void 0,Ho);return r&&r.role==="metric"?YV(r,hn):hn}const ue=T?P_(T.field,T.aggregate):null,qe=F?P_(F.field,F.aggregate):null,ot=BV(j,_,ue,qe,{},u,r==null?void 0:r.id,void 0,_==="scale"?D:void 0);return r&&r.role==="metric"?YV(r,ot):ot},be=async ue=>{var ot,mt,ut;if(S==="dimension"){const Lt=Uo();if(ue==="dashboard"){if(!i){Y(Mn=>({...Mn,scope:"Dashboard scope is not available"}));return}i(Lt),Yn();return}if(ue==="domain"){if(!c){Y(hn=>({...hn,scope:"Domain scope is not available"}));return}const Mn=((ot=Lt.calculatedFormula)==null?void 0:ot.inputFields)||[],Gn=new Map,tr=Mn.map(hn=>{const $t=rc(hn.label||hn.name),Lr=Gn.get($t)||0;return Gn.set($t,Lr+1),Lr===0?$t:`${$t}_${Lr+1}`}),Ho=((mt=Lt.expression)==null?void 0:mt.replace(/\{field_(\d+)\}/g,(hn,$t)=>`{${tr[Number($t)]||$t}}`))||"",kn=tr.reduce((hn,$t,Lr)=>{const Wo=Mn[Lr];return KN(Wo)?hn[$t]={dimension:Wo.name}:hn[$t]={dataset:Wo.entityName,field:Wo.name},hn},{});try{await c({name:rc(j),label:j.trim(),description:I.trim(),expression:Ho,inputs:kn,dataType:ft,tags:X.split(",").map(hn=>hn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(hn){Y($t=>({...$t,scope:(hn==null?void 0:hn.message)||"Failed to save to domain"}));return}Yn();return}o(Lt),Yn();return}const qe=yt();if(ue==="dashboard"){if(!i){Y(Lt=>({...Lt,scope:"Dashboard scope is not available"}));return}i(qe),Yn();return}if(ue==="domain"){if(!a){Y(kn=>({...kn,scope:"Domain scope is not available"}));return}if(!qe.calculatedFormula){Y(kn=>({...kn,scope:"Calculated formula missing"}));return}const Lt=qe.calculatedFormula.inputFields,Mn=new Map,Gn=Lt.map(kn=>{const hn=rc(kn.label||kn.name),$t=Mn.get(hn)||0;return Mn.set(hn,$t+1),$t===0?hn:`${hn}_${$t+1}`}),tr=((ut=qe.expression)==null?void 0:ut.replace(/\{field_(\d+)\}/g,(kn,hn)=>`{${Gn[Number(hn)]||hn}}`))||"",Ho=Gn.reduce((kn,hn,$t)=>{const Lr=Lt[$t];return Lr.role==="metric"?Eh(Lr)?kn[hn]={metric:Lr.name}:kn[hn]={dataset:Lr.entityName,field:Lr.name,aggregate:Lr.aggregate}:kn[hn]={dataset:Lr.entityName,field:Lr.name},kn},{});try{await a({name:rc(j),label:j.trim(),description:I.trim(),expression:tr,inputs:Ho,tags:X.split(",").map(kn=>kn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(kn){Y(hn=>({...hn,scope:(kn==null?void 0:kn.message)||"Failed to save to domain"}));return}Yn();return}o(qe),Yn()},Qe=async()=>{if(Se)return;if(Y({}),S==="metric"){if(!await mr())return}else if(!await Xs())return;const ue=ye?V:s||"card";if(S==="metric"&&ue!=="domain"&&en&&!r){ee(ue),oe(!0);return}Ce(!0);try{await be(ue)}finally{Ce(!1)}},ht=w.useMemo(()=>{if(!kt||_==="custom")return"";if(_==="scale"){const ue=Number.isFinite(D)?D:1;return`${A_(T)} x ${ue}`}return`${A_(T)||"A"} ${kt.symbol} ${A_(F)||"B"}`},[kt,_,T,F,D]),pn=S==="metric"?jdt:Edt,lr=S==="metric"?kdt:_dt,er=S==="metric"?"Calculated Metric":"Calculated Dimension",Nr=S==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(Yr,{modal:!1,open:e,onOpenChange:ue=>{ue?t(!0):Yn()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Rr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:ue=>{ue.preventDefault()},children:[l.jsxs(Pr,{children:[l.jsxs(Fr,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(tt,{variant:"outline",className:Nr,children:er})]}),l.jsx(us,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(Kut,{groups:Pe,searchTerm:K,onSearchTermChange:G,onFieldClick:wt,selectedFieldIds:Bn,disabled:Se}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Field Type"}),l.jsx(Gut,{value:S,onChange:ar,disabled:Se||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"calculated-name",children:"Name"}),l.jsx(Pt,{id:"calculated-name",value:j,onChange:ue=>k(ue.target.value),placeholder:S==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:$.name?"border-red-500":"",disabled:Se}),$.name&&l.jsx("p",{className:"text-xs text-red-500",children:$.name})]}),ye&&(Ne||$e)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(tdt,{scope:V,onChange:O,showDashboardScope:Ne,showDomainScope:$e,error:$.scope,disabled:Se}),V==="domain"&&l.jsx(ndt,{description:I,tags:X,onDescriptionChange:W,onTagsChange:Z,descriptionError:$.description,disabled:Se})]}),S==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Operation"}),l.jsx(Zut,{value:_,onChange:qn,allowCustom:!0,disabled:Se}),$.operation&&l.jsx("p",{className:"text-xs text-red-500",children:$.operation})]}),_==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(HV,{ref:je,value:z,onChange:ue=>{U(ue)},onGenerate:()=>re(!0),showGenerate:!!He&&!Se,docsUrl:pn,placeholder:lr,disabled:Se}),l.jsx(WV,{onValidate:ke,isValidating:We,validationResult:Ze,error:ct,disabled:Se}),$.expression&&l.jsx("p",{className:"text-xs text-red-500",children:$.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(pe,{children:"Inputs"}),l.jsx(UV,{label:"A",input:T,availableFields:Ie,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:ue=>{const qe=R_(ue,(T==null?void 0:T.aggregate)||cm(ue));M(em(ue,qe))},onAggregateChange:ue=>wn("A",ue),onRemove:()=>M(null),onActivate:()=>H("A"),allowMedian:C,disabled:Se}),$.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:$.inputA}),_!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(UV,{label:"B",input:F,availableFields:Ie,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:ue=>{const qe=R_(ue,(F==null?void 0:F.aggregate)||cm(ue));P(em(ue,qe))},onAggregateChange:ue=>wn("B",ue),onRemove:()=>P(null),onActivate:()=>H("B"),allowMedian:C,disabled:Se}),$.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:$.inputB})]}),_==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(Pt,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(D)?"":D,onChange:ue=>L(ue.target.value===""?Number.NaN:Number(ue.target.value)),className:$.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:Se}),$.constant&&l.jsx("p",{className:"text-xs text-red-500",children:$.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:ht||"Select inputs to preview formula"}),$.inputs&&l.jsxs(Ej,{variant:"destructive",children:[l.jsx(Lc,{className:"h-4 w-4"}),l.jsx(kj,{children:$.inputs})]})]})]}),S==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(HV,{ref:je,value:z,onChange:ue=>{U(ue)},onGenerate:()=>re(!0),showGenerate:!!He&&!Se,docsUrl:pn,placeholder:lr,disabled:Se}),l.jsx(WV,{onValidate:ke,isValidating:We,validationResult:Ze,error:ct,disabled:Se}),$.expression&&l.jsx("p",{className:"text-xs text-red-500",children:$.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Output Type"}),l.jsxs(xt,{value:ft,onValueChange:ue=>R(ue),disabled:Se,children:[l.jsx(pt,{className:"h-9 w-full",children:l.jsx(vt,{placeholder:"Select output type"})}),l.jsx(gt,{children:GV.map(ue=>l.jsx(_e,{value:ue.value,children:ue.label},ue.value))})]}),Je&&!B&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",Je]})]})]})]})]}),l.jsxs(Ls,{children:[l.jsx(ne,{variant:"outline",onClick:Yn,disabled:de,children:"Cancel"}),l.jsx(ne,{onClick:Qe,disabled:de||Se,children:de?l.jsxs(l.Fragment,{children:[l.jsx(In,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Creating"," ",S==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Create"," ",S==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(adt,{open:J,onOpenChange:re,availableFields:Ie,fieldType:S,onExpressionGenerated:async ue=>{U(ue),Be()},endpoint:He,dialect:p==null?void 0:p.dialect}),l.jsx(Wc,{open:xe,onOpenChange:oe,children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Name Conflict"}),l.jsxs(Vl,{children:['A domain metric named "',j.trim(),'" already exists. Your local version will override it in this'," ",me==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs($l,{children:[l.jsx(Ul,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Bl,{onClick:async()=>{if(me){oe(!1),Ce(!0);try{await be(me)}finally{Ce(!1),ee(null)}}},children:"Continue"})]})]})})]})}function ule({domainId:e}){const{authToken:t,tokenProps:n}=it(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var g;if(!e)return null;const m=(g=n==null?void 0:n.apiServiceUrl)==null?void 0:g.replace(/\/$/,""),p=`/v1/domains/${e}/calculated-metrics`;return m?`${m}${p}`:p},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var g;if(!e)return null;const m=(g=n==null?void 0:n.apiServiceUrl)==null?void 0:g.replace(/\/$/,""),p=`/v1/domains/${e}/calculated-dimensions`;return m?`${m}${p}`:p},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async m=>{if(!a){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(a,t.accessToken,m)}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to save to domain";throw i(g),new Error(g)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async m=>{if(!c){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(c,t.accessToken,m)}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to save to domain";throw i(g),new Error(g)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]),f=w.useCallback(async({name:m})=>{if(!a){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(a,t.accessToken,{name:m},"DELETE")}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to delete from domain";throw i(g),new Error(g)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),h=w.useCallback(async({name:m})=>{if(!c){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(c,t.accessToken,{name:m},"DELETE")}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to delete from domain";throw i(g),new Error(g)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,deleteMetric:f,deleteDimension:h,isPromoting:r,error:o}}const dle=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var qn,Yn,Zr,zs;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric"),[b,x]=w.useState(null),[y,v]=w.useState(!1);ze(ve=>ve.isDevMode);const C=ze(ve=>ve.card.dataSource),S=ze(ve=>ve.card.config),N=ze(ve=>ve.card),j=ze(ve=>ve.frame),k=ze(ve=>ve.actions.updateCardConfig),_=ze(ve=>ve.actions.updateFrame),{userContext:E}=Vo(),{autoJoinMetadata:T}=_l(N),{columns:M,rawColumnGroups:F,scopedFields:P,domainCalculatedFields:D,dashboardCalculatedFields:L,cardCalculatedFields:z,isLoading:U,error:B,refetch:R}=I5(),V=(C==null?void 0:C.mode)==="semanticDomain"?C.semanticDomainId:void 0,{data:O}=M5(V),{promoteMetric:I,promoteDimension:W,deleteMetric:X,deleteDimension:Z}=ule({domainId:V}),$=w.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(Yn=(qn=S==null?void 0:S.joinPlan)==null?void 0:qn.baseEntity)==null||Yn.name,(zs=(Zr=T==null?void 0:T.resolvedJoinPlan)==null?void 0:Zr.baseEntity)==null||zs.name,Lae();const Y=t==="editor",q=(E==null?void 0:E.type)==="organization",H=Y?P:M,K=F,G=s.toLowerCase(),J=(S==null?void 0:S.metricColumns)||[],re=(S==null?void 0:S.groupByColumns)||[],me=w.useCallback(async ve=>{try{await I(ve),await R(),Ge.success(`${ve.overwrite?"Updated":"Saved"} ${ve.label||ve.name} in the semantic domain`)}catch(Ke){const wt=(Ke==null?void 0:Ke.message)||(Ke==null?void 0:Ke.error)||"Failed to save to semantic domain";throw Ge.error(wt),Ke}},[I,R]),ee=w.useCallback(async ve=>{try{await W(ve),await R(),Ge.success(`${ve.overwrite?"Updated":"Saved"} ${ve.label||ve.name} in the semantic domain`)}catch(Ke){const wt=(Ke==null?void 0:Ke.message)||(Ke==null?void 0:Ke.error)||"Failed to save to semantic domain";throw Ge.error(wt),Ke}},[W,R]),xe=ve=>ve.name.toLowerCase().includes(G)||ve.dataType.toLowerCase().includes(G)||ve.label&&ve.label.toLowerCase().includes(G)||ve.qualifiedEntityName&&ve.qualifiedEntityName.toLowerCase().includes(G),oe=w.useCallback(ve=>(ve.label||ve.name).toLowerCase().trim(),[]),de=w.useCallback((ve,Ke)=>oe(ve).localeCompare(oe(Ke),void 0,{numeric:!0,sensitivity:"base"}),[oe]),Ce=H.filter(xe).sort(de),je=ve=>{if(ve.role==="metric"&&Eh(ve)||ve.role==="groupby"&&ve.expression)return"calculated";if(ve.dataType==="number"||ve.dataType==="integer"||ve.dataType==="float"||ve.dataType==="decimal"||ve.dataType==="currency")return"metrics";const Ke=Nn(ve.dataType);return["date","string","boolean"].includes(Ke)?"dimensions":Ke==="number"?"metrics":"dimensions"},Ae=ve=>{const Ke=ve.filter(xe);return i==="all"?Ke:Ke.filter(wt=>je(wt)===i)},ge=i==="all"?Ce:Ce.filter(ve=>je(ve)===i),Oe=Y?[...D,...L,...z]:[],Ee=Y?Ae(Oe).sort(de):[],le=Y?M.filter(ve=>ve.fieldScope!=="domain"):M,Se=Ae(le).sort(de).reduce((ve,Ke)=>{const wt=Ke.qualifiedEntityName||"Other Fields";return ve[wt]||(ve[wt]={label:Uf(Ke.entityName),fields:[]}),ve[wt].fields.push(Ke),ve},{}),he=w.useMemo(()=>Object.entries(Se).map(([ve,Ke])=>{const wt=K.find(mr=>mr.entityName===ve)||{entityName:ve,label:Ke.label},wn=ve===Ao?"Domain Calculated Fields":wt.label||wt.entityName;return{groupName:ve,groupLabel:wn,fields:[...Ke.fields].sort(de)}}).sort((ve,Ke)=>ve.groupLabel.localeCompare(Ke.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Se,K,de]),fe=ve=>ve.id||`${ve.entityName}-${ve.qualifiedEntityName}-${ve.name}-${ve.role||"field"}`,Fe=w.useMemo(()=>{const ve=new Map;return(Y?P:M).forEach(wt=>{ve.set(fe(wt),rP(wt,{joinabilityMap:(O==null?void 0:O.joinabilityMap)||null,selectedFields:$,cardConfig:S,autoJoinMetadata:T}))}),ve},[Y,P,M,O==null?void 0:O.joinabilityMap,$,S,T]),ye=Y?[{key:"scope-calculated",label:"Calculated Fields",fields:Ee}].filter(ve=>ve.fields.length>0):[],$e=[...ye.map(ve=>ve.key),...he.map(ve=>ve.groupName)],Re=Ce.filter(ve=>je(ve)==="dimensions").length,Ue=Ce.filter(ve=>je(ve)==="metrics").length,He=Ce.filter(ve=>je(ve)==="calculated").length,Ye=Ce.length>0&&t!=="inline-filter",et=t==="inline-filter"?"w-full":"w-[290px]";if(U)return l.jsx("div",{className:Q("flex h-full flex-col items-center justify-center py-8",et),children:l.jsx(nd,{size:"md",color:"muted","aria-label":"Loading data"})});if(B)return l.jsxs("div",{className:Q("flex h-full flex-col items-center justify-center py-8",et),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:B.message||"Failed to load column data"})]});if(!C||!C.selectedEntities||C.selectedEntities.length===0)return l.jsxs("div",{className:Q("flex flex-col items-center justify-center py-8 text-center",et),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const ie=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Te=t==="inline-filter"?"overflow-hidden":"",Pe=ve=>ve!=null&&ve.startsWith("card-source-")?ve.replace("card-source-",""):ve,Ie=(ve,Ke,wt)=>{const wn=Pe(ve.id),mr=Pe(Ke.id);return wn&&mr&&wn===mr?!0:!wn||!mr||wt!=null&&wt.allowNameFallback?ve.name===Ke.name&&ve.role===Ke.role:!1},Ze=(ve,Ke,wt)=>ve.findIndex(wn=>Ie(wn,Ke,wt)),ke=ve=>{if(!j)return ve;const Ke=j.calculatedFields||[],wt=Ze(Ke,ve),wn=wt>=0&&Ke[wt].id!==ve.id?{...ve,id:Ke[wt].id}:ve,mr=wt>=0?Ke.map((Xs,Uo)=>Uo===wt?wn:Xs):[...Ke,wn];return _({calculatedFields:mr}),wn},We=(ve,Ke,wt,wn)=>{var Xs;const mr=Ze(ve,wt||Ke,wn);if(mr>=0){const Uo=(Xs=ve[mr])==null?void 0:Xs.id,yt=Uo&&Uo!==Ke.id?{...Ke,id:Uo}:Ke;return ve.map((be,Qe)=>Qe===mr?yt:be)}return[...ve,Ke]},ct=ve=>{if(ve.role==="metric")return J.find(Ke=>Ie(Ke,ve));if(ve.role==="groupby")return re.find(Ke=>Ie(Ke,ve))},Be=ve=>{var Ke;return(Ke=j==null?void 0:j.calculatedFields)==null?void 0:Ke.find(wt=>Ie(wt,ve))},Je=ve=>{if(ve.role==="metric"){k(N.id,{metricColumns:J.filter(Ke=>!Ie(Ke,ve,{allowNameFallback:ve.fieldScope==="dashboard"}))});return}ve.role==="groupby"&&k(N.id,{groupByColumns:re.filter(Ke=>!Ie(Ke,ve,{allowNameFallback:ve.fieldScope==="dashboard"}))})},ft=ve=>{if(!j)return;const Ke=(j.calculatedFields||[]).filter(wt=>!Ie(wt,ve));_({calculatedFields:Ke})},kt=ve=>{if(!q)return;if(ve.fieldScope==="domain"){f(ve),m("domain"),g(ve.role==="metric"?"metric":"dimension"),u(!0);return}if(ve.fieldScope==="dashboard"){const wt=Be(ve);if(!wt)return;f(wt),m("dashboard"),g(wt.role==="metric"?"metric":"dimension"),u(!0);return}const Ke=ct(ve);Ke&&(f(Ke),m("card"),g(Ke.role==="metric"?"metric":"dimension"),u(!0))},en=async ve=>{if(q){if(ve.fieldScope==="domain"){if(!V){Ge.error("Domain context is unavailable");return}try{ve.role==="metric"?await X({name:ve.name}):ve.role==="groupby"&&await Z({name:ve.name}),Je(ve),await R(),Ge.success(`Removed ${ve.label||ve.name} from the semantic domain`)}catch(Ke){throw Ge.error((Ke==null?void 0:Ke.message)||"Failed to delete domain calculated field"),Ke}return}if(ve.fieldScope==="dashboard"){ft(ve),Je(ve);return}Je(ve)}},Bn=async()=>{if(b){v(!0);try{await en(b),x(null)}catch{}finally{v(!1)}}},ar=ve=>{if(!q)return null;const wt=ve.fieldScope==="domain"&&!V;return l.jsxs(ud,{children:[l.jsx(dd,{asChild:!0,children:l.jsx(ne,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(vh,{className:"h-3.5 w-3.5"})})}),l.jsxs(Uc,{align:"end",className:"w-36",children:[l.jsx(lo,{onClick:()=>kt(ve),children:"Edit"}),l.jsx(lo,{className:"text-destructive focus:text-destructive",disabled:wt,onClick:()=>x(ve),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Q("mt-2 flex h-full w-full grow flex-col gap-2",ie,Te),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[H.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Hn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ve=>o(ve.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Tt,{className:"size-3.5"})})]}),Ye&&l.jsx($s,{defaultValue:"all",value:i,onValueChange:ve=>a(ve),className:"mb-4",children:l.jsxs(js,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(sn,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ce.length})]}),l.jsxs(sn,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(rN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Re})]}),l.jsxs(sn,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(QS,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ue})]}),l.jsxs(sn,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(iA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:He})]})]})}),t==="editor"&&i==="calculated"&&q&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(ne,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(qr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(Ba,{className:"min-h-0 flex-1",children:[l.jsxs(SE,{type:"multiple",defaultValue:$e,className:"space-y-2",children:[ye.map(ve=>l.jsxs(Rp,{value:ve.key,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ve.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ve.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ve.fields.map(Ke=>{const wt=Fe.get(fe(Ke)),wn=t==="editor"&&q&&je(Ke)==="calculated";return l.jsx(zV,{field:Ke,context:t,fieldState:wt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:wn?ar(Ke):void 0},Ke.id)})})})]},ve.key)),he.map(({groupName:ve,groupLabel:Ke,fields:wt})=>l.jsxs(Rp,{value:ve,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:Ke,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Ke}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:wt.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:wt.map(wn=>{const mr=Fe.get(fe(wn)),Xs=t==="editor"&&q&&je(wn)==="calculated";return l.jsx(zV,{field:wn,context:t,fieldState:mr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Xs?ar(wn):void 0},wn.id)})})})]},ve))]}),H.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),H.length>0&&ge.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Ra,{orientation:"horizontal"}),l.jsx(Ra,{orientation:"vertical"})]})]}),l.jsx(Wc,{open:!!b,onOpenChange:ve=>{ve||x(null)},children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Delete calculated field?"}),l.jsxs(Vl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(b==null?void 0:b.label)||(b==null?void 0:b.name)||"this calculated field"})," ",(b==null?void 0:b.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs($l,{children:[l.jsx(Ul,{disabled:y,children:"Cancel"}),l.jsx(Bl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:ve=>{ve.preventDefault(),Bn()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(cle,{open:c,onOpenChange:ve=>{u(ve),ve||(f(null),m("card"))},availableFields:P,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ve=>{if(ve.role==="metric"){if(d&&h==="card"){k(N.id,{metricColumns:We(J,ve,d)});return}k(N.id,{metricColumns:We(J,ve)});return}if(d&&h==="card"){k(N.id,{groupByColumns:We(re,ve,d)});return}k(N.id,{groupByColumns:We(re,ve)})},onSaveToDashboard:ve=>{const Ke=!!(d&&h==="dashboard"),wt=Ke?d:void 0;if(ve.role==="metric"){const mr=ke(ve);k(N.id,{metricColumns:We(J,mr,wt,{allowNameFallback:Ke})});return}const wn=ke(ve);k(N.id,{groupByColumns:We(re,wn,wt,{allowNameFallback:Ke})})},cardId:N.id,onPromoteMetricToDomain:V?me:void 0,onPromoteDimensionToDomain:V?ee:void 0,domainId:V})]})}),fle=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(dle,{context:t})," "]})});function hle(){const e=ze(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=_r();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=A5(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Tdt(){hle();const e=te(c=>c.selectedSheetId),t=te(c=>c.selectedFrameId),n=te(c=>c.dashboard),r=te(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=Jt(),{setCard:o}=_r(),i=ze(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Idt(){const e=te(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Jt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(ns,{children:[l.jsx(rs,{asChild:!0,children:l.jsx(ne,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(gl,{className:"h-4 w-4"})})}),l.jsx(ss,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(Po,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Rn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(pe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Rn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(pe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Qt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(pe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Qt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(pe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Mdt(){const e=te(n=>n.actions.setShowFilters),{hasEntities:t}=Tdt();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(pe,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Idt,{}),l.jsx(ne,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(hre,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(cv,{collisionDetection:iv,children:l.jsx(uv,{items:[],strategy:FO,children:l.jsx(fle,{context:"filter"})})})})]})}function Ddt(){const e=te(r=>r.dashboard.filters),t=te(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:Q("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)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(TO,{filter:r}),l.jsx(Dg,{filter:r})]},r.id))}):null}function Adt(){const e=te(r=>r.showFilters),t=te(r=>r.isVisualEditing),n=te(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Q("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Ddt,{}),l.jsx(Tae,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Mdt,{})})]})}const Rdt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-nYrePhKP.js"))),Pdt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-f17MIvBF.js"))),Fdt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-B9J-U_dZ.js"))),Odt=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CtIxVLTX.js")).then(e=>({default:e.ResourceManagementPanel})));function Ldt({showControls:e=!1,showFooter:t=!0,...n}){const r=te(c=>c.isDashboardPanelOpen),s=te(c=>c.isVisualEditing),o=te(c=>c.showDashboardJSON),i=te(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Fa,{FallbackComponent:zj,children:l.jsxs(sA,{dashboardProps:n,children:[l.jsx(sye,{}),l.jsx(T5,{componentType:"surfboard",componentId:n.id}),l.jsx(_5,{children:l.jsxs(Iae,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Fdt,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Rdt,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Odt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(TP,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Pdt,{})}),l.jsx(Adt,{})]})})]})]})]})})]})})}const mle=A.forwardRef(({className:e,...t},n)=>l.jsx(ev,{className:Q("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(mO,{className:Q("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));mle.displayName=ev.displayName;var $dt=Object.defineProperty,zdt=(e,t,n)=>t in e?$dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Jw=(e,t,n)=>zdt(e,typeof t!="symbol"?t+"":t,n);const Vdt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Bdt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},Udt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Hdt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function ple(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Wdt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=ple(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},qdt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Ydt={stringify:e=>e,parse:e=>e},F_={string:Ydt,number:qdt,boolean:Vdt,function:Bdt,method:Wdt,json:Udt},xb=Symbol.for("r2wc.render"),e1=Symbol.for("r2wc.connected"),zd=Symbol.for("r2wc.context"),ci=Symbol.for("r2wc.props");function Gdt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Hdt(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Jw(this,o,!0),Jw(this,s),Jw(this,r,{}),Jw(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[ci].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?F_[x]:null;if(x==="method"){const v=ple(g);Object.defineProperty(this[ci].container,v,{enumerable:!0,configurable:!0,get(){return this[ci][v]},set(C){this[ci][v]=C,this[xb]()}}),this[ci][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[ci][p]=y.parse(b,g,this))}for(const p of a)this[ci][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[e1]=!0,this[xb]()}disconnectedCallback(){this[e1]=!1,this[zd]&&n.unmount(this[zd]),delete this[zd]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?F_[y]:null;x in c&&v!=null&&v.parse&&b&&(this[ci][x]=v.parse(b,p,this),this[xb]())}[(o=e1,s=zd,r=ci,xb)](){this[e1]&&(this[zd]?n.update(this[zd],this[ci]):this[zd]=n.mount(this.container,e,this[ci]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[ci][m]},set(b){this[ci][m]=b;const x=g?F_[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[xb]()}})}return h}function Kdt(e,t,n){const r=hce.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Zdt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Xdt({root:e}){e.unmount()}function Qdt(e,t={}){return Gdt(e,t,{mount:Kdt,update:Zdt,unmount:Xdt})}const Jdt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},eft=Qdt(Mae,{props:Jdt});function KV(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function tft(e){if(Array.isArray(e))return e}function nft(e,t,n){return(t=cft(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rft(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function sft(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1195
+ `)}})}});var Olt=Iat(()=>Xie(Qi([Mr({type:rn("text-start"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("text-delta"),id:Et(),delta:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("text-end"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("error"),errorText:Et()}),Mr({type:rn("tool-input-start"),toolCallId:Et(),toolName:Et(),providerExecuted:Ko().optional(),dynamic:Ko().optional()}),Mr({type:rn("tool-input-delta"),toolCallId:Et(),inputTextDelta:Et()}),Mr({type:rn("tool-input-available"),toolCallId:Et(),toolName:Et(),input:el(),providerExecuted:Ko().optional(),providerMetadata:Xr.optional(),dynamic:Ko().optional()}),Mr({type:rn("tool-input-error"),toolCallId:Et(),toolName:Et(),input:el(),providerExecuted:Ko().optional(),providerMetadata:Xr.optional(),dynamic:Ko().optional(),errorText:Et()}),Mr({type:rn("tool-output-available"),toolCallId:Et(),output:el(),providerExecuted:Ko().optional(),dynamic:Ko().optional(),preliminary:Ko().optional()}),Mr({type:rn("tool-output-error"),toolCallId:Et(),errorText:Et(),providerExecuted:Ko().optional(),dynamic:Ko().optional()}),Mr({type:rn("reasoning-start"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("reasoning-delta"),id:Et(),delta:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("reasoning-end"),id:Et(),providerMetadata:Xr.optional()}),Mr({type:rn("source-url"),sourceId:Et(),url:Et(),title:Et().optional(),providerMetadata:Xr.optional()}),Mr({type:rn("source-document"),sourceId:Et(),mediaType:Et(),title:Et(),filename:Et().optional(),providerMetadata:Xr.optional()}),Mr({type:rn("file"),url:Et(),mediaType:Et(),providerMetadata:Xr.optional()}),Mr({type:qie(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Et().optional(),data:el(),transient:Ko().optional()}),Mr({type:rn("start-step")}),Mr({type:rn("finish-step")}),Mr({type:rn("start"),messageId:Et().optional(),messageMetadata:el().optional()}),Mr({type:rn("finish"),finishReason:Uie(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:el().optional()}),Mr({type:rn("abort")}),Mr({type:rn("message-metadata"),messageMetadata:el()})])));function Llt(e){return e.type.startsWith("data-")}function oae(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=oae(o,s):n[r]=s}return n}function $lt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function iae(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await MS({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await MS({text:$lt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function I1(e){return e.type.startsWith("tool-")}function zlt(e){return e.type==="dynamic-tool"}function iD(e){return I1(e)||zlt(e)}function MV(e){return e.type.split("-").slice(1).join("-")}function Vlt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Blt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,m,p;function g(C){const N=u.message.parts.filter(I1).find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function b(C){const N=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===C);if(N==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return N}function x(C){var S;const N=u.message.parts.find(_=>I1(_)&&_.toolCallId===C.toolCallId),j=C,k=N;N!=null?(N.state=C.state,k.input=j.input,k.output=j.output,k.errorText=j.errorText,k.rawInput=j.rawInput,k.preliminary=j.preliminary,k.providerExecuted=(S=j.providerExecuted)!=null?S:N.providerExecuted,j.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(C){var S,N;const j=u.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===C.toolCallId),k=C,_=j;j!=null?(j.state=C.state,_.toolName=C.toolName,_.input=k.input,_.output=k.output,_.errorText=k.errorText,_.rawInput=(S=k.rawInput)!=null?S:_.rawInput,_.preliminary=k.preliminary,_.providerExecuted=(N=k.providerExecuted)!=null?N:j.providerExecuted,k.providerMetadata!=null&&j.state==="input-available"&&(j.callProviderMetadata=k.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,providerExecuted:k.providerExecuted,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function v(C){if(C!=null){const S=u.message.metadata!=null?oae(u.message.metadata,C):C;t!=null&&await EV({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(m=a.providerMetadata)!=null?m:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(I1);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:S}=await iae(C.text);C.dynamic?y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:MV(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:MV(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Llt(a)){(n==null?void 0:n[a.type])!=null&&await EV({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const S=C.id!=null?u.message.parts.find(N=>C.type===N.type&&C.id===N.id):void 0;S!=null?S.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function Ult({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}bv({prefix:"aitxt",size:24});bv({prefix:"aiobj",size:24});var Hlt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};bv({prefix:"aiobj",size:24});var Wlt={};klt(Wlt,{object:()=>Ylt,text:()=>qlt});var qlt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Ylt=({schema:e})=>{const t=jlt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await iae(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await MS({text:n});if(!s.success)throw new TV({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await C5({value:s.value,schema:t});if(!o.success)throw new TV({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Glt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Klt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Jh(this.body),c=await Jh(this.headers),u=await Jh(this.credentials),d={...qd(c),...qd(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,m=(f==null?void 0:f.headers)!==void 0?qd(f.headers):d,p=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:NV({"Content-Type":"application/json",...m},`ai-sdk/${IV}`,SV()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Jh(this.body),a=await Jh(this.headers),c=await Jh(this.credentials),u={...qd(a),...qd(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?qd(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:c,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:NV(h,`ai-sdk/${IV}`,SV()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},N5=class extends Klt{constructor(e={}){super(e)}processResponseStream(e){return Aat({stream:e,schema:Olt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},Zlt=class{constructor({generateId:e=Sat,id:t=e(),transport:n=new N5,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new Hlt,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await Glt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(C=>iD(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>iD(C)&&C.toolCallId===m?{...C,state:f,output:p,errorText:g}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:Vlt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await Ult({stream:Blt({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function aae({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(iD).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Xlt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Qlt=Xlt;const Jlt=hh(Qlt);var lae=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},gr=(e,t,n)=>(lae(e,t,"read from private field"),n?n.call(e):t.get(e)),Ga=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},au=(e,t,n,r)=>(lae(e,t,"write to private field"),t.set(e,n),n);function ect(e,t){return t!=null?Jlt(e,t):e}var Ri,M1,D1,Xb,Qb,Jb,am,aD,lD,tct=class{constructor(e=[]){Ga(this,Ri,void 0),Ga(this,M1,"ready"),Ga(this,D1,void 0),Ga(this,Xb,new Set),Ga(this,Qb,new Set),Ga(this,Jb,new Set),this.pushMessage=t=>{au(this,Ri,gr(this,Ri).concat(t)),gr(this,am).call(this)},this.popMessage=()=>{au(this,Ri,gr(this,Ri).slice(0,-1)),gr(this,am).call(this)},this.replaceMessage=(t,n)=>{au(this,Ri,[...gr(this,Ri).slice(0,t),this.snapshot(n),...gr(this,Ri).slice(t+1)]),gr(this,am).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?ect(t,n):t;return gr(this,Xb).add(r),()=>{gr(this,Xb).delete(r)}},this["~registerStatusCallback"]=t=>(gr(this,Qb).add(t),()=>{gr(this,Qb).delete(t)}),this["~registerErrorCallback"]=t=>(gr(this,Jb).add(t),()=>{gr(this,Jb).delete(t)}),Ga(this,am,()=>{gr(this,Xb).forEach(t=>t())}),Ga(this,aD,()=>{gr(this,Qb).forEach(t=>t())}),Ga(this,lD,()=>{gr(this,Jb).forEach(t=>t())}),au(this,Ri,e)}get status(){return gr(this,M1)}set status(e){au(this,M1,e),gr(this,aD).call(this)}get error(){return gr(this,D1)}set error(e){au(this,D1,e),gr(this,lD).call(this)}get messages(){return gr(this,Ri)}set messages(e){au(this,Ri,[...e]),gr(this,am).call(this)}};Ri=new WeakMap;M1=new WeakMap;D1=new WeakMap;Xb=new WeakMap;Qb=new WeakMap;Jb=new WeakMap;am=new WeakMap;aD=new WeakMap;lD=new WeakMap;var lm,DV=class extends Zlt{constructor({messages:e,...t}){const n=new tct(e);super({...t,state:n}),Ga(this,lm,void 0),this["~registerMessagesCallback"]=(r,s)=>gr(this,lm)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>gr(this,lm)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>gr(this,lm)["~registerErrorCallback"](r),au(this,lm,n)}};lm=new WeakMap;function cae({experimental_throttle:e,resume:t=!1,...n}={}){const r=w.useRef("chat"in n?n.chat:new DV(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new DV(n));const o="id"in n?n.id:null,i=w.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=w.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=w.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=w.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=w.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return w.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function nct(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function rct(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function sct(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function oct(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function uae(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:oct(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function dae(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function yE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function fae(e,t,n){const r=yE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>ZN(o)).filter(o=>o!==void 0).map(s)}function hae(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function ict(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function bm(e){return(e||[]).map(ict)}function mae(e){return bm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function j5(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function act(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...j5(s)}})}function lct(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...j5(t)}))}function pae(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function M_(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>pae(s,`${t}:${r}:${o}`)))}function cct(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function uct(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function dct(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(uct).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...j5(r)})),n=e.filter(cct).map((r,s)=>pae(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function fct({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=kD(e.id,t),s=t[xa],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>M_(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>M_(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>M_(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function gae(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>gae(t)).filter(Boolean)}:null}function bae(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==ID.trim()}function hct(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":bae(e)?"custom-python":"config"}function xae({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=yE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=y0({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=x0({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=dct(n==null?void 0:n.filters),m=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:m?h.dashboardFilterValues:act(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:lct(a==null?void 0:a[t.id]),interactionFilterValues:m?h.interactionFilterValues:fct({card:t,interactionStates:i,currentDashboardId:r.id})}}function mct({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=xae({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:bm(c.metricColumns),dimensions:mae(c),selectedEntities:hae(t)}}function pct({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function AV({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=yE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:BC(e.filters,n,r)}}function gct({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=yE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=fae(e,t.selectedSheetId,s),c=Gc(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>mct({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:pct({activeFilters:t.activeFilters})}}function bct({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var v,C;const c=fae(e,t.selectedSheetId,i).find(({sourceCard:S,visibleCard:N})=>S.id===n||N.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:m,inlineFilterValues:p,interactionFilterValues:g}=xae({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:b,targetValue:x}=Gne(h,d.type),y=hct(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:y,...(v=d.sql)!=null&&v.trim()?{sql:d.sql.trim()}:{},...bae(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:hae(d),metrics:bm(h.metricColumns),dimensions:mae(h),comparison:b!=="none"?{type:b,...x!==void 0?{targetValue:x}:{}}:null,cardFilters:gae(h.filters),effectiveDashboardFilters:m,activeInlineFilters:p,activeInteractionFilters:g,sortingOrGroupingSummary:{groupBy:bm(h.groupByColumns),pivotBy:bm(h.pivotByColumns),sortBy:bm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...y==="custom-sql"?["This card runs custom SQL."]:y==="custom-python"?["This card runs custom Python."]:[]]}}function bb(e,t,n){const r=e.getPropertyValue(t).trim();return r?`hsl(${r})`:n}function xct(){if(typeof document>"u")return{mode:"light",background:"hsl(0 0% 100%)",foreground:"hsl(240 10% 3.9%)",muted:"hsl(240 3.8% 46.1%)",border:"hsl(240 5.9% 90%)",accent:"hsl(240 5.9% 10%)"};const e=document.documentElement,t=window.getComputedStyle(e);return{mode:e.classList.contains("dark")?"dark":"light",background:bb(t,"--semaphor-background","hsl(0 0% 100%)"),foreground:bb(t,"--semaphor-foreground","hsl(240 10% 3.9%)"),muted:bb(t,"--semaphor-muted-foreground","hsl(240 3.8% 46.1%)"),border:bb(t,"--semaphor-border","hsl(240 5.9% 90%)"),accent:bb(t,"--semaphor-primary","hsl(240 5.9% 10%)")}}async function yct({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",os.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>dr(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=zK(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function vct({dynamicVisualMode:e="auto"}={}){var N;const{authToken:t,tokenProps:n}=it(),r=ps(),s=te(j=>j.dashboard.aiScopeTables),o=(N=ZS().data)==null?void 0:N.assistantProfileId,i=w.useRef(null),a=w.useRef(e);a.current=e;function c(){const j=Cs.getState(),k=te.getState(),_=BK({overrides:j.dashboardEntitySelectionOverrides,dashboardId:k.dashboard.id,draftScopeKey:k.dashboardAssistantDraftScopeKey});return WD(dTe({currentAIContext:j.currentAIContext,manualSelectedEntities:_.selectedEntities,hasManualOverride:_.hasManualOverride,dashboardAIContext:k.dashboard.aiContext,derivedSelectedSheetEntities:VK(k.dashboard,k.selectedSheetId)}))}function u(){const j=te.getState();return{aiContext:c(),dashboardViewState:AV({dashboard:j.dashboard,selectedSheetId:j.selectedSheetId,activeFilters:j.filterValues})}}const{sendMessage:d,messages:f,setMessages:h,regenerate:m,status:p,addToolResult:g,error:b,stop:x,clearError:y}=cae({transport:new N5({api:`${n.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${t==null?void 0:t.accessToken}`}),body:()=>{const j=Cs.getState();i.current||(i.current=u());const{aiContext:k,dashboardViewState:_}=i.current;return{assistantId:"dashboard-assistant",assistantProfileId:o,aiContext:k,dashboardViewState:_,dynamicVisualMode:a.current,dynamicVisualTheme:xct(),reasoningEffort:j.reasoningEffort,showReasoning:j.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:j,body:k})=>({body:{...k,messages:o7(j)}})}),onToolCall:v,sendAutomaticallyWhen:aae,onFinish({message:j,isAbort:k,isDisconnect:_,isError:E}){var T;j!=null&&j.id&&((T=i.current)!=null&&T.aiContext)&&Cs.getState().actions.setAssistantMessageContext(j.id,i.current.aiContext),console.log(k?"[Dashboard Assistant] Stream aborted by user":_?"[Dashboard Assistant] Stream disconnected (network error)":E?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),i.current=null},onError(j){var k;if(j.name==="AbortError"||(k=j.message)!=null&&k.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),i.current=null;return}console.error("[Dashboard Assistant] Stream error:",j),i.current=null}});async function v({toolCall:j}){var P,D;if(j.toolName==="getCurrentTableScope"){g({tool:j.toolName,toolCallId:j.toolCallId,output:{tables:uae(s||[])}});return}const k=te.getState().dashboard,_=te.getState().inlineFilterValuesMap,E=Vt.getState(),T=E.interactionStates,M=await yct({replacedCards:E.replacedCards,apiServiceUrl:n.apiServiceUrl,accessToken:(t==null?void 0:t.accessToken)||"",queryClient:r}),F=AV({dashboard:k,selectedSheetId:te.getState().selectedSheetId,activeFilters:te.getState().filterValues});if(j.toolName==="getDashboardSynopsis"){g({tool:j.toolName,toolCallId:j.toolCallId,output:gct({dashboard:k,viewState:F,interactionStates:T,inlineFilterValuesMap:_,replacedCards:M})});return}if(j.toolName==="getCardContext"){const L=((P=j.input)==null?void 0:P.cardId)||((D=j.args)==null?void 0:D.cardId)||"";g({tool:j.toolName,toolCallId:j.toolCallId,output:bct({dashboard:k,viewState:F,cardId:L,runtimeFilterValues:te.getState().filterValues,interactionStates:T,inlineFilterValuesMap:_,replacedCards:M})})}}const C=!["ready","error"].includes(p),S=dae(b);return{sendMessage:d,regenerate:m,isLoading:C,messages:f,setMessages:h,status:p,stop:x,errorMessage:S,clearError:y}}function yae(){var u;const{authToken:e,tokenProps:t}=it(),n=(u=ZS().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=Xt({queryKey:["assistant-profile",n],queryFn:()=>dr(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function vae({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(G7,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(ne,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function wct({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=w.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ac-n;if(c.length>u){Ge.error(`You can only attach ${ac} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=eie(c);if(f.forEach(({file:h,error:m})=>{Ge.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>m5(m)));e(h)}catch(h){console.error("Failed to process files:",h),Ge.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ac}),l.jsx(ne,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ac,title:n>=ac?`Maximum ${ac} files allowed`:"Attach files",children:l.jsx(yA,{className:"h-4 w-4 text-muted-foreground"})})]})}function Cct({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=w.useState(!1),a=w.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=w.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=w.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=w.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const m=ac-r;if(h.length>m){Ge.error(`You can only attach ${ac} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=eie(h);if(g.forEach(({file:b,error:x})=>{Ge.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>m5(x)));t(b),Ge.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),Ge.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:Q("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(_A,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ac-r," slot(s) available"]})]})})]})}function wae(e){return e.type==="dataset"&&e.label||e.name}function Sct(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function Nct({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsxs("div",{className:"mb-4 space-y-2",children:[l.jsxs(pe,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),l.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs(tt,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[l.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),wae(n),l.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:l.jsx(Tt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function jct(e){const{tokenProps:t}=it(),n=te(c=>c.authToken)||e;ze(c=>c.selectedConnectionId),ze(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=Xt({queryKey:["semantic-domains"],queryFn:()=>dr(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function Ect(e,t){const{tokenProps:n}=it(),r=te(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:c}=Xt({queryKey:["datasets",e],queryFn:()=>dr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:c,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:c,refetchDatasets:s}}function kct(e){var g,b;const{tokenProps:t}=it(),n=te(x=>x.authToken)||e,{connections:r}=ra(e),s=ze(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){var y;return!s||!x?!1:!!((y=o==null?void 0:o.capabilities)!=null&&y.path.includes("database"))}const{data:d,isPending:f,error:h,refetch:m}=Xt({queryKey:["databases",s],queryFn:()=>dr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:c}}function _ct(e){var g;const{tokenProps:t}=it(),n=te(b=>b.authToken)||e,{connections:r}=ra(e),s=ze(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ze(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,c=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){var b;return!(!s||!((b=i==null?void 0:i.capabilities)!=null&&b.path.includes("schema"))||!o)}const{data:d,isPending:f,error:h,refetch:m}=Xt({queryKey:["schemas",s,o],queryFn:()=>dr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:c}}function Cae(e){const{tokenProps:t}=it(),n=te(h=>h.authToken)||e,{connections:r}=ra(e),s=ze(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:c,error:u,refetch:d}=Xt({queryKey:["dataModels",s],queryFn:()=>dr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:c,error:u,dataModels:f||[],refetch:d}}function Tct(){var S,N,j;const e=ze(k=>k.card.dataSource);ze(k=>k.actions.updateDirectSource);const t=ze(k=>k.actions.updateDataSource),[n,r]=w.useState(""),{selectedConnection:s,error:o}=ra(),{databases:i,isPending:a,error:c,label:u}=kct(),{schemas:d,isPending:f,error:h,label:m}=_ct(),{error:p}=Cae(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=k=>{e&&t({...e,dbSelection:{database:k,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},C=k=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:k},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return l.jsxs(l.Fragment,{children:[(o||c||h||p)&&l.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[l.jsx("div",{className:"flex items-center",children:l.jsxs("div",{className:"text-sm text-red-800",children:[l.jsx("strong",{children:"Error loading data:"}),l.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&l.jsxs("li",{children:["Connections: ",o]}),c&&l.jsxs("li",{children:[u,": ",c.message]}),h&&l.jsxs("li",{children:[m,": ",h.message]}),p&&l.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),l.jsx(ne,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),l.jsxs("div",{className:"space-y-4",children:[b&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:u}),l.jsxs(xt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[a&&l.jsx(In,{className:"h-4 w-4 animate-spin"}),l.jsx(vt,{placeholder:c?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),l.jsx(gt,{children:i.map(k=>l.jsx(_e,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]}),((N=e==null?void 0:e.dbSelection)==null?void 0:N.database)&&g&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:m}),l.jsxs(xt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:C,disabled:f,children:[l.jsx(pt,{className:"w-full",children:l.jsxs("div",{className:"flex items-center gap-2",children:[f&&l.jsx(In,{className:"h-4 w-4 animate-spin"}),l.jsx(vt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),l.jsx(gt,{children:d.map(k=>l.jsx(_e,{className:"hover:bg-muted",value:k.id,children:k.name},k.id))})]})]})]})]})}function Ict(){const e=ze(c=>c.card.dataSource),t=ze(c=>c.actions.updateDataSource),[n,r]=w.useState(!1),s=c=>{if(!c||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(c).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=c=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==c);t({...e,selectedEntities:u})},i=c=>{if(c===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(c)/Math.log(u));return Number.parseFloat((c/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:"Upload Files"}),l.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:c=>{c.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:c=>{c.preventDefault(),r(!1),s(c.dataTransfer.files)},children:[l.jsx(_A,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),l.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:c=>s(c.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(ne,{variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("file-upload"))==null?void 0:c.click()},children:"Select Files"}),l.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(pe,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(c=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(Ma,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:c.originalName}),l.jsx("p",{className:"text-xs text-gray-500",children:c.file?i(c.file.size):""})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(c.id),children:l.jsx(Tt,{className:"h-3 w-3"})})]},c.id))})]})]})}function Mct(){const e=ze(f=>f.card.dataSource),t=ze(f=>f.actions.updateDataSource),[n,r]=w.useState(""),[s,o]=w.useState(""),[i,a]=w.useState("api"),c=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),l.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"Source Name"}),l.jsx(Pt,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"URL"}),l.jsx(Pt,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-xs text-gray-600",children:"Type"}),l.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[l.jsx("option",{value:"api",children:"API Endpoint"}),l.jsx("option",{value:"csv",children:"CSV File"}),l.jsx("option",{value:"json",children:"JSON File"})]})]}),l.jsxs(ne,{onClick:c,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[l.jsx(qr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs(pe,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>l.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(tN,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),l.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:l.jsx(Tt,{className:"h-3 w-3"})})]},f.id))})]})]})}function Dct(e,t){var y,v;const{tokenProps:n}=it(),r=te(C=>C.authToken)||t,{connections:s}=ra(t),o=ze(C=>{var S,N;return(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.connectionId}),i=ze(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.database}),a=ze(C=>{var S,N,j;return(j=(N=(S=C==null?void 0:C.card)==null?void 0:S.dataSource)==null?void 0:N.dbSelection)==null?void 0:j.schema}),c=s==null?void 0:s.find(C=>C.id===o),u=c==null?void 0:c.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){if(!o)return!1;const C=(u==null?void 0:u.path)||[];return!(C.includes("database")&&!i||C.includes("schema")&&!a)}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=Xt({queryKey:[e,o,i,a],queryFn:()=>dr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(C=>{var S;return{connectionId:c==null?void 0:c.id,connectionType:c==null?void 0:c.type,dialect:c==null?void 0:c.dialect,type:e,dbObjectType:(S=C==null?void 0:C.table_type)==null?void 0:S.toLowerCase(),id:C[`${e}_name`],database:i,schema:a,name:C[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function DS({title:e,message:t}){return l.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:l.jsxs("div",{className:"flex items-start gap-4",children:[l.jsx(Lc,{className:"h-6 w-6 flex-shrink-0"}),l.jsxs("div",{className:"flex-1",children:[l.jsx("h4",{className:"text-base font-semibold",children:e}),t&&l.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function Act({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=ra(),[i,a]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=_r(),{entities:p,isLoading:g,error:b}=Dct("table"),{dataModels:x,isPending:y,error:v}=Cae(),C=E=>{const T=s.find(F=>F.id===E);if(!T)return;const M=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:M,dbSelection:{database:"",schema:"",entityType:"table"}}),m(E)},S=E=>{var P,D;const T=n||[],M=T.some(L=>L.name===E.name&&L.type===E.type);let F;if(M)F=T.filter(L=>!(L.name===E.name&&L.type===E.type));else{const L={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((P=e.dbSelection)==null?void 0:P.database)||"",schema:((D=e.dbSelection)==null?void 0:D.schema)||"",name:E.name,dialect:E.dialect};F=[...T,L]}t==null||t(F)},N=E=>{const T=n||[],M=T.some(P=>P.type==="model"&&P.name===E.name);let F;M?F=T.filter(P=>!(P.type==="model"&&P.name===E.name)):F=[...T,E],t==null||t(F)},j=p.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),k=x.filter(E=>E.name.toLowerCase().includes(c.toLowerCase())),_=w.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const F=j.filter(P=>!E.some(D=>D.name===P.name&&D.type==="table")).map(P=>{var D,L;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:P.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((L=e.dbSelection)==null?void 0:L.schema)||"",name:P.name,dialect:P.dialect}});T=[...E,...F]}else if(d==="datamodels"){const M=k.filter(F=>!E.some(P=>P.name===F.name&&P.type==="model"));T=[...E,...M]}t(T)},[d,j,k,n,e,t]);return w.useEffect(()=>{r&&r(_)},[r,_]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"font-medium= text-sm",children:"Connection"}),l.jsxs(xt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:C,disabled:o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(vt,{placeholder:o?"Loading connections...":"Select connection..."})}),l.jsx(gt,{children:s.map(E=>l.jsx(_e,{className:"hover:bg-muted",value:E.id,children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(pl,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"truncate",children:E.name}),l.jsx(tt,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&l.jsxs(l.Fragment,{children:[e.connectionType==="upload"&&l.jsx(Ict,{}),e.connectionType==="url"&&l.jsx(Mct,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&l.jsxs(l.Fragment,{children:[l.jsx(Tct,{}),l.jsx("div",{className:"space-y-4",children:l.jsx("div",{className:"space-y-2",children:l.jsxs($s,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsxs(sn,{value:"tables",children:["Tables & Views (",j.length,")"]}),l.jsxs(sn,{value:"datamodels",children:["Data Models (",k.length,")"]})]}),l.jsxs(ur,{value:"tables",className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?l.jsx(DS,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const T=n.some(M=>M.name===E.name&&M.type==="table");return l.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[l.jsx(Qt,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:M=>M.stopPropagation(),disabled:g}),l.jsxs(pe,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&l.jsx(tt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&l.jsx(tt,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),l.jsxs(ur,{value:"datamodels",className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search data models...",value:c,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?l.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?l.jsx(DS,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):k.length===0?l.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):k.map(E=>{const T=n.some(M=>M.name===E.name&&M.type==="model");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>N(E),children:[l.jsx(Qt,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>N(E),onClick:M=>M.stopPropagation(),disabled:y}),l.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[l.jsx(pe,{className:"cursor-pointer",children:E.name}),l.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function Rct({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,domainAccess:s=_c.DEFAULT_SEMANTIC_DOMAIN_ACCESS,autoSelectedDomainId:o,onRegisterSelectAll:i}){var C;const[a,c]=w.useState(""),u=w.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);w.useEffect(()=>{o&&!(e!=null&&e.semanticDomainId)&&u(o)},[o,e==null?void 0:e.semanticDomainId,u]);const{semanticDomains:d,isPending:f,error:h}=jct(),m=d.filter(S=>{var N,j;switch(s.mode){case"all":return!0;case"none":return!1;case"include":return((N=s.domainIds)==null?void 0:N.includes(S.id))??!1;case"exclude":return!(((j=s.domainIds)==null?void 0:j.includes(S.id))??!1);default:return!0}}),{datasets:p,isPending:g,error:b}=Ect(e==null?void 0:e.semanticDomainId),x=S=>{const N=r||[],j=N.some(_=>_.id===S.id&&_.type==="dataset");let k;if(j)k=N.filter(_=>!(_.id===S.id&&_.type==="dataset"));else{const _={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};k=[...N,_]}n==null||n(k)},y=p.filter(S=>S.name.toLowerCase().includes(a.toLowerCase())),v=w.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],j=y.filter(_=>!S.some(E=>E.id===_.id&&E.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...S,...j];n(k)},[y,r,e==null?void 0:e.semanticDomainId,n]);return w.useEffect(()=>{i&&i(v)},[i,v]),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium",children:"Semantic Domain"}),l.jsxs(xt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:u,disabled:f||s.mode==="none"||s.mode==="include"&&!!o,children:[l.jsx(pt,{className:"w-full",children:l.jsx(vt,{placeholder:f?"Loading semantic domains...":s.mode==="none"?"No semantic domains available for this token":s.mode==="include"&&o?"Loading domain...":"Select semantic domain...",children:((C=m.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:C.label)||"Select semantic domain"})}),l.jsx(gt,{children:m.map(S=>l.jsx(_e,{className:"hover:bg-muted",value:S.id,children:l.jsxs("div",{className:"flex flex-col items-start",children:[l.jsx("span",{className:"font-medium",children:S.label}),l.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),h&&l.jsx(DS,{title:"Error loading semantic models",message:h.message})]}),(e==null?void 0:e.semanticDomainId)&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Hn,{placeholder:"Search datasets...",value:a,onChange:S=>c(S.target.value),className:"h-8 text-sm",disabled:g}),l.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):b?l.jsx(DS,{title:"Error loading datasets",message:b.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):y.length===0?l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:a?"No datasets match your search":"No datasets available"}):y.map(S=>{const N=r.some(j=>j.id===S.id&&j.type==="dataset");return l.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>x(S),children:[l.jsx(Qt,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>x(S),onClick:j=>j.stopPropagation(),disabled:g}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx(pe,{className:"cursor-pointer font-medium",children:S.label||S.name}),l.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function Pct(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function Fct({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!Pct(e,t,n):r}function Oct(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function E5({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var V,O;const{tokenProps:a}=it(),c=a.semanticDomainAccess||_c.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[u,d]=w.useState([]),[f,h]=w.useState(void 0),{updateDataSource:m}=_r(),p=te(I=>I.isVisualEditing),g=te(I=>I.dashboard.aiContext),{setAiContext:b}=Jt(),x=w.useRef(null),[y,v]=w.useState(!1),C=c.mode,S=C==="include"||C==="exclude",N=C!=="all",j=!S,k=r==="aiContext"&&S?"semanticDomain":n.mode,_=C==="include"&&(((V=c.domainIds)==null?void 0:V.length)||0)===1?(O=c.domainIds)==null?void 0:O[0]:void 0,E=w.useCallback(I=>{const W=I;m({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:W,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...W!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,m]),T=w.useCallback(I=>{m({...n,...I})},[n,m]),M=w.useCallback(I=>{if(r==="aiContext"){"semanticDomainId"in I&&h(I.semanticDomainId);return}T(I)},[r,T]),F=r==="aiContext"?f:n.semanticDomainId,P=r==="aiContext"?{...n,mode:k,semanticDomainId:f}:n;w.useEffect(()=>{if(!N||r==="aiContext"&&!e)return;if(S&&n.mode!=="semanticDomain"&&r==="dataSource"){E("semanticDomain");return}if(k!=="semanticDomain")return;const I=F,W=c.domainIds??[],X=r==="aiContext"?u:n.selectedEntities,Z=((X==null?void 0:X.length)??0)>0,$=((u==null?void 0:u.length)??0)>0;Fct({mode:C,currentDomainId:I,scopedDomainIds:W,hasSelectedEntities:Z})&&(r==="dataSource"?T({semanticDomainId:void 0,selectedEntities:[]}):h(void 0),$&&d([]))},[S,N,k,n.mode,F,n.selectedEntities,r,f,u,e,c.domainIds,C,T,E]),w.useEffect(()=>{_&&!F&&M({semanticDomainId:_})},[_,F,M]),w.useEffect(()=>{if(e){d(s||[]);const I=r==="aiContext"?Oct(s):void 0;h(n.semanticDomainId||I)}else x.current=null,v(!1)},[e,n==null?void 0:n.selectedEntities,r,m,s,n]);const D=I=>{const W=u.filter(X=>!yi(X,I));d(W)},L=()=>{d([])},z=w.useCallback(I=>{d(I)},[]),U=w.useCallback(()=>{x.current&&x.current()},[]),B=w.useCallback(I=>{x.current=I,v(!0)},[]);function R(){var I,W;if(r==="aiContext"){if(p&&m(n),i){const X={...g,selectedEntities:u,mode:u.length>0?"fixed":"auto"};b(X)}o==null||o(u),t(!1)}else if(r==="dataSource"){if(n.mode==="semanticDomain"){const X=(I=u==null?void 0:u[0])==null?void 0:I.connectionId,Z=(W=u==null?void 0:u[0])==null?void 0:W.connectionType;m({...n,connectionId:X,connectionType:Z,selectedEntities:u})}else m({...n,selectedEntities:u});t(!1)}}return l.jsx(Yr,{open:e,onOpenChange:t,children:l.jsx(Rr,{className:"flex max-w-2xl flex-col",children:l.jsxs("div",{children:[l.jsxs(Pr,{className:"flex-shrink-0",children:[l.jsx(Fr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),l.jsx(us,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),l.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:l.jsxs("div",{className:"space-y-4",children:[j&&l.jsx("div",{className:"space-y-2",children:l.jsx($s,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:E,className:"w-full",children:l.jsxs(js,{className:"grid w-full grid-cols-2",children:[l.jsx(sn,{value:"database",children:"Direct Source"}),l.jsx(sn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),k==="semanticDomain"&&l.jsx(Rct,{dataSource:P,onDataSourceUpdate:M,selectedEntities:u,onSelectionChange:z,domainAccess:c,autoSelectedDomainId:_,onRegisterSelectAll:B}),k==="database"&&j&&l.jsx(Act,{dataSource:n,onDataSourceUpdate:T,selectedEntities:u,onSelectionChange:z,onRegisterSelectAll:B})]})}),l.jsx(Nct,{selectedEntities:u,onDeselectEntity:D}),l.jsx(Ls,{className:"flex-shrink-0",children:l.jsx("div",{className:"flex w-full justify-between",children:l.jsxs("div",{className:"flex grow justify-end gap-2",children:[l.jsx(ne,{variant:"outline",onClick:U,disabled:!y,children:"Select All"}),l.jsx(ne,{variant:"outline",onClick:L,disabled:u.length===0,children:"Clear All"}),l.jsxs(ne,{variant:"outline",onClick:()=>t(!1),children:[l.jsx(Tt,{className:"mr-2 h-4 w-4"}),"Close"]}),l.jsxs(ne,{onClick:R,children:[l.jsx(es,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function AS(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(NA,{className:r});case"view":return l.jsx(Uu,{className:r});case"materialized view":return l.jsx(Hhe,{className:r});case"model":return l.jsx(rN,{className:r});case"file":return l.jsx(Ma,{className:r});case"dataset":return l.jsx(pl,{className:r});case"upload":return l.jsx(_A,{className:r});case"url":return l.jsx(eU,{className:r});default:return l.jsx(tN,{className:r})}}const cD=e=>e.name||e.name,Lct=e=>{const t=cD(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function $ct({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=w.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(wr,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const m="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsxs(tt,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[AS(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate text-xs",children:cD(f)}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(f),children:l.jsx(Tt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-w-xs",children:Lct(f)})]},m)}),d&&l.jsxs(yn,{open:o,onOpenChange:i,children:[l.jsx(vn,{asChild:!0,children:l.jsxs(tt,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(X7,{className:"h-3 w-3"}),l.jsxs("span",{className:"text-xs",children:[u.length," more"]}),l.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(u),children:l.jsx(Tt,{className:"h-3 w-3"})})]})}),l.jsx(Tn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:AS(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:cD(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(Tt,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Sae=A.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Zs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(vo.Input,{ref:n,className:Q("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Sae.displayName=vo.Input.displayName;const Xw=e=>e.label||(e==null?void 0:e.name),RV=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function zct({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=it(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=w.useState(""),[p,g]=w.useState(""),b=s.filter(N=>{if(!h)return!0;const j=Xw(N).toLowerCase(),k=RV(N).toLowerCase(),_=h.toLowerCase();return j.includes(_)||k.includes(_)});w.useEffect(()=>{e||(m(""),g(""))},[e]),w.useEffect(()=>{b.length>0&&!p&&g(Xw(b[0]))},[b,p]);const x=()=>{if(!p)return;const N=b.find(j=>Xw(j)===p);N&&(o.some(k=>"id"in N&&"id"in k?N.id===k.id:N.name===k.name&&N.connectionId===k.connectionId)||t(N),i(N),r())},y=N=>{(N.key==="Tab"||N.key==="Enter")&&(N.preventDefault(),x())};if(!e)return null;const v=N=>o.some(j=>"id"in N&&"id"in j?N.id===j.id:N.name===j.name&&N.connectionId===j.connectionId),C=o.length===s.length,S=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(gg,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Sae,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(qr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),a==null||a()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),c==null||c()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(Tt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(bg,{className:"min-h-60",children:[l.jsx(xg,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(ne,{onClick:N=>{N.preventDefault(),N.stopPropagation(),u==null||u()},onMouseDown:N=>{N.preventDefault(),N.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(qr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx(yg,{children:b.map((N,j)=>{const k=v(N),_="id"in N?N.id:`${N.connectionId}-${N.name}`,E=Xw(N);return l.jsxs(vg,{value:E,onSelect:()=>{k?n==null||n(N):t(N)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:Q("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:AS(N.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:E}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:RV(N)})]}),k&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(es,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}function uD({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:m="secondary",triggerLabel:p="Add entity",triggerIconOnly:g=!0,assistantType:b}){const[x,y]=w.useState(!1),[v,C]=w.useState(!1),S=o??x,N=o!==void 0,j=w.useRef(!1),_=ze(q=>q.card.dataSource)??pE,{selectedEntities:E,availableEntities:T,syncWithGlobalContext:M,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:D}=XN(b),L=e==="full"||e==="display",z=e==="full"||e==="trigger",U=w.useMemo(()=>g&&E.length>0?`Add entity (${E.length})`:p,[E.length,g,p]);w.useEffect(()=>{S&&!j.current&&s&&M(),j.current=S},[S,s,M]);const B=w.useCallback(q=>{N||y(q),i==null||i(q)},[N,i]),R=w.useCallback(q=>{const H=E.filter(K=>!yi(K,q));F(H),c==null||c(q),d==null||d(H)},[c,d,E,F]),V=w.useCallback(q=>{if(q.length===0)return;const H=E.filter(K=>!q.some(G=>yi(K,G)));F(H),u==null||u(q),d==null||d(H)},[u,d,E,F]),O=w.useCallback(q=>{const H=D(q)?E.filter(K=>!yi(K,q)):[...E,q];F(H),d==null||d(H)},[D,d,E,F]),I=w.useCallback(()=>{F(T),d==null||d(T)},[T,d,F]),W=w.useCallback(()=>{F([]),d==null||d([])},[d,F]),X=w.useCallback(q=>{b==="dashboard"?P():F(q),d==null||d(q)},[P,b,d,F]),Z=w.useCallback(q=>{const H=E.some(K=>yi(K,q))?E:[...E,q];F(H),a==null||a(q),d==null||d(H),B(!1)},[a,d,E,B,F]),$=L?l.jsx($ct,{className:Q(n?"contents":"space-y-2"),entities:E,availableEntities:T,onRemoveEntity:R,onRemoveEntities:V}):null,Y=z?l.jsxs(l.Fragment,{children:[l.jsxs(ns,{open:S,onOpenChange:B,children:[l.jsx(rs,{asChild:!0,children:l.jsxs(ne,{variant:m,size:"sm",className:Q(t?"h-7 gap-1.5 px-2 text-xs":"h-7 px-2",h),title:p,children:[l.jsx($he,{className:"h-4 w-4 text-muted-foreground"}),!g&&l.jsx("span",{children:U})]})}),l.jsx(ss,{className:Q("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:q=>q.preventDefault(),children:l.jsx(zct,{isOpen:!0,onSelect:O,onDeselect:O,onClose:()=>B(!1),availableEntities:T,selectedEntities:E,onTabComplete:Z,onSelectAll:I,onRemoveAll:W,onAddContext:()=>{B(!1),C(!0)}})})]}),l.jsx(E5,{incomingSelectedEntities:E,open:v,onOpenChange:C,dataSource:_,dialogMode:"aiContext",onSaveSelectedEntities:X,saveAsDashboardDefault:b==="dashboard"})]}):null;return l.jsx("div",{className:Q(n?"flex flex-wrap items-center gap-1":"",!n&&L?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[Y,$]}):l.jsxs(l.Fragment,{children:[$,Y]})})}const k5=w.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=w.useState(!1),h=w.useRef(null),{queueMessage:m}=zp(),{addFileAttachment:p,removeFileAttachment:g,clearFileAttachments:b}=KD(),x=GD(c);w.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const y=w.useCallback(()=>{const E=h.current;if(E){if(!e||e.length===0){E.style.height="10px";return}E.style.height="auto";const T=Math.min(Math.max(E.scrollHeight,10),200);E.style.height=`${T}px`}},[e]);w.useEffect(()=>{y()},[y]),w.useEffect(()=>{const E=setTimeout(()=>{y()},0);return()=>clearTimeout(E)},[y]);const v=()=>{const E=e.trim();!E&&x.length===0||(a!=="ready"?(m(c,E,x),t(""),b(c)):r({preventDefault:()=>{}}))},C=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),v()),E.key==="@"&&f(!0)},S=w.useCallback(E=>{const T=Wnt(E.nativeEvent);T.length>0&&(E.preventDefault(),T.forEach(async M=>{const F=await m5(M);p(c,F)}))},[p,c]),N=w.useCallback(E=>{E.forEach(T=>{p(c,T)})},[p,c]),j=w.useCallback(E=>{E.forEach(T=>{p(c,T)})},[p,c]),k=w.useCallback(E=>{g(c,E)},[g,c]),_=w.useCallback(E=>{const T=`@${E}`;e.includes(T)&&t(e.replace(T,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(Cct,{onFilesDropped:N,currentFileCount:x.length,disabled:s,className:"space-y-4",children:[l.jsx(uD,{mode:"display",assistantType:c,onEntityRemoved:E=>{const T="label"in E?E.label:E.name;_(T)},onEntitiesRemoved:E=>{let T=e;E.forEach(M=>{const F="label"in M?M.label:M.name;T=T.replace(`@${F}`,"")}),T!==e&&t(T.replace(/\s{2,}/g," ").trim())}}),x.length>0&&l.jsx(qnt,{files:x,onRemove:k,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-xl border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:S,onFocus:()=>{y(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pt-3 pb-1 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(uD,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:E=>{var M;const T="label"in E?E.label:E.name;t(`${e}@${T} `),(M=h.current)==null||M.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(wct,{onFilesSelected:j,disabled:s,currentFileCount:x.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(ne,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(nme,{className:"size-3.5"})}),!s&&l.jsx(ne,{disabled:!e.trim()&&x.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:v,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(CA,{className:"size-3.5"})})]})]})]})]})});k5.displayName="ChatInputWithContext";function Nae({assistantType:e,className:t}){const n=i7(e),{removeFromQueue:r}=zp();return n.length===0?null:l.jsxs("div",{className:Q("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(Bu,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(ne,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(Tt,{className:"h-3 w-3"})})]})},s.id))})]})}function jae({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=i7(e),{dequeueMessage:o}=zp();w.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Vct(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Bct(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Vct(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Eae(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!0),[d,f]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(0),b=w.useRef(!0),x=w.useRef(!0),y=w.useRef(!1),v=w.useRef(!1),C=w.useRef(0),S=w.useRef({count:0,signature:"none"}),N=w.useCallback(()=>{if(i.current)return i.current;const D=a.current;if(!D)return null;const L=D.closest("[data-radix-scroll-area-viewport]");if(L)return i.current=L,L;const z=D.parentElement;return z?(i.current=z,z):null},[]),j=w.useCallback(()=>{const D=N();return D?D.scrollHeight-D.scrollTop-D.clientHeight:0},[N]),k=w.useCallback(()=>j()<=n,[j,n]),_=w.useCallback(D=>{b.current!==D&&(b.current=D,u(D))},[]),E=w.useCallback(D=>{x.current!==D&&(x.current=D,f(D))},[]),T=w.useCallback(()=>{m(D=>D&&!1),g(D=>D===0?D:0)},[]),M=w.useCallback((D={})=>{const L=N();if(!L)return;const{force:z=!1,instant:U=!1}=D;if(!z&&y.current)return;const B=U||r==="auto"||r==="instant"?"auto":r;v.current=!0,B==="smooth"&&"scrollTo"in L?L.scrollTo({top:L.scrollHeight,behavior:"smooth"}):L.scrollTop=L.scrollHeight,C.current=L.scrollTop,y.current=!1,_(!0),E(!0),T(),requestAnimationFrame(()=>{v.current=!1})},[r,T,N,_,E]),F=w.useCallback(()=>{g(0),m(!1)},[]),P=w.useCallback(()=>{const D=N();if(!D)return;const L=C.current,z=D.scrollTop,U=z-L;C.current=z;const B=k();if(v.current){E(B),B&&(y.current=!1,_(!0));return}if(U<-1&&!B){y.current=!0,_(!1),E(!1);return}if(B){y.current=!1,_(!0),E(!0),T();return}E(!1),y.current&&_(!1)},[T,N,k,_,E]);return w.useEffect(()=>{const D=N();if(!e||e.length===0){S.current={count:0,signature:"none"},D&&(C.current=D.scrollTop),T();return}const L=e[e.length-1],z=Bct(L),U=S.current,B=e.length>U.count,R=z!==U.signature;S.current={count:e.length,signature:z};const V=o||s&&(L==null?void 0:L.role)==="assistant"&&R;if(!y.current){_(!0),D&&k()&&E(!0),(B||R||V)&&M({force:!1,instant:V});return}if(B){const O=e.length-U.count;O>0&&(m(!0),g(I=>I+O))}else R&&(m(!0),g(O=>O>0?O:1))},[T,o,s,N,k,e,M,_,E]),w.useEffect(()=>{M({force:!0,instant:!0})},[M]),w.useEffect(()=>{if(typeof ResizeObserver>"u")return;const D=a.current;if(!D)return;const L=new ResizeObserver(()=>{y.current||M({force:!1,instant:!0})});return L.observe(D),()=>{L.disconnect()}},[M]),w.useEffect(()=>()=>{v.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:p,scrollToBottom:M,handleScroll:P,resetNewMessageCount:F}}function kae(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=w.useState(r),a=w.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=w.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=w.useCallback(()=>{i(r)},[r]);return w.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const PV={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Uct(e,t){var r;if((r=PV[e])!=null&&r[t])return PV[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function _ae(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Uct(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Hct=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Wct({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(MD),[u,d]=w.useState(!1),[f,h]=w.useState("auto"),[m,p]=w.useState(!1),[g,b]=w.useState(!1),x=n??g,{isLocalDev:y,isConsoleMode:v}=Xp(),C=w.useRef(null);te(ie=>ie.dashboard.aiScopeTables),te(ie=>ie.isDashboardEditing);const S=te(ie=>ie.selectedSheetId),{setDataSource:N}=_r(),{addFrame:j,setSelectedFrameId:k,setIsDashboardEditing:_}=Jt(),{setReasoningEffort:E,setShowReasoning:T,clearAssistantMessageContexts:M}=GS(),{clearQueue:F}=zp(),{clearFileAttachments:P,getFileAttachments:D}=KD(),L=GD("dashboard"),z=ze(ie=>ie.card.dataSource),{assistantProfile:U}=yae(),B=te(ie=>ie.handleOpenAssistantProfile),{selectedEntities:R,applyDashboardDefaultEntities:V}=XN("dashboard"),{sendMessage:O,isLoading:I,messages:W,setMessages:X,status:Z,stop:$,errorMessage:Y,clearError:q}=vct({dynamicVisualMode:f}),H=w.useCallback(ie=>{r==null||r(ie),n===void 0&&b(ie)},[n,r]),K=w.useCallback(()=>{H(!x)},[x,H]);w.useEffect(()=>{if(!x)return;function ie(Te){Te.key==="Escape"&&H(!1)}return window.addEventListener("keydown",ie),()=>{window.removeEventListener("keydown",ie)}},[x,H]);const[G,J]=w.useState(""),re=ie=>{J(ie.target.value)};function me({sql:ie,cardTitle:Te,connectionId:Pe,cardType:Ie,python:Ze,cardConfig:ke,dataSource:We,customVisualPreferences:ct}){if(!S)return;const Be={id:kr(),title:Te||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ie==="horizontalBar"?"y":"x"}},type:Ie,sql:ie,python:Ze,dataSource:We,config:ke,connectionId:Pe,customCardPreferences:ct?{url:ct.url,componentName:ct.componentName,pluginChartType:ct.pluginChartType,settings:ct.settings,type:"component"}:void 0},Je={id:kr(),cards:[Be],activeCardId:Be.id};_(!0),j(S,Je,"end"),k(Je.id)}const ee=ie=>{ie.preventDefault();const Te=G.trim();if(!Te&&L.length===0)return;const Pe=[];Te&&Pe.push({type:"text",text:Te}),L.forEach(Ie=>{Ie.data&&Pe.push({type:"file",mediaType:Ie.type,filename:Ie.name,url:`data:${Ie.type};base64,${Ie.data}`})}),O({role:"user",parts:Pe}),J(""),P("dashboard"),he({force:!0})};w.useEffect(()=>{var ie;e&&((ie=C.current)==null||ie.focus())},[e]),jae({assistantType:"dashboard",status:Z,isLoading:I,sendMessage:O});const{hasActiveTools:xe,activeToolText:oe}=_ae(W),{visibleMessages:de,hasMoreMessages:Ce,totalMessageCount:je,loadMoreMessages:Ae,resetMessageWindow:ge}=kae(W,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Oe,contentRef:Ee,isAtBottom:le,hasNewMessages:se,newMessageCount:Se,scrollToBottom:he,handleScroll:fe,resetNewMessageCount:Fe}=Eae(de,{threshold:40,behavior:"smooth",isStreaming:I});function ye(ie){const Te={role:"user",parts:[{type:"text",text:ie.title+" "+ie.subtitle}]};O(Te)}function Ne(ie){O({role:"user",parts:[{type:"text",text:ie}]})}function $e(ie){O({role:"user",parts:[{type:"text",text:ie}]}),he({force:!0})}const Re=w.useCallback(async()=>{const ie=JSON.stringify(W??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ie),Ge.success("Conversation copied")}catch(Te){console.error("Failed to copy conversation",Te),Ge.error("Unable to copy conversation")}},[W]),Ue=(G==null?void 0:G.length)===0&&(W==null?void 0:W.filter(ie=>ie.role==="user").length)===0;function He(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Ye(){return l.jsxs(ud,{children:[l.jsx(dd,{asChild:!0,children:l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(vh,{className:"size-3.5"})})}),l.jsxs(Uc,{align:"end",children:[l.jsx(kf,{children:"Options"}),l.jsx(Wu,{}),l.jsx(lu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(lu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(lu,{checked:u,onCheckedChange:d,children:"System Message"}),(y||v)&&l.jsxs(l.Fragment,{children:[l.jsx(Wu,{}),l.jsx(kf,{children:"Dynamic Visuals"}),l.jsx(lu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(lu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(lu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const et=l.jsxs("div",{"data-role":"dashboard-assistant",className:Q("flex h-full grow flex-col justify-between break-words px-6 py-4",x&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[He(),B&&l.jsx(ne,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:B,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[v&&Ye(),a&&l.jsx(ne,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Re,children:"Copy Conversation"}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:x?"Exit Fullscreen":"Expand",onClick:K,children:x?l.jsx(xA,{className:"size-4"}):l.jsx(sN,{className:"size-4"})}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const ie=W.filter(Te=>Te.role==="assistant").map(Te=>Te.id).filter(Te=>!!Te);X([]),F("dashboard"),q(),M(ie),ge()},children:l.jsx(iN,{className:"size-4"})}),l.jsx(Au,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(Tt,{className:"size-4"})})]})]}),l.jsxs(Ba,{"data-role":"dashboard-assistant-scroll-area",ref:Oe,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:fe,children:[l.jsxs("div",{ref:Ee,className:"min-w-0 space-y-3 pb-4",children:[Ce&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(ne,{variant:"outline",size:"sm",onClick:Ae,className:"text-xs",children:["Load ",Math.min(5,je-de.length)," ","more messages (",je-de.length," ","hidden)"]})}),l.jsx(nie,{showTools:a,showSystemMessage:u,messages:de,onAddToDashboard:me,onQuickReply:$e,disableQuickReplies:I}),l.jsx(tie,{status:Z,errorMessage:Y,activeToolText:I&&xe?oe:void 0})]}),l.jsx(Ra,{orientation:"horizontal"})]}),e&&!le&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(ne,{onClick:()=>{he({force:!0}),Fe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(vr,{className:"h-4 w-4"}),se&&Se>0&&l.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:Se>9?"9+":Se})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&Ue&&l.jsx(rie,{onClick:ye,placeholders:Hct}),l.jsx("div",{children:Ue&&U&&l.jsx(vae,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:Ne})}),l.jsx(Nae,{assistantType:"dashboard",className:"mb-3"}),l.jsx(k5,{ref:C,setInput:J,stop:$,input:G,handleInputChange:re,handleSubmit:ie=>{ee(ie),he({force:!0})},isLoading:I,status:Z,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(E5,{incomingSelectedEntities:R,open:m,onOpenChange:p,dataSource:z||pE,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ie=>V()})]});return x&&s?yr.createPortal(l.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:l.jsx("div",{className:"flex h-full w-full",children:et})}),s):et}function qct(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Jt(),o=te(d=>d.dashboard.sheets),a=te(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=te(d=>d.isDashboardEditing),u=te(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),Ge.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=fne(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),Ge.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,c,u,t])}function Yct(e,t){switch(e.interactionMode){case"drillToDetail":Gct(e,t);break;case"drillThrough":Kct(e,t);break;case"drillToURL":Zct(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Gct(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Kct(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Zct(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Xct({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Yr,{open:e,onOpenChange:t,children:l.jsxs(Rr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Pr,{children:[l.jsx(Fr,{children:i||"Insight Detail"}),l.jsx(us,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(nre,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(cre,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function Qct(){const e=Vt(C=>C.interactionStates),t=Vt(C=>C.setInteractionState),n=Vt(C=>C.clearLastInteractionEvent),r=Vt(C=>C.replaceCardWithInsight),s=Vt(C=>C.setPendingDrillThrough),o=Vt(C=>C.pendingDrillThrough),i=Vt(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=Jt(),{selectDashboard:u}=Bp(),d=te(C=>C.dashboard),f=te(C=>C.filterValues),{data:h,isLoading:m}=yW((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=w.useState({open:!1,insightId:""}),b=ure(p.insightId,{enabled:p.open&&!!p.insightId}),x=w.useRef(new Set),y=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:S,contextMode:N})=>{g({open:!0,insightId:C,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:N})},replaceCardContent:({cardId:C,insightId:S,filters:N,contextMode:j})=>{r(C,S,N,j)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k})=>{const E={sourceCardId:xa,interactionMode:"clickFilter",filterGroups:[{filters:C}]},T={...Ui(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:N,sourceDashboardTitle:j,targetDashboardId:k};t(xa,T)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([C,S])=>{if(S!=null&&S.lastInteractionEvent){const N=S.lastInteractionEvent,j=`${C}-${N.interactionMode}-${N.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{Yct(N,y)}catch(k){console.error("Error executing interaction event:",k)}finally{n(C),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),w.useEffect(()=>{if(!(!o||!h||m))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,c,i]);const v=()=>{g({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Xct,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[l.jsx(In,{className:"h-8 w-8 animate-spin text-primary"}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Jct(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=eut(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function eut(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function tut(e){return e?`Back to ${e}`:"Back"}function nut(){var x,y,v,C,S;const e=Vt(N=>N.interactionStates[xa]),t=te(N=>N.actions.goBackFromDrill),n=te(N=>N.actions.clearDrillContext),{selectDashboard:r}=Bp(),[s,o]=w.useState({x:16,y:16}),[i,a]=w.useState(!1),c=w.useRef({x:0,y:0});w.useEffect(()=>{if(!i)return;const N=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",N),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",N),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(N){console.error("[DrillBack] Error during back navigation:",N)}},p=()=>{n()},g=N=>{N.target.closest("button")||(a(!0),c.current={x:N.clientX-s.x,y:N.clientY-s.y})};Jct(f);const b=tut(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((N,j)=>{const k=N.field.label||N.field.name,_=String(N.value);return l.jsxs(tt,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",_]},j)})})]}),l.jsx(ne,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Tt,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(ne,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(B7,{className:"mr-2 h-4 w-4"}),b]})})]})})}function rut(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Tae(){var je,Ae;const{showAssistant:e,tokenProps:t}=it(),n=rut((je=t.config)==null?void 0:je.showDashboardAssistant,e),{preferences:r,isConsoleMode:s}=Xp(),o=((Ae=r==null?void 0:r.cardDisplay)==null?void 0:Ae.mode)==="print",i=w.useRef(null),a=w.useRef(null),[c,u]=w.useState(!1),{handleDragStart:d,isDraggingRef:f,getStyle:h,getPositionClasses:m}=FGe({initialPosition:"bottom-right"}),p=Af(ge=>ge.setFullscreen),g=Af(ge=>ge.setPanelOpen),b=Af(ge=>ge.setContainer),x=aQ("dashboard"),y=lQ(),v=cQ("dashboard"),C=x.isOpen,S=y==="dashboard",N=te(ge=>ge.isVisualEditing),j=te(ge=>ge.themeStyle),k=te(ge=>{var Oe;return(Oe=ge.dashboard)==null?void 0:Oe.sheets}),_=te(ge=>ge.showFilters),E=te(ge=>ge.isDashboardEditing),T=te(ge=>ge.selectedSheetId),M=te(ge=>{var Oe,Ee;return((Ee=(Oe=ge.dashboard)==null?void 0:Oe.summary)==null?void 0:Ee.position)||"top"}),F=te(ge=>{var Oe;return(Oe=ge.dashboard)==null?void 0:Oe.id}),P=te(ge=>ge.isDashboardPanelOpen),D=te(ge=>ge.actions.setIsDashboardPanelOpen),L=j==null?void 0:j.controlInputRadius,{getDefaultSheetId:z,setDefaultSheetId:U,clearDefaultSheetId:B}=O7(F),[R,V]=w.useState(null);vN(os.DASHBOARD);const{setSelectedSheetId:O,setSheetTitle:I,addSheet:W,setSheets:X}=Jt();qct(a);const{setActiveAssistantType:Z}=GS();w.useEffect(()=>{if(F){const ge=z();V(ge)}},[F,z]),w.useEffect(()=>{C?Z("dashboard"):y==="dashboard"&&p(null)},[C,Z,y,p]),w.useEffect(()=>{var ge;C||(ge=i.current)==null||ge.resize(0)},[C]);function $(ge){var Oe,Ee;ge?((Oe=i.current)==null||Oe.resize(40),g("dashboard",!0),p("dashboard"),Z("dashboard")):(g("dashboard",!1),p(null),(Ee=i.current)==null||Ee.resize(0),Z(null))}function Y(){const ge={id:kr(),title:"New Sheet"};W(ge),O(ge.id)}function q(ge,Oe){if(!F)return;R===ge?(B(),V(null),Ge.success("Default sheet cleared")):(U(ge),V(ge),Ge.success(`"${Oe}" set as default sheet`))}function H(ge){var Oe;ge<1?(g("dashboard",!1),p(null),Z(null),(Oe=i.current)==null||Oe.resize(0)):(C||g("dashboard",!0),Z("dashboard"))}function K(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const G=(ge,Oe)=>{ge.dataTransfer.setData("tabIndex",Oe.toString())},J=ge=>{ge.preventDefault()},re=(ge,Oe)=>{const Ee=ge.dataTransfer.getData("tabIndex");if(Ee===Oe.toString())return;const le=Array.from(k||[]),[se]=le.splice(parseInt(Ee),1);le.splice(Oe,0,se),X(le)},me=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,ee=n===!0&&!o&&!C&&!N&&!_;function xe(){if(k&&k.length>1||E)return l.jsxs(js,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[s&&me&&!P&&l.jsx(ne,{style:{borderRadius:L},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!P)},className:"h-9 shrink-0 px-3",children:l.jsx(rU,{className:"h-4 w-4"})}),k==null?void 0:k.map((ge,Oe)=>{const Ee=T===ge.id,le=R===ge.id;return l.jsxs(sn,{draggable:!0,onDragStart:se=>G(se,Oe),onDragOver:J,onDrop:se=>re(se,Oe),style:{borderRadius:L},onClick:()=>O(ge.id),className:"flex h-9 shrink-0 items-center gap-1 border border-border/70 bg-background/70 px-3 py-1 text-muted-foreground transition-colors hover:text-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none data-[state=active]:shadow-[inset_0_-2px_0_0_hsl(var(--foreground))]",value:ge.id,children:[l.jsx(oS,{enabled:E&&Ee,text:ge.title,onSave:se=>I(ge.id,se),children:ge.title},ge.id),!E&&Ee&&l.jsx("div",{title:le?"Clear default sheet":"Set as default sheet",children:l.jsx(SA,{className:Q("ml-1 size-3 cursor-pointer transition-all",le?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),q(ge.id,ge.title||"Sheet")}})}),E&&Ee&&k.length>1&&l.jsx(Tt,{className:"ml-1 size-3",onClick:()=>u(!0)})]},ge.id)}),E&&l.jsx(ne,{style:{borderRadius:L},variant:"outline","aria-label":"Add sheet",className:"h-9 shrink-0 border-border/70 bg-background/70 px-3 text-muted-foreground hover:bg-background/80 hover:text-foreground",onClick:Y,children:l.jsx(qr,{className:"size-4"})})]})}function oe(){return l.jsx("div",{ref:a,style:{},className:"grow",children:k==null?void 0:k.map(ge=>l.jsx(ur,{style:{backgroundColor:K()},className:Q("mt-0",{}),value:ge.id,children:l.jsx(iGe,{sheet:ge})},ge.id))})}function de(){var ge;return l.jsxs($s,{"data-role":"dashboard-tabs-container",className:Q("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:Oe=>{O(Oe)},value:T||((ge=k==null?void 0:k[0])==null?void 0:ge.id),children:[xe(),M==="top"&&l.jsx(_M,{}),l.jsx(Ba,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:oe()}),M==="bottom"&&l.jsx(_M,{}),l.jsx(OGe,{open:c,setOpen:u})]})}const Ce=w.useCallback(ge=>{b("dashboard",ge)},[b]);return k?l.jsxs(l.Fragment,{children:[l.jsx(Qct,{}),l.jsx(nut,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Lse,{className:Q("flex-1 basis-0 overflow-y-auto transition-opacity",S&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx($M,{children:de()}),n===!0&&l.jsxs(l.Fragment,{children:[l.jsx(PGe,{open:C,onTabClick:$,withHandle:!0,disabled:!C}),l.jsx($M,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:H,defaultSize:C?40:0,ref:i,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Wct,{open:C,setOpen:$,isFullscreen:S,onFullscreenChange:ge=>p(ge?"dashboard":null),fullscreenContainer:v})})})]})]}),l.jsx("div",{ref:Ce,className:Q("absolute inset-0",!S&&"pointer-events-none")}),ee&&l.jsx("div",{className:Q("absolute z-50 transition-all duration-300 ease-in-out",m().horizontal,m().vertical),style:h(),children:l.jsx(ne,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{f.current||$(!0)},onMouseDown:d,onTouchStart:d,title:"Open Assistant (drag to move)",children:l.jsx(Xhe,{className:"h-5 w-5"})})})]})]}):null}function _5({children:e}){return l.jsx(ta,{style:{height:"100%",width:"100%"},children:l.jsx(qfe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(wr,{delayDuration:0,children:e})})})}function Iae({children:e,preferences:t}){const{currentUser:n}=Vo(),r=w.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(QH.Provider,{value:r,children:l.jsx(EO,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function sut(e=2e3,t=500){const n=whe(),[r,s]=w.useState(!1),[o,i]=w.useState(!1),a=w.useRef(null);return w.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),w.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function T5({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=sut(e,t);return w.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function Mae(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Fa,{FallbackComponent:zj,children:l.jsxs(sA,{dashboardProps:e,children:[l.jsx(T5,{componentType:"dashboard",componentId:e.id}),l.jsx(_5,{children:l.jsx(Iae,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(TP,{...e,type:"dashboard",children:l.jsx(Tae,{})})})})})]})})}function out(e){return!!e.expression}function iut(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function aut(e){const t=iut(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function lut(e){return e.fieldScope==="domain"||e.entityName===Ao||e.qualifiedEntityName===Ao}function cut(e){return e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Ei||aut(e.id)}function RS(e){return out(e)?lut(e)?"domain_calculated":cut(e)?"user_calculated":"inline_expression":"none"}function FV(e,t){return e.map(n=>({...n,fieldScope:t}))}function uut(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function OV(e){if(Eh(e)||KN(e))return e.expression}function I5(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=LO(),i=ze(g=>g.frame.calculatedFields),a=ze(g=>g.card.config),c=w.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=w.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=w.useMemo(()=>i!=null&&i.length?FV(i,"dashboard"):[],[i]),f=w.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=w.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(v=>v.role==="metric"&&RS(v)==="user_calculated"),b=((a==null?void 0:a.groupByColumns)||[]).filter(v=>v.role==="groupby"&&RS(v)==="user_calculated"),y=uut([...g,...b]).filter(v=>{const C=`${v.name}-${v.role||"unknown"}`,S=f.get(C);if(!S)return!0;const N=OV(v),j=OV(S);return N&&j?N!==j:!0});return FV(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=w.useMemo(()=>[...c,...d,...h,...u],[h,u,d,c]),p=w.useMemo(()=>t.filter(g=>g.entityId!==qB),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:c,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function M5(e){const{tokenProps:t,authToken:n}=it(),r=t==null?void 0:t.apiServiceUrl;return Xt({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return dr(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function Dae(e,t,n){if(t==="source")return{isValid:!0};const r=Nn(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Aae(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function dut(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const fut=new Set(["COUNT","DISTINCT"]),hut=new Set(["running_total","moving_average","previous_period_delta"]);function mut(e){return Nn(e.dataType||"")==="number"?!0:e.aggregate?fut.has(e.aggregate.toUpperCase()):!1}function put(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function D5(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Rae({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!mut(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||D5(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:hut.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function gut(e){return e.find(t=>Nn(t.dataType||"")==="date")}function but(e){return e}function kx({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||D5(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function xut({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=gut(n.groupByColumns||[]))==null?void 0:i.id),o=kx({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const yut=new Set(["table","aggregateTable","pivotTable","detailTable"]);function vut(e){return e.alias||e.label||e.name}function Pae(e,t,n){var a,c,u;if(!e)return null;const r=Mi(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(yut.has(e.type)){const d=c7(r),f=vut(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=Ys();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=Nfe(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Fae=e=>{var X;const t=(X=e==null?void 0:e.dataSource)==null?void 0:X.semanticDomainId,{data:n}=M5(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=_r(),m=ze(Z=>Z.card.type),p=e==null?void 0:e.id,g=(Z,$)=>{if(Z.id)return Z.id;const Y=Z.qualifiedEntityName||Z.entityName||$;return`${$}-${Y}-${Z.name}`},b=w.useCallback(Z=>{if(!(e!=null&&e.config))return[];switch(Z){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:g($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:g($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:g($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:g($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return dut(e.config.detailColumns,$=>g($,"detailColumns"));case"source":return[];default:return[]}},[e]),x=w.useCallback((Z,$)=>{if(p)switch(Z){case"groupBy":{r(p,{groupByColumns:$});break}case"metrics":{r(p,{metricColumns:$});break}case"pivotBy":{r(p,{pivotByColumns:$});break}case"sortBy":{r(p,{sortByColumns:$});break}case"detailColumns":{r(p,{detailColumns:$});break}}},[p,r]),y=w.useCallback((Z,$,Y)=>{if(!p)return;const q=b(Z),H=q[$];if(H)switch(Z){case"groupBy":s(p,H.id,{label:Y});break;case"metrics":o(p,H.id,{label:Y});break;case"pivotBy":i(p,H.id,{label:Y});break;case"sortBy":a(p,H.id,{label:Y});break;case"detailColumns":{const K=q.map((G,J)=>J===$?{...G,label:Y}:G);r(p,{detailColumns:K});break}}},[p,b,s,o,i,a,r]),v=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{aggregate:$,label:RK(q.name,$)})},[p,b,o]),C=w.useCallback((Z,$,Y,q="groupBy")=>{if(!p)return;const H=b(q),K=H[Z];if(!K)return;const G={dateFormat:$,customFormat:$==="custom"&&Y?Y:void 0};if(q==="detailColumns"){const J=H.map((re,me)=>me===Z?{...re,...G}:re);r(p,{detailColumns:J});return}s(p,K.id,G)},[p,b,r,s]),S=w.useCallback((Z,$)=>{if(!p)return;const q=b("groupBy")[Z];q&&s(p,q.id,{granularity:$})},[p,b,s]),N=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{aliasTemplate:$})},[p,b,o]),j=w.useCallback((Z,$)=>{if(console.log("handleValueAliasesChange",Z,$),!p)return;console.log("handleValueAliasesChange",Z,$);const q=b("metrics")[Z];q&&(console.log("handleValueAliasesChange",$),o(p,q.id,{valueAliases:$}))},[p,b,o]),k=w.useCallback((Z,$)=>{var H,K;if(!p)return;const q=b("metrics")[Z];q&&(o(p,q.id,{format:$}),m==="kpi"&&((K=(H=e==null?void 0:e.preferences)==null?void 0:H.kpiVisualOptions)!=null&&K.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,p,m,b,h,o]),_=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=$!=="none"&&((K=q.parameters)==null?void 0:K.windowTransform);o(p,q.id,{comparisonType:$,...$!=="target"?{targetValue:void 0}:{},...H?{parameters:{...q.parameters||{},windowTransform:void 0}}:{}})},[p,b,o]),E=w.useCallback((Z,$)=>{var me,ee,xe;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;if($==="none"){o(p,q.id,{parameters:{...q.parameters||{},windowTransform:void 0}});return}const H=Rae({cardType:m,cardConfig:e.config,metric:q,transformMode:$});if(!H.supported){Ge.error(H.reason||"Metric transform is not supported here.");return}const K=new Set((e.config.groupByColumns||[]).map(oe=>oe.id)),G=(xe=(ee=(me=q.parameters)==null?void 0:me.windowTransform)==null?void 0:ee.orderBy)==null?void 0:xe.fieldId,J=G&&K.has(G)?G:void 0,re=xut({transformMode:$,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:J});o(p,q.id,{comparisonType:"none",targetValue:void 0,parameters:{...q.parameters||{},windowTransform:re}})},[e,p,m,b,o]),T=w.useCallback((Z,$)=>{var re,me;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(re=q.parameters)==null?void 0:re.windowTransform;if(!H||!["running_total","moving_average","previous_period_delta"].includes(H.function))return;const K=kx({cardType:m,cardConfig:e.config,orderByFieldId:$}),J=(H.partitionByFieldIds||K).filter(ee=>ee!==$);o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,orderBy:{fieldId:$,direction:((me=H.orderBy)==null?void 0:me.direction)||"asc"},partitionByFieldIds:J}}})},[e,p,m,b,o]),M=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||!["running_total","moving_average","previous_period_delta"].includes(H.function)||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,orderBy:H.orderBy?{...H.orderBy,direction:$}:H.orderBy}}})},[p,b,o]),F=w.useCallback((Z,$)=>{var J,re;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(J=q.parameters)==null?void 0:J.windowTransform;if(!H)return;const K=kx({cardType:m,cardConfig:e.config,orderByFieldId:(re=H.orderBy)==null?void 0:re.fieldId}),G=new Set(H.partitionByFieldIds||K);G.has($)?G.delete($):G.add($),o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,partitionByFieldIds:Array.from(G)}}})},[e,p,m,b,o]),P=w.useCallback((Z,$)=>{var re,me;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(re=q.parameters)==null?void 0:re.windowTransform;if(!H||H.function!=="moving_average")return;const K=Math.max(1,Math.floor($||1)),G=((me=H.movingAverage)==null?void 0:me.minPeriods)||1,J=Math.min(G,K);o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,movingAverage:{windowSize:K,minPeriods:J}}}})},[p,b,o]),D=w.useCallback((Z,$)=>{var J,re;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(J=q.parameters)==null?void 0:J.windowTransform;if(!H||H.function!=="moving_average")return;const K=((re=H.movingAverage)==null?void 0:re.windowSize)||7,G=Math.max(1,Math.min(Math.floor($||1),K));o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,movingAverage:{windowSize:K,minPeriods:G}}}})},[p,b,o]),L=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||H.function!=="previous_period_delta"||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,previousPeriodDelta:{mode:$}}}})},[p,b,o]),z=w.useCallback((Z,$)=>{var G;if(!p||!(e!=null&&e.config))return;const q=b("metrics")[Z];if(!q)return;const H=(G=q.parameters)==null?void 0:G.windowTransform;if(!H||H.function!=="percent_of_total")return;const K=$==="grand_total"?[]:(H.partitionByFieldIds||[]).length>0?H.partitionByFieldIds||[]:kx({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,partitionByFieldIds:K,percentOfTotal:{...H.percentOfTotal||{},scope:$}}}})},[e,p,m,b,o]),U=w.useCallback((Z,$)=>{var K;if(!p)return;const q=b("metrics")[Z];if(!q)return;const H=(K=q.parameters)==null?void 0:K.windowTransform;!H||H.function!=="percent_of_total"||o(p,q.id,{parameters:{...q.parameters||{},windowTransform:{...H,percentOfTotal:{...H.percentOfTotal||{},output:$}}}})},[p,b,o]),B=w.useCallback(Z=>{p&&r(p,{showTrendline:Z})},[p,r]),R=w.useCallback(Z=>{p&&r(p,{trendlineWindow:Z})},[p,r]),V=w.useCallback(Z=>{p&&r(p,{trendlineGranularity:Z})},[p,r]),O=w.useCallback((Z,$)=>{if(!p)return;const q=b("metrics")[Z];q&&o(p,q.id,{targetValue:$})},[p,b,o]),I=w.useCallback(async Z=>{var re;if(!p)return;const $=[...b("groupBy"),...b("pivotBy"),...b("metrics"),...b("sortBy"),...b("detailColumns")],Y=Z,q=K_e(Y,$,{joinPlan:(re=e==null?void 0:e.config)==null?void 0:re.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!q.isValid){q.showError&&TK();return}const H=sTe(Y,$,m);if(!H){Ge.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const K=Dae(Y,H,m);if(!K.isValid){Ge.error("Invalid Field Type",{description:K.reason,position:"top-center",duration:3e3});return}const G=b(H);if(IK(Y,G))return;const J=PK(Y,H,G);if(J){const me=[...G,J];if(x(H,me),H==="metrics"){const ee=Pae(e,J,e==null?void 0:e.preferences);ee&&h(ee),Aae(m,e==null?void 0:e.config,r,p,me)}}},[p,e,b,x,t,n,m,r,h]),W=w.useCallback((Z,$)=>{if(!p)return;const q=b(Z)[$];if(q){if(Z!=="sortBy"){const H=b("sortBy"),K=H.filter(G=>!(G.name===q.name&&G.qualifiedEntityName===q.qualifiedEntityName));K.length!==H.length&&r(p,{sortByColumns:K})}switch(Z){case"groupBy":c(p,q.id);break;case"metrics":u(p,q.id);break;case"pivotBy":d(p,q.id);break;case"sortBy":f(p,q.id);break;case"detailColumns":{r(p,{detailColumns:(b("detailColumns")||[]).filter((H,K)=>K!==$)});break}}}},[p,b,c,u,d,f,r]);return{getFieldsForContainer:b,setFieldsForContainer:x,updateLabel:y,handleAggregationChange:v,handleDateFormatChange:C,handleGranularityChange:S,handleAliasTemplateChange:N,handleValueAliasesChange:j,handleMetricFormatChange:k,removeField:W,handleFieldClick:I,handleMetricComparisonChange:_,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:M,handleMetricWindowPartitionToggle:F,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:D,handleMetricPreviousPeriodDeltaModeChange:L,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:B,handleKpiTrendlineWindowChange:R,handleKpiTrendlineGranularityChange:V,handleMetricTargetValueChange:O,cardType:m}};function vE(e,t){var ye,Ne,$e,Re,Ue,He,Ye,et;const{tokenProps:n}=it(),r=ps(),s=it().authToken||e,o=ze(ie=>ie.selectedConnectionId),i=ze(ie=>ie.card),{queryKey:a}=pve(i),c=ze(ie=>ie.selectedDatamodelId),u=ze(ie=>ie.isDevMode),d=ze(ie=>ie.selectedDatabaseName),f=ze(ie=>ie.selectedSchemaName),h=ze(ie=>ie.selectedTableName),m=ze(ie=>ie.actions.setSelectedConnectionId),p=ze(ie=>ie.actions.setSelectedDatamodelId),g=ze(ie=>ie.actions.setSelectedDatabaseName),b=ze(ie=>ie.actions.setSelectedSchemaName),x=ze(ie=>ie.actions.setSelectedTableName);ze(ie=>ie.actions.setCardSql);const{setQueryConfig:y}=_r();function v(ie){var ke;if(!o||!ie)return!1;const Te=((ke=_==null?void 0:_.capabilities)==null?void 0:ke.path)||[],Pe=Te.includes("database"),Ie=Te.includes("schema");return!(!Te.includes("table")||Pe&&(!d||d==="NA")||Ie&&!f)}function C(ie){var Te;return!o||!ie?!1:!!((Te=_==null?void 0:_.capabilities)!=null&&Te.path.includes("database"))}const{refetchConnections:S,connectionsData:N,isConnectionsLoading:j,isConnectionsError:k,selectedConnection:_}=ra(e),{refetch:E,data:T,isLoading:M,isError:F}=Xt({queryKey:["models",o],queryFn:()=>dr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=_==null?void 0:_.type,D=((ye=_==null?void 0:_.capabilities)==null?void 0:ye.path.includes("schema"))??!1,L=((Ne=_==null?void 0:_.capabilities)==null?void 0:Ne.path.length)===1&&(($e=_==null?void 0:_.capabilities)==null?void 0:$e.path[0])==="table",z=L,{data:U,isLoading:B,isFetching:R,isError:V,refetch:O}=Xt({queryKey:["databases",o],queryFn:()=>dr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:I,isLoading:W,isFetching:X,isError:Z,refetch:$}=Xt({queryKey:["schemas",o,d],queryFn:()=>dr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&D&&d!=="NA"}),{data:Y,isLoading:q,isFetching:H,isError:K,refetch:G}=Xt({queryKey:["tables",o,d,f],queryFn:()=>dr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(P)}),{columns:J,isColumnsLoading:re,isColumnsFetching:me,isColumnsError:ee,refetchColumns:xe}=OK(e);w.useEffect(()=>{L&&(g(""),b(""),p(""),P==="API"&&x("api"))},[P,x,g,b,p,L]);const oe=(_==null?void 0:_.type)==="API"?(Re=_==null?void 0:_.type)==null?void 0:Re.toLowerCase():h||"",de=D&&f||"";function Ce(ie){x(ie),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function je(ie){b(ie),x("")}function Ae(ie){g(ie==="none"?"":ie),b(""),x(""),ie!=="none"&&ie!==""&&p("")}function ge(ie){m(ie)}function Oe(ie){p(ie==="none"?"":ie),ie!=="none"&&ie!==""&&g("")}U&&((Ue=U==null?void 0:U.databases)==null?void 0:Ue.length)>0,I&&((He=I==null?void 0:I.schemas)==null?void 0:He.length)>0;const Ee=N==null?void 0:N.connections.map(ie=>({id:ie.id,name:ie.name,type:ie.type})),le=(Ye=T==null?void 0:T.datamodels)==null?void 0:Ye.map(ie=>({id:ie.id,name:ie.name})),se=U==null?void 0:U.databases.map(ie=>({id:ie.database_name,name:ie.database_name})),Se=I==null?void 0:I.schemas.map(ie=>({id:ie.schema_name,name:ie.schema_name})),he=Y==null?void 0:Y.tables.map(ie=>({id:ie.table_name,name:ie.table_name})),fe=(et=T==null?void 0:T.datamodels.find(ie=>ie.id===c))==null?void 0:et.name,Fe=_!=null&&_.capabilities?z1({schemaName:de,tableName:oe,modelName:fe,databaseName:d||"",capabilities:_.capabilities}):oe;return{connectionItems:Ee,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:j,isConnectionsError:k,modelItems:le,selectedDatamodelId:c,selectedDatamodelName:fe,isModelsLoading:M,isModelsError:F,selectedDatabaseName:d,databaseItems:se,isDatabasesLoadingOrFetching:B||R,isDatabaseError:V,schemaItems:Se,selectedSchemaName:f,isSchemaLoadingOrFetching:W||X,isSchemaError:Z,tableItems:he,selectedTableName:h,isTableLoadingOrFetching:q||H,isTableError:K,columns:J,isColumnsLoadingOrFetching:re||me,isColumnsError:ee,isNonDbConnection:z,connectionType:P,tableName:oe,formattedTableName:Fe,schemaName:de,refetchConnections:S,refetchModels:E,refetchDatabases:O,refetchSchemas:$,refetchTables:G,refetchColumns:xe,handleConnectionChange:ge,handleDatamodelChange:Oe,handleDatabaseChange:Ae,handleSchemaChange:je,handleTableChange:Ce}}function Qw(e){return`${e}-${kr()}`}function LV(e,t){const n=Al(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function wut(e,t){const n=Al(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function A5(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Oae(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Lae(){const e=ze(j=>j.sqlGen),t=ze(j=>j.isDevMode),n=ze(j=>j.card.dataSource),r=ze(j=>{var k,_;return(_=(k=j.card)==null?void 0:k.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=A5(n),a=Oae(n),c=ze(j=>j.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=_r(),{modelItems:g,selectedDatamodelName:b}=vE(),{selectedConnection:x}=ra(),y=x==null?void 0:x.capabilities,v=j=>({column_name:j.name,data_type:j.dataType,label:j.label,description:j.description});return{handleDevModeFieldClick:j=>{var _;if(!t)return;const k=v(j);if(t&&a&&s&&y){const E=FD(k,e);m(E);const T=(_=g==null?void 0:g.find(F=>F.id===c))==null?void 0:_.name,M=PD(E,o||"",s,T||"",i||"",y,j.qualifiedEntityName);M&&(f(M),h(!0))}else if(!t){if(Ky(k.data_type))if(r&&r.length>0){const E={...k,role:"groupby",id:Qw(k.column_name),name:k.column_name,type:k.data_type};d(E)}else{const E={...k,role:"metric",id:Qw(k.column_name),name:k.column_name,label:LV(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(E)}if(ka(k.data_type)){const E={...k,role:"groupby",id:Qw(k.column_name),name:k.column_name,type:k.data_type,label:wut(k.column_name,"month"),granularity:"month"};d(E)}if(Ea(k.data_type)){const E={...k,role:"metric",id:Qw(k.column_name),name:k.column_name,label:LV(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=z1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${j}`:`SELECT * FROM ${j} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const j=z1({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${j}`),h(!0)},isNumberField:j=>Ea(j.dataType)}}function Cut(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>Px(o)).join("."),s=Px(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function $ae(e){const t=e;return{name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,expression:t.expression,calculatedFormula:t.calculatedFormula}}function zae(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function Vae(e){var t,n;return e?!!(e.entityName===Ei||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function Bae(){const e=te(c=>c.dashboard.filters)||[],t=te(c=>c.selectedSheetId),n=te(c=>c.actions.addFilter),r=te(c=>c.actions.removeFilter),{removeFilterValues:s}=Jt(),o=ze(c=>c.card.dataSource),{selectedConnection:i}=ra();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Cut(c);let m;if(u==="sheet"&&t?m=zRe(e,d,f,t):m=e==null?void 0:e.find(p=>Sp(p.column)===Sp(d)),m)s(m.id),r(m.id);else{const p=kr(),g=$ae(c),b=zae(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=Vae(g),y=u==="sheet"&&t?[t]:void 0,v=Nn(c.dataType)==="date"?"between":"in";return n({id:p,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:v,applyToSheetIds:y,sql:x?"":ote(c.dataType,f,h),fieldMeta:g,semanticContext:b}),p}}return{assignFilter:a}}function Sut({column:e}){const[t,n]=w.useState(!1),r=ze(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=A5(r),a=ze(y=>y.selectedDatamodelId),c=ze(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=vE(),f=d==null?void 0:d.capabilities,h=ze(y=>y.actions.setSqlGen),m=ze(y=>y.actions.setCardSql),p=ze(y=>y.actions.setRunSql),g=Oae(r);function b(y,v){var k,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=FD(y,c,v),S=(k=u==null?void 0:u.find(E=>E.id===a))==null?void 0:k.name;if(h(C),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const N=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),j=PD(C,o||"",s,S||"",i||"",f,N);j&&(m(j),p(!0)),n(!1)}function x(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?l.jsxs(Qp,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Jp,{asChild:!0,children:l.jsx(vh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(eg,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}const Uae="absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 font-mono text-[7px] font-semibold leading-none shadow-sm",$V="bg-emerald-500/90 text-white",Nut="bg-blue-500/90 text-white";function Hae(e){const t=RS(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:$V}:{label:"fx",badgeClassName:e.role==="metric"?$V:Nut}}function jut(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function Eut(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function kut({field:e,fieldState:t}){const n=Eut(e),r=jut(e.format);return l.jsxs("div",{className:"w-64 bg-background p-0",children:[l.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[l.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),l.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&l.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-xs text-foreground",children:n})]}),r.length>0&&l.jsxs("div",{className:"mb-3 rounded bg-muted/50 p-2",children:[l.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Format"}),l.jsx("div",{className:"space-y-0.5",children:r.map(s=>l.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[l.jsx("span",{className:"text-muted-foreground",children:s.label}),l.jsx("span",{className:"font-mono text-foreground",children:s.value})]},`${s.label}-${s.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),l.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:l.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function zV({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=ze(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",c=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=te(K=>K.dashboard.filters),d=te(K=>K.selectedSheetId),f=te(K=>K.actions.removeFilter),{removeFilterValues:h}=Jt(),{assignFilter:m}=Bae(),p=t==="filter"?Gc(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const G=Sp(K.column||""),J=Sp(e.name);return G.endsWith(`.${J}`)||G===J}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,C=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:C,selectedSheetId:d});const[S,N]=w.useState(!1),[j,k]=w.useState(null),{attributes:_,listeners:E,setNodeRef:T,transform:M,transition:F,isDragging:P}=Lg({id:e.id,disabled:c}),[D,L]=w.useState(!1),z=ze(K=>K.card),{handleFieldClick:U}=Fae(z),{handleDevModeFieldClick:B,isNumberField:R}=Lae(),V=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),k(null),N(!1)},O=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&C?(k(e),N(!0)):m(e,"sheet"):i?B(e):U(e)},I={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},W={transform:Ti.Transform.toString(M),transition:F},X=()=>{if(!n||a)return{};const G={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...G},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...G},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...G}}[n.state]||G};function Z(K){return K==="domain"?{label:"Semantic domain",Icon:tme,className:"text-foreground/55 hover:text-foreground/85"}:K==="dashboard"?{label:"Dashboard",Icon:pA,className:"text-foreground/55 hover:text-foreground/85"}:{label:"Card",Icon:aU,className:"text-foreground/55 hover:text-foreground/85"}}const $=X(),Y=e.fieldScope,q=Y?Z(Y):null,H=Hae(e);return l.jsxs("div",{ref:T,style:W,...c?{}:_,...c?{}:E,className:Q("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",P&&"scale-95 opacity-50",!P&&"border",$.borderColor||"border-transparent",$.bgColor||"",$.hoverBorderColor,$.hoverBgColor||"hover:bg-muted",$.opacity,$.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!c&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:O,children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(e.dataType),H&&l.jsx("span",{className:Q(Uae,H.badgeClassName),children:H.label})]}),l.jsx(wr,{children:l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${D?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),l.jsx(Tn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:l.jsx(kut,{field:e,fieldState:n})})]})}),i&&!a&&R(e)&&l.jsx("div",{onClick:K=>K.stopPropagation(),children:l.jsx(Sut,{column:I})}),t==="editor"&&q&&l.jsxs("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:[o&&l.jsx("div",{className:"mr-1 flex items-center opacity-0 transition-opacity pointer-events-none group-hover/container:opacity-100 group-hover/container:pointer-events-auto group-focus-within/container:opacity-100 group-focus-within/container:pointer-events-auto [@media(hover:none)]:opacity-100 [@media(hover:none)]:pointer-events-auto",children:o}),l.jsxs(yn,{children:[l.jsx(vn,{asChild:!0,children:l.jsx("span",{"aria-label":`${q.label} calculated field`,title:"",className:Q("block p-0.5 transition-colors",q.className),children:l.jsx(q.Icon,{className:"h-3.5 w-3.5"})})}),l.jsxs(Tn,{side:"top",align:"end",children:[q.label," calculated field"]})]})]}),o&&(!q||t!=="editor")&&l.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),D&&l.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:l.jsx(Ni,{className:"",children:l.jsxs(Ia,{className:"space-y-2 p-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lU,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.label||e.name})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(lme,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"break-all",children:e.name})]}),l.jsx(tt,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),l.jsx(Wc,{open:S,onOpenChange:N,children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Vl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs($l,{children:[l.jsx(Ul,{children:"Cancel"}),l.jsx(Bl,{onClick:V,children:"Remove Filter"})]})]})})]})}var Wa="Accordion",_ut=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[R5,Tut,Iut]=o0(Wa),[wE]=gs(Wa,[Iut,GZ]),P5=GZ(),Wae=w.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(R5.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Rut,{...o,ref:t}):l.jsx(Aut,{...s,ref:t})})});Wae.displayName=Wa;var[qae,Mut]=wE(Wa),[Yae,Dut]=wE(Wa,{collapsible:!1}),Aut=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=Os({prop:n,defaultProp:r??"",onChange:s,caller:Wa});return l.jsx(qae,{scope:e.__scopeAccordion,value:w.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:w.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(Yae,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(Gae,{...i,ref:t})})})}),Rut=w.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=Os({prop:n,defaultProp:r??[],onChange:s,caller:Wa}),c=w.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=w.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(qae,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(Yae,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(Gae,{...o,ref:t})})})}),[Put,CE]=wE(Wa),Gae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=w.useRef(null),c=jt(a,t),u=Tut(n),f=ld(s)==="ltr",h=Xe(e.onKeyDown,m=>{var k;if(!_ut.includes(m.key))return;const p=m.target,g=u().filter(_=>{var E;return!((E=_.ref.current)!=null&&E.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,C=x-1,S=()=>{y=b+1,y>C&&(y=v)},N=()=>{y=b-1,y<v&&(y=C)};switch(m.key){case"Home":y=v;break;case"End":y=C;break;case"ArrowRight":o==="horizontal"&&(f?S():N());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?N():S());break;case"ArrowUp":o==="vertical"&&N();break}const j=y%x;(k=g[j].ref.current)==null||k.focus()});return l.jsx(Put,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(R5.Slot,{scope:n,children:l.jsx(dt.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),PS="AccordionItem",[Fut,F5]=wE(PS),Kae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=CE(PS,n),i=Mut(PS,n),a=P5(n),c=Wr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(Fut,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(XZ,{"data-orientation":o.orientation,"data-state":tle(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Kae.displayName=PS;var Zae="AccordionHeader",Xae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(Zae,n);return l.jsx(dt.h3,{"data-orientation":s.orientation,"data-state":tle(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Xae.displayName=Zae;var dD="AccordionTrigger",Qae=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(dD,n),i=Dut(dD,n),a=P5(n);return l.jsx(R5.ItemSlot,{scope:n,children:l.jsx(qIe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Qae.displayName=dD;var Jae="AccordionContent",ele=w.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=CE(Wa,n),o=F5(Jae,n),i=P5(n);return l.jsx(YIe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});ele.displayName=Jae;function tle(e){return e?"open":"closed"}var Out=Wae,Lut=Kae,$ut=Xae,nle=Qae,rle=ele;const SE=Out,Rp=A.forwardRef(({className:e,...t},n)=>l.jsx(Lut,{ref:n,className:Q("border-b",e),...t}));Rp.displayName="AccordionItem";const Pp=A.forwardRef(({className:e,children:t,...n},r)=>l.jsx($ut,{className:"flex",children:l.jsxs(nle,{ref:r,className:Q("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(vr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Pp.displayName=nle.displayName;const Fp=A.forwardRef(({className:e,children:t,...n},r)=>l.jsx(rle,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:Q("pb-4 pt-0",e),children:t})}));Fp.displayName=rle.displayName;let sle=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Oy=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],rc=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Jd=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e,VV="calculated_fields";function zut(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function Vut(e){return e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Ei||e.entityName===VV||e.qualifiedEntityName===VV||zut(e.id)}function But(e){return e.aggregate?e.aggregate:DK(e.dataType)}function Uut(e,t){const n=But(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function Hut(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||Vut(o)||typeof o.expression=="string"&&MK(o.expression)?n:Uut(n,o)})}function BV(e,t,n,r,s,o,i,a,c,u){const d=Oy.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(c===void 0||Number.isNaN(c))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(c)),h=[n],m=c}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}t!=="custom"&&(f=Hut(f,h));const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=rc(e);return{id:i||`calc_${sle(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",expression:f,calculatedFormula:p,entityId:o,entityName:Ei,entityType:"table",description:`Calculated field: ${e}`}}function Wut(e){var r,s;const t=Oy.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function qut(e,t,n,r,s,o){const i=rc(e);return{id:o||`calc_dim_${sle(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:Ei,entityType:"table",description:`Calculated field: ${e.trim()}`}}function Yut(){const{domainCalculatedFields:e}=I5(),t=w.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=w.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function Gut({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx($s,{value:a,onValueChange:c=>t(c),className:"w-full",children:l.jsx(js,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(c=>l.jsx(sn,{value:c,disabled:i,className:"text-xs",children:c==="metric"?"Calculated Metric":"Calculated Dimension"},c))})})}function Kut({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Hn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&l.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:l.jsx(Tt,{className:"size-3.5"})})]}),l.jsx(Ba,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(SE,{type:"multiple",defaultValue:c,className:"space-y-2",children:e.map(f=>l.jsxs(Rp,{value:f.id,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return l.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:Q("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(h.dataType),h.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:l.jsx("span",{className:Q("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&l.jsx(tt,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function Zut({value:e,onChange:t,allowCustom:n,disabled:r}){const s=Oy.filter(c=>n?!0:c.id!=="custom"),i=!s.some(c=>c.id==="custom")&&e==="custom"?[...s,Oy.find(c=>c.id==="custom")]:s,a=i.find(c=>c.id===e);return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(xt,{value:e,onValueChange:c=>t(c),disabled:r,children:[l.jsx(pt,{children:l.jsx(vt,{})}),l.jsx(gt,{children:l.jsxs(NP,{children:[l.jsx(cj,{children:"OPERATIONS"}),i.map(c=>l.jsx(_e,{value:c.id,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-sm",children:c.symbol}),l.jsx("span",{children:c.label})]})},c.id))]})})]}),a&&l.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const Xut={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function Qut({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?Nn(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],c=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return l.jsxs(xt,{value:e,onValueChange:u=>t(u),disabled:n,children:[l.jsx(pt,{className:"h-9",children:l.jsx(vt,{})}),l.jsx(gt,{children:c.map(u=>l.jsx(_e,{value:u,children:Xut[u]},u))})]})}const Jut=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function UV({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:c,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return l.jsxs("div",{className:Q("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),l.jsxs("div",{className:"flex flex-1 gap-2",children:[l.jsxs(xt,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[l.jsx(pt,{className:"h-9 flex-1",children:l.jsx(vt,{placeholder:"Select field"})}),l.jsx(gt,{children:f.map(h=>l.jsx(_e,{value:h.id,children:Jut(h)},h.id))})]}),l.jsx("div",{className:"w-36",children:l.jsx(Qut,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:c})})]}),t&&l.jsx(ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:l.jsx(Tt,{className:"h-3.5 w-3.5"})})]})}const HV=w.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,docsUrl:o,placeholder:i,disabled:a},c){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm font-medium",children:"Expression"}),l.jsxs("div",{className:"flex items-center gap-2",children:[o&&l.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:["Docs",l.jsx(ep,{className:"h-3 w-3"})]}),s&&l.jsxs(ne,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:a,className:"h-7 gap-2 text-xs",children:[l.jsx(X1,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]})]}),l.jsx(ah,{ref:c,value:t,onChange:u=>n(u.target.value),disabled:a,rows:3,placeholder:i||"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-0 resize-none overflow-y-auto font-mono text-xs leading-5"})]})}),O5=A.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(Nye,{children:l.jsx(ta,{children:l.jsx(g0,{ref:r,sideOffset:t,className:Q("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));O5.displayName="ValidationTooltipContent";const ole=JA;function D_(e,t){return`${e} ${t}${e===1?"":"s"}`}function edt({result:e}){const t=e.errors.length>0,n=D_(e.tokens.length,"token"),r=e.errors.length>0?D_(e.errors.length,"error"):null,s=e.warnings.length>0?D_(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
1196
+ `);return l.jsxs(yn,{delayDuration:120,children:[l.jsx(vn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:Q("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(Tt,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(es,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(O5,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:Q("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(oA,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(rd,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(ole,{className:"fill-popover"})]})]})}function WV({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(ne,{type:"button",variant:"outline",onClick:e,disabled:t||s,className:"h-8",children:t?"Validating expression (may take a few seconds)...":"Validate Expression"}),n&&l.jsx(edt,{result:n}),!n&&r&&l.jsxs(yn,{delayDuration:120,children:[l.jsx(vn,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(Tt,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(O5,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(rd,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(ole,{className:"fill-popover"})]})]})]})}function tdt({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Availability"}),l.jsxs(Po,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-card",value:"card"}),l.jsx(pe,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-dashboard",value:"dashboard"}),l.jsx(pe,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Rn,{id:"scope-domain",value:"domain"}),l.jsx(pe,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]})}function ndt({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return l.jsxs("div",{className:"space-y-2 rounded-md border border-muted bg-muted/30 p-2.5",children:[l.jsxs("div",{className:"grid gap-2 sm:grid-cols-[minmax(0,1fr)_220px] sm:items-end",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(pe,{htmlFor:"domain-description",children:"Description"}),l.jsx(ah,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:Q("min-h-0 resize-none overflow-y-auto text-sm",s&&"border-red-500"),rows:2,disabled:o}),s&&l.jsx("p",{className:"text-xs text-red-500",children:s})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(pe,{htmlFor:"domain-tags",children:"Tags (optional)"}),l.jsx(Pt,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o,className:"h-9"})]})]}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function rdt(e){var r;const t=Jy(e,"AI generation failed"),n=(r=Ffe(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function sdt({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=it(),[o,i]=w.useState(!1),[a,c]=w.useState(null);return{generateExpression:w.useCallback(async d=>{var f;if(!e)return c("AI generation is not available"),null;if(!d.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType,...p.role==="metric"||p.role==="groupby"?{role:p.role}:{}})),fieldType:n},options:{dialect:r}},m=await Ur(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return c(rdt(h)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function ile(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei}function odt(e){return ile(e)?Ao:e.qualifiedEntityName||e.entityName||"Other"}function idt(e){return ile(e)?"Calculated Fields":e.qualifiedEntityName?Uf(e.entityName||e.qualifiedEntityName):Uf(e.entityName||"Other")}function adt({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,c]=w.useState(""),[u,d]=w.useState(""),[f,h]=w.useState(""),[m,p]=w.useState([]),g=w.useRef(null),{generateExpression:b,isGenerating:x,error:y}=sdt({endpoint:o,availableFields:n,fieldType:r,dialect:i}),v=w.useMemo(()=>{const M=f.trim().toLowerCase();return M?n.filter(F=>[F.label,F.baseLabel,F.name,F.tokenLabel,F.entityName,F.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(M)):n},[n,f]),C=w.useMemo(()=>{const M=new Map;return v.forEach(F=>{var L;const P=odt(F),D=idt(F);M.has(P)||M.set(P,{id:P,label:D,fields:[]}),(L=M.get(P))==null||L.fields.push(F)}),Array.from(M.values())},[v]),S=w.useMemo(()=>C.map(M=>M.id),[C]);w.useEffect(()=>{e&&p(S)},[e,S]),w.useEffect(()=>{if(e){if(f.trim()){p(S);return}p(M=>{const F=M.filter(P=>S.includes(P));return F.length>0?F:S})}},[e,f,S]);const N=M=>{const P=(M.name||M.baseLabel||M.label||M.tokenLabel||"").trim();return P.includes(".")&&P.split(".").pop()||P},j=M=>{const F=`{${M}}`,P=g.current;if(!P){c(z=>z+F);return}const D=P.selectionStart||0,L=P.selectionEnd||0;c(z=>`${z.slice(0,D)}${F}${z.slice(L)}`),requestAnimationFrame(()=>{P.focus();const z=D+F.length;P.setSelectionRange(z,z)})},k=M=>{const F=M.tokenLabel||M.name||M.baseLabel||M.label||"";F.trim()&&j(F.trim())},_=async()=>{const M=await b(a.trim());M&&d(M)},E=()=>{u.trim()&&(s(u.trim()),c(""),d(""),t(!1))},T=()=>{c(""),d(""),h(""),p([]),t(!1)};return l.jsx(Yr,{open:e,onOpenChange:M=>{M?t(!0):T()},children:l.jsxs(Rr,{className:"max-w-3xl",children:[l.jsxs(Pr,{children:[l.jsx(Fr,{children:"Generate Expression with AI"}),l.jsx(us,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),l.jsx(ah,{id:"ai-prompt",ref:g,value:a,onChange:M=>c(M.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),l.jsx(ne,{size:"sm",onClick:_,disabled:x||!a.trim(),children:x?"Generating...":u?"Regenerate":"Generate"})]}),y&&l.jsx("p",{className:"text-xs text-destructive whitespace-pre-wrap",children:y})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Available fields"}),l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),l.jsx(Pt,{value:f,onChange:M=>h(M.target.value),placeholder:"Search fields...",className:"pl-9"})]}),l.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:l.jsx(Ba,{className:"h-64",children:C.length===0?l.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):l.jsx(SE,{type:"multiple",value:m,onValueChange:p,className:"space-y-1 p-2",children:C.map(M=>l.jsxs(Rp,{value:M.id,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[360px] truncate text-sm font-medium text-primary",children:M.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:M.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:M.fields.map(F=>l.jsxs("button",{type:"button",onClick:()=>k(F),className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",children:[l.jsxs("div",{className:"relative shrink-0",children:[lh(F.dataType),F.isCalculated&&l.jsx("span",{className:Q("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",F.role==="metric"?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-mono text-xs text-foreground/90 group-hover/container:text-foreground",children:N(F)}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:F.tokenLabel})]}),l.jsx(tt,{variant:"secondary",className:"shrink-0 px-1.5 py-0 text-[11px]",children:F.dataType})]},F.id))})})]},M.id))})})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Generated expression"}),l.jsx(ah,{value:u,onChange:M=>d(M.target.value),rows:2,className:"font-mono text-sm"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Review and edit the generated expression before using it."})]})]}),l.jsxs(Ls,{className:"gap-2",children:[l.jsx(ne,{variant:"ghost",onClick:T,children:"Cancel"}),l.jsx(ne,{onClick:E,disabled:!u.trim(),children:"Use Expression"})]})]})})}const ldt=/\{([^}]+)\}/g;function NE(e){return e.trim().toLowerCase()}function ale(e){return Array.from(e.matchAll(ldt)).map(t=>t[1]).filter(Boolean)}function cdt(e){const t=new Set,n=[];return e.forEach(r=>{const s=NE(r);t.has(s)||(t.add(s),n.push(r))}),n}function L5(e){const t=new Map,n=(r,s)=>{const o=NE(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function A1(e,t){const n=ale(e),r=cdt(n),s=L5(t),o=r.map(a=>{const c=s.get(NE(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function fD(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${udt(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function udt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const ddt=e=>e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei?"Calculated Fields":e.qualifiedEntityName?Uf(e.entityName||e.qualifiedEntityName):Uf(e.entityName||"Other");function fdt(e){return e.entityName===Ao||e.qualifiedEntityName===Ao||e.entityName===Ei?Ao:e.qualifiedEntityName||e.entityName||"Other"}const hdt=e=>Nn(e.dataType||"")==="number";function mdt(e,t,n){const r=new Set((n||[]).map(s=>Jd(s)));return e.filter(s=>{const o=Jd(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function pdt(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Ei?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function gdt(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||hdt(o);return{...o,isCompatible:i}}).filter(o=>r)}function bdt(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function xdt(e){const t=new Map;return e.forEach(n=>{var s;const r=fdt(n);t.has(r)||t.set(r,{id:r,label:ddt(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function ydt({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=w.useMemo(()=>mdt(e,t,r),[e,t,r]),a=w.useMemo(()=>pdt(i),[i]),c=w.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&Eh(m)||m.role==="groupby"&&KN(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=w.useMemo(()=>L5(c),[c]),d=w.useMemo(()=>gdt(c,t,s,o),[c,t,s,o]),f=w.useMemo(()=>bdt(d,n),[d,n]),h=w.useMemo(()=>xdt(f),[f]);return{allFields:c,filteredFields:f,groups:h,tokenCandidates:u}}const vdt=e=>Nn(e.dataType||"")==="number",qV=e=>vdt(e)?"SUM":"COUNT",wdt=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||qV(e)}}const t=qV(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},Cdt=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}}};function Sdt({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=it(),[u,d]=w.useState(null),[f,h]=w.useState(!1),[m,p]=w.useState(null),g=w.useMemo(()=>L5(t),[t]),b=w.useMemo(()=>ale(e).map(S=>{const N=g.get(NE(S))||[];return{token:S,field:N.length===1?N[0]:null}}),[e,g]),x=w.useCallback((C,S)=>{const N=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:b,errors:N,warnings:[]}},[b]),y=w.useCallback(async()=>{var P;p(null);const C=n==null?void 0:n.trim();if(!C){const D=x("Validation endpoint is not configured");return d(D),D}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const D=x("Validation context is incomplete for server-side validation");return d(D),D}const{orderedTokens:N,orderedFields:j}=A1(e,t),k=[],_=[];N.forEach((D,L)=>{const z=j[L];z&&(k.push(D),_.push(z))});const E=o==="metric"?_.map(wdt):_,T=Cdt(e,_),M=fD(e,k),F={type:"calculated-field-expression",fieldType:o,expression:M,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const D=await Ur(C,(c==null?void 0:c.accessToken)||"",F),L=D==null?void 0:D.status,z=D==null?void 0:D.error,U=D==null?void 0:D.errorCode,B=[],R=[];L==="invalid"?B.push({code:"SQL_VALIDATION_ERROR",message:z||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):L==="unverified"?R.push({code:"EXECUTION_UNVERIFIED",message:z||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):L!=="valid"&&B.push({code:"SQL_VALIDATION_ERROR",message:z||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const V={isValid:(L==="valid"||L==="unverified")&&B.length===0,tokens:b,errors:B,warnings:R,inferredDataType:(D==null?void 0:D.inferredDataType)??((P=D==null?void 0:D.metadata)==null?void 0:P.inferredDataType)??T??i??void 0};return d(V),V}catch(D){const L=(D==null?void 0:D.error)||(D==null?void 0:D.message)||"Expression validation failed";p(L);const z=x(L);return d(z),z}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,x,b]),v=w.useCallback(()=>{d(null),p(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:y,resetValidation:v}}function YV(e,t){const{aggregate:n,...r}=e;return{...r,...t}}const GV=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],Ndt=[],jdt="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",Edt="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",kdt="SUM({amount} - {discount_amount}) / NULLIF(SUM({quantity}), 0)",_dt="CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",A_=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},lle=e=>Nn(e.dataType||"")==="number",cm=e=>lle(e)?"SUM":"COUNT",R_=(e,t)=>lle(e)||t==="COUNT"||t==="DISTINCT"?t:cm(e);function P_(e,t){if(e.role==="metric"){const n=e;return Eh(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function em(e,t){const n=e.role==="metric"&&Eh(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function cle({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:c,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var Es;const{tokenProps:m}=it(),{selectedConnection:p}=FK(),g=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.config}),b=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.dataSource}),x=ze(ue=>{var qe;return(qe=ue.card)==null?void 0:qe.type}),v=ze(ue=>ue.filterValues)??Ndt,C=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[S,N]=w.useState(f),[j,k]=w.useState(""),[_,E]=w.useState("ratio"),[T,M]=w.useState(null),[F,P]=w.useState(null),[D,L]=w.useState(1),[z,U]=w.useState(""),[B,R]=w.useState(null),[V,O]=w.useState("card"),[I,W]=w.useState(""),[X,Z]=w.useState(""),[$,Y]=w.useState({}),[q,H]=w.useState("A"),[K,G]=w.useState(""),[J,re]=w.useState(!1),[me,ee]=w.useState(null),[xe,oe]=w.useState(!1),[de,Ce]=w.useState(!1),je=w.useRef(null),Ae=w.useRef(!1),ge=w.useRef(null),{userContext:Oe}=Vo(),{metrics:Ee,dimensions:le}=Yut(),se=(Oe==null?void 0:Oe.type)==="organization",Se=!se,he=!!d&&se,fe=he&&!!a,Fe=he&&!!c,ye=!!(i||fe||Fe),Ne=!!i,$e=S==="metric"?fe:Fe,Re=(Es=m==null?void 0:m.apiServiceUrl)==null?void 0:Es.replace(/\/$/,""),Ue=Re?`${Re}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",He=Re?`${Re}/v1/ai/generate`:"/v1/ai/generate",Ye=w.useMemo(()=>{var ot;const ue=[...n];return(((ot=r==null?void 0:r.calculatedFormula)==null?void 0:ot.inputFields)||[]).forEach(mt=>{ue.some(Lt=>Lt.id===mt.id||Lt.qualifiedFieldName===mt.qualifiedFieldName||Lt.name===mt.name)||ue.push(mt)}),ue},[n,r]),et=q==="A"?T:F,ie=S==="metric"&&_!=="custom"?et==null?void 0:et.aggregate:void 0,{allFields:Te,groups:Pe}=ydt({fields:Ye,mode:S,searchTerm:K,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:ie,showIncompatible:!0}),Ie=Te,{validationResult:Ze,validateExpression:ke,isValidating:We,serverError:ct,resetValidation:Be}=Sdt({expression:z,availableFields:Ie,validationEndpoint:Ue,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect,fieldType:S,outputType:B||void 0,validationContext:{connectionId:(p==null?void 0:p.id)||(b==null?void 0:b.connectionId),cardId:u,cardConfig:g||{},cardDataSource:b||null,activeFilters:v,cardType:x}}),Je=Ze==null?void 0:Ze.inferredDataType,ft=B||Je||"string",kt=Oy.find(ue=>ue.id===_),en=w.useMemo(()=>{if(!j.trim())return!1;const ue=rc(j),qe=s==="domain"&&(r!=null&&r.name)?rc(r.name):null;return(S==="metric"?Ee:le).some(mt=>{const ut=rc(mt.name);return qe&&ut===qe?!1:ut===ue})},[le,Ee,r,s,S,j]),Bn=w.useMemo(()=>{if(S==="metric"&&_==="custom"){const{orderedFields:qe}=A1(z,Ie);return qe.filter(ot=>!!ot).map(ot=>ot.id)}const ue=[];return T!=null&&T.field.id&&ue.push(T.field.id),F!=null&&F.field.id&&ue.push(F.field.id),ue},[Ie,z,S,T,F,_]),ar=ue=>{Se||(N(ue),ue==="dimension"&&V==="domain"&&!Fe&&O("card"),ue==="metric"&&V==="domain"&&!fe&&O("card"))},qn=ue=>{Se||(E(ue),ue==="scale"&&P(null),ue==="custom"&&(M(null),P(null)))},Yn=()=>{k(""),E("ratio"),M(null),P(null),L(1),U(""),R(null),O("card"),W(""),Z(""),Y({}),G(""),re(!1),ee(null),oe(!1),Be(),t(!1)},Zr=w.useCallback(ue=>Ye.find(qe=>qe.qualifiedFieldName===ue.qualifiedFieldName||qe.name===ue.name)||ue,[Ye]),zs=w.useCallback(ue=>{if(!ue.calculatedFormula)return;const qe=ue.calculatedFormula;if(E(qe.operation),U(""),qe.operation==="scale"){const ut=qe.inputFields[0];ut&&M(em(Zr(ut),ut.aggregate||"SUM")),L(qe.constant===void 0?1:qe.constant);return}if(qe.operation==="custom"){U(ve(ue.expression||"",qe.inputFields||[])),M(null),P(null);return}const[ot,mt]=qe.inputFields;ot&&M(em(Zr(ot),ot.aggregate||"SUM")),mt&&P(em(Zr(mt),mt.aggregate||"SUM"))},[Zr]),ve=w.useCallback((ue,qe)=>ue.replace(/\{field_(\d+)\}/g,(ot,mt)=>{var Mn;const ut=qe[Number(mt)];return ut?`{${((Mn=Ie.find(Gn=>Gn.id===ut.id))==null?void 0:Mn.tokenLabel)||ut.label||ut.name}}`:ot}),[Ie]);w.useEffect(()=>{var ot;if(!e){Ae.current=!1,ge.current=null;return}const ue=r?`${r.role}-${r.id||r.name}`:"new";if(Ae.current&&ge.current===ue)return;if(Ae.current=!0,ge.current=ue,Y({}),G(""),Be(),r){const mt=r.tags||[];if(r.role==="metric"){N("metric"),k(r.label||r.name),O(s||"card"),W(r.description||""),Z(mt.join(", ")),zs(r);return}N("dimension");const ut=r;k(ut.label||ut.name),O(s||"card"),U(ve(ut.expression||"",((ot=ut.calculatedFormula)==null?void 0:ot.inputFields)||[]));const Lt=GV.some(Mn=>Mn.value===ut.dataType)?ut.dataType:"string";R(Lt),W(ut.description||""),Z(mt.join(", "));return}const qe=h&&h.length>0?h.includes(f)?f:h[0]:f;N(qe),k(""),E("ratio"),M(null),P(null),L(1),U(""),R(null),O("card"),W(""),Z("")},[e,r,s,f,h,zs,ve,Be]);const Ke=ue=>{const qe=`{${ue}}`,ot=je.current;if(!ot){U(Mn=>Mn+qe);return}const mt=ot.selectionStart||0,ut=ot.selectionEnd||0,Lt=`${z.slice(0,mt)}${qe}${z.slice(ut)}`;U(Lt),requestAnimationFrame(()=>{ot.focus();const Mn=mt+qe.length;ot.setSelectionRange(Mn,Mn)})},wt=ue=>{if(Se)return;if(S==="dimension"||_==="custom"){Ke(ue.tokenLabel||ue.label||ue.name);return}const qe=R_(ue,q==="A"?(T==null?void 0:T.aggregate)||cm(ue):(F==null?void 0:F.aggregate)||cm(ue)),ot=em(ue,qe);if(q==="A"){M(ot),F||H("B");return}P(ot),T||H("A")},wn=(ue,qe)=>{if(!Se){if(ue==="A"&&T){M({...T,aggregate:qe});return}ue==="B"&&F&&P({...F,aggregate:qe})}},mr=async()=>{const ue={};if(j.trim()||(ue.name="Name is required"),_==="custom")z.trim()||(ue.expression="Expression is required"),ue.expression||(await ke()).isValid||(ue.expression="Fix validation errors before saving");else if(_==="scale")T||(ue.inputA="Please select a metric for input A"),Number.isNaN(D)&&(ue.constant="Please enter a valid multiplication factor");else{if(T||(ue.inputA="Please select a metric for input A"),F||(ue.inputB="Please select a metric for input B"),T&&F){const qe=T.field.id===F.field.id,ot=T.aggregate===F.aggregate;qe&&ot&&(ue.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const qe=Jd(r.id);(Jd(T==null?void 0:T.field.id)===qe||Jd(F==null?void 0:F.field.id)===qe)&&(ue.inputs="Cannot reference the field being edited")}}return ye&&(V==="domain"&&!fe&&(ue.scope="You do not have permission to save to domain"),V==="domain"&&!I.trim()&&(ue.description="Description is required for domain fields"),V==="domain"&&en&&(ue.name="A domain field with this name already exists")),Y(ue),Object.keys(ue).length===0},Xs=async()=>{const ue={};return j.trim()||(ue.name="Name is required"),z.trim()||(ue.expression="Expression is required"),ue.expression||(await ke()).isValid||(ue.expression="Fix validation errors before saving"),ye&&(V==="domain"&&!Fe&&(ue.scope="You do not have permission to save to domain"),V==="domain"&&!I.trim()&&(ue.description="Description is required for domain fields"),V==="domain"&&en&&(ue.name="A domain field with this name already exists")),Y(ue),Object.keys(ue).length===0},Uo=()=>{const{orderedTokens:ue,orderedFields:qe}=A1(z,Ie),ot=qe.filter(Lt=>!!Lt),mt=fD(z,ue),ut=qut(j,mt,ot,ft,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...ut}:ut},yt=()=>{var mt;if(_==="custom"){const{orderedTokens:ut,orderedFields:Lt}=A1(z,Ie),Mn=Lt.filter($t=>!!$t),Gn=(r==null?void 0:r.role)==="metric"?((mt=r.calculatedFormula)==null?void 0:mt.inputFields)||[]:[],tr=new Map;Gn.forEach($t=>{const Lr=Jd($t.id);Lr&&tr.set(Lr,$t),$t.qualifiedFieldName&&tr.set($t.qualifiedFieldName,$t),$t.name&&tr.set($t.name,$t)});const Ho=Mn.map($t=>{const Lr=Jd($t.id),Wo=Lr&&tr.get(Lr)||$t.qualifiedFieldName&&tr.get($t.qualifiedFieldName)||tr.get($t.name),Hg=((Wo==null?void 0:Wo.role)==="metric"?Wo.aggregate:void 0)||($t.role==="metric"?$t.aggregate:void 0)||cm($t);return P_($t,Hg)}),kn=fD(z,ut),hn=BV(j,_,null,null,{},u,r==null?void 0:r.id,kn,void 0,Ho);return r&&r.role==="metric"?YV(r,hn):hn}const ue=T?P_(T.field,T.aggregate):null,qe=F?P_(F.field,F.aggregate):null,ot=BV(j,_,ue,qe,{},u,r==null?void 0:r.id,void 0,_==="scale"?D:void 0);return r&&r.role==="metric"?YV(r,ot):ot},be=async ue=>{var ot,mt,ut;if(S==="dimension"){const Lt=Uo();if(ue==="dashboard"){if(!i){Y(Mn=>({...Mn,scope:"Dashboard scope is not available"}));return}i(Lt),Yn();return}if(ue==="domain"){if(!c){Y(hn=>({...hn,scope:"Domain scope is not available"}));return}const Mn=((ot=Lt.calculatedFormula)==null?void 0:ot.inputFields)||[],Gn=new Map,tr=Mn.map(hn=>{const $t=rc(hn.label||hn.name),Lr=Gn.get($t)||0;return Gn.set($t,Lr+1),Lr===0?$t:`${$t}_${Lr+1}`}),Ho=((mt=Lt.expression)==null?void 0:mt.replace(/\{field_(\d+)\}/g,(hn,$t)=>`{${tr[Number($t)]||$t}}`))||"",kn=tr.reduce((hn,$t,Lr)=>{const Wo=Mn[Lr];return KN(Wo)?hn[$t]={dimension:Wo.name}:hn[$t]={dataset:Wo.entityName,field:Wo.name},hn},{});try{await c({name:rc(j),label:j.trim(),description:I.trim(),expression:Ho,inputs:kn,dataType:ft,tags:X.split(",").map(hn=>hn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(hn){Y($t=>({...$t,scope:(hn==null?void 0:hn.message)||"Failed to save to domain"}));return}Yn();return}o(Lt),Yn();return}const qe=yt();if(ue==="dashboard"){if(!i){Y(Lt=>({...Lt,scope:"Dashboard scope is not available"}));return}i(qe),Yn();return}if(ue==="domain"){if(!a){Y(kn=>({...kn,scope:"Domain scope is not available"}));return}if(!qe.calculatedFormula){Y(kn=>({...kn,scope:"Calculated formula missing"}));return}const Lt=qe.calculatedFormula.inputFields,Mn=new Map,Gn=Lt.map(kn=>{const hn=rc(kn.label||kn.name),$t=Mn.get(hn)||0;return Mn.set(hn,$t+1),$t===0?hn:`${hn}_${$t+1}`}),tr=((ut=qe.expression)==null?void 0:ut.replace(/\{field_(\d+)\}/g,(kn,hn)=>`{${Gn[Number(hn)]||hn}}`))||"",Ho=Gn.reduce((kn,hn,$t)=>{const Lr=Lt[$t];return Lr.role==="metric"?Eh(Lr)?kn[hn]={metric:Lr.name}:kn[hn]={dataset:Lr.entityName,field:Lr.name,aggregate:Lr.aggregate}:kn[hn]={dataset:Lr.entityName,field:Lr.name},kn},{});try{await a({name:rc(j),label:j.trim(),description:I.trim(),expression:tr,inputs:Ho,tags:X.split(",").map(kn=>kn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(kn){Y(hn=>({...hn,scope:(kn==null?void 0:kn.message)||"Failed to save to domain"}));return}Yn();return}o(qe),Yn()},Qe=async()=>{if(Se)return;if(Y({}),S==="metric"){if(!await mr())return}else if(!await Xs())return;const ue=ye?V:s||"card";if(S==="metric"&&ue!=="domain"&&en&&!r){ee(ue),oe(!0);return}Ce(!0);try{await be(ue)}finally{Ce(!1)}},ht=w.useMemo(()=>{if(!kt||_==="custom")return"";if(_==="scale"){const ue=Number.isFinite(D)?D:1;return`${A_(T)} x ${ue}`}return`${A_(T)||"A"} ${kt.symbol} ${A_(F)||"B"}`},[kt,_,T,F,D]),pn=S==="metric"?jdt:Edt,lr=S==="metric"?kdt:_dt,er=S==="metric"?"Calculated Metric":"Calculated Dimension",Nr=S==="metric"?"border-emerald-600/30 bg-emerald-500/10 text-emerald-700":"border-sky-600/30 bg-sky-500/10 text-sky-700";return l.jsxs(l.Fragment,{children:[l.jsxs(Yr,{modal:!1,open:e,onOpenChange:ue=>{ue?t(!0):Yn()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(Rr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:ue=>{ue.preventDefault()},children:[l.jsxs(Pr,{children:[l.jsxs(Fr,{className:"flex items-center gap-2",children:[l.jsxs("span",{children:[r?"Edit":"Create"," Calculated Field"]}),l.jsx(tt,{variant:"outline",className:Nr,children:er})]}),l.jsx(us,{children:"Build calculated metrics and dimensions using expressions."})]}),l.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[l.jsx(Kut,{groups:Pe,searchTerm:K,onSearchTermChange:G,onFieldClick:wt,selectedFieldIds:Bn,disabled:Se}),l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2 pb-6",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Field Type"}),l.jsx(Gut,{value:S,onChange:ar,disabled:Se||!!r,options:h||["metric","dimension"]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"calculated-name",children:"Name"}),l.jsx(Pt,{id:"calculated-name",value:j,onChange:ue=>k(ue.target.value),placeholder:S==="metric"?"e.g., Profit Margin":"e.g., Sales Tier",className:$.name?"border-red-500":"",disabled:Se}),$.name&&l.jsx("p",{className:"text-xs text-red-500",children:$.name})]}),ye&&(Ne||$e)&&l.jsxs("div",{className:"space-y-3",children:[l.jsx(tdt,{scope:V,onChange:O,showDashboardScope:Ne,showDomainScope:$e,error:$.scope,disabled:Se}),V==="domain"&&l.jsx(ndt,{description:I,tags:X,onDescriptionChange:W,onTagsChange:Z,descriptionError:$.description,disabled:Se})]}),S==="metric"&&l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Operation"}),l.jsx(Zut,{value:_,onChange:qn,allowCustom:!0,disabled:Se}),$.operation&&l.jsx("p",{className:"text-xs text-red-500",children:$.operation})]}),_==="custom"?l.jsxs("div",{className:"space-y-4",children:[l.jsx(HV,{ref:je,value:z,onChange:ue=>{U(ue)},onGenerate:()=>re(!0),showGenerate:!!He&&!Se,docsUrl:pn,placeholder:lr,disabled:Se}),l.jsx(WV,{onValidate:ke,isValidating:We,validationResult:Ze,error:ct,disabled:Se}),$.expression&&l.jsx("p",{className:"text-xs text-red-500",children:$.expression})]}):l.jsxs("div",{className:"space-y-3",children:[l.jsx(pe,{children:"Inputs"}),l.jsx(UV,{label:"A",input:T,availableFields:Ie,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:ue=>{const qe=R_(ue,(T==null?void 0:T.aggregate)||cm(ue));M(em(ue,qe))},onAggregateChange:ue=>wn("A",ue),onRemove:()=>M(null),onActivate:()=>H("A"),allowMedian:C,disabled:Se}),$.inputA&&l.jsx("p",{className:"text-xs text-red-500",children:$.inputA}),_!=="scale"&&l.jsxs(l.Fragment,{children:[l.jsx(UV,{label:"B",input:F,availableFields:Ie,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:ue=>{const qe=R_(ue,(F==null?void 0:F.aggregate)||cm(ue));P(em(ue,qe))},onAggregateChange:ue=>wn("B",ue),onRemove:()=>P(null),onActivate:()=>H("B"),allowMedian:C,disabled:Se}),$.inputB&&l.jsx("p",{className:"text-xs text-red-500",children:$.inputB})]}),_==="scale"&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{htmlFor:"constantFactor",children:"Multiplication Factor"}),l.jsx(Pt,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(D)?"":D,onChange:ue=>L(ue.target.value===""?Number.NaN:Number(ue.target.value)),className:$.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:Se}),$.constant&&l.jsx("p",{className:"text-xs text-red-500",children:$.constant})]}),l.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:ht||"Select inputs to preview formula"}),$.inputs&&l.jsxs(Ej,{variant:"destructive",children:[l.jsx(Lc,{className:"h-4 w-4"}),l.jsx(kj,{children:$.inputs})]})]})]}),S==="dimension"&&l.jsxs("div",{className:"space-y-4",children:[l.jsx(HV,{ref:je,value:z,onChange:ue=>{U(ue)},onGenerate:()=>re(!0),showGenerate:!!He&&!Se,docsUrl:pn,placeholder:lr,disabled:Se}),l.jsx(WV,{onValidate:ke,isValidating:We,validationResult:Ze,error:ct,disabled:Se}),$.expression&&l.jsx("p",{className:"text-xs text-red-500",children:$.expression}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(pe,{children:"Output Type"}),l.jsxs(xt,{value:ft,onValueChange:ue=>R(ue),disabled:Se,children:[l.jsx(pt,{className:"h-9 w-full",children:l.jsx(vt,{placeholder:"Select output type"})}),l.jsx(gt,{children:GV.map(ue=>l.jsx(_e,{value:ue.value,children:ue.label},ue.value))})]}),Je&&!B&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",Je]})]})]})]})]}),l.jsxs(Ls,{children:[l.jsx(ne,{variant:"outline",onClick:Yn,disabled:de,children:"Cancel"}),l.jsx(ne,{onClick:Qe,disabled:de||Se,children:de?l.jsxs(l.Fragment,{children:[l.jsx(In,{className:"mr-2 h-4 w-4 animate-spin"}),r?"Updating":"Creating"," ",S==="metric"?"Metric":"Dimension","..."]}):l.jsxs(l.Fragment,{children:[r?"Update":"Create"," ",S==="metric"?"Metric":"Dimension"]})})]})]})]}),l.jsx(adt,{open:J,onOpenChange:re,availableFields:Ie,fieldType:S,onExpressionGenerated:async ue=>{U(ue),Be()},endpoint:He,dialect:p==null?void 0:p.dialect}),l.jsx(Wc,{open:xe,onOpenChange:oe,children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Name Conflict"}),l.jsxs(Vl,{children:['A domain metric named "',j.trim(),'" already exists. Your local version will override it in this'," ",me==="dashboard"?"dashboard":"card",". Continue?"]})]}),l.jsxs($l,{children:[l.jsx(Ul,{onClick:()=>{ee(null)},children:"Choose Different Name"}),l.jsx(Bl,{onClick:async()=>{if(me){oe(!1),Ce(!0);try{await be(me)}finally{Ce(!1),ee(null)}}},children:"Continue"})]})]})})]})}function ule({domainId:e}){const{authToken:t,tokenProps:n}=it(),[r,s]=w.useState(!1),[o,i]=w.useState(null),a=w.useMemo(()=>{var g;if(!e)return null;const m=(g=n==null?void 0:n.apiServiceUrl)==null?void 0:g.replace(/\/$/,""),p=`/v1/domains/${e}/calculated-metrics`;return m?`${m}${p}`:p},[e,n==null?void 0:n.apiServiceUrl]),c=w.useMemo(()=>{var g;if(!e)return null;const m=(g=n==null?void 0:n.apiServiceUrl)==null?void 0:g.replace(/\/$/,""),p=`/v1/domains/${e}/calculated-dimensions`;return m?`${m}${p}`:p},[e,n==null?void 0:n.apiServiceUrl]),u=w.useCallback(async m=>{if(!a){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(a,t.accessToken,m)}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to save to domain";throw i(g),new Error(g)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=w.useCallback(async m=>{if(!c){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(c,t.accessToken,m)}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to save to domain";throw i(g),new Error(g)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]),f=w.useCallback(async({name:m})=>{if(!a){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(a,t.accessToken,{name:m},"DELETE")}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to delete from domain";throw i(g),new Error(g)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),h=w.useCallback(async({name:m})=>{if(!c){const p="Domain promotion is not available";throw i(p),new Error(p)}if(!(t!=null&&t.accessToken)){const p="Missing authentication token";throw i(p),new Error(p)}s(!0),i(null);try{return await Ur(c,t.accessToken,{name:m},"DELETE")}catch(p){const g=(p==null?void 0:p.error)||(p==null?void 0:p.message)||"Failed to delete from domain";throw i(g),new Error(g)}finally{s(!1)}},[c,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,deleteMetric:f,deleteDimension:h,isPromoting:r,error:o}}const dle=w.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var qn,Yn,Zr,zs;const[s,o]=w.useState(""),[i,a]=w.useState("all"),[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,m]=w.useState("card"),[p,g]=w.useState("metric"),[b,x]=w.useState(null),[y,v]=w.useState(!1);ze(ve=>ve.isDevMode);const C=ze(ve=>ve.card.dataSource),S=ze(ve=>ve.card.config),N=ze(ve=>ve.card),j=ze(ve=>ve.frame),k=ze(ve=>ve.actions.updateCardConfig),_=ze(ve=>ve.actions.updateFrame),{userContext:E}=Vo(),{autoJoinMetadata:T}=_l(N),{columns:M,rawColumnGroups:F,scopedFields:P,domainCalculatedFields:D,dashboardCalculatedFields:L,cardCalculatedFields:z,isLoading:U,error:B,refetch:R}=I5(),V=(C==null?void 0:C.mode)==="semanticDomain"?C.semanticDomainId:void 0,{data:O}=M5(V),{promoteMetric:I,promoteDimension:W,deleteMetric:X,deleteDimension:Z}=ule({domainId:V}),$=w.useMemo(()=>[...(S==null?void 0:S.groupByColumns)||[],...(S==null?void 0:S.metricColumns)||[],...(S==null?void 0:S.detailColumns)||[]],[S==null?void 0:S.groupByColumns,S==null?void 0:S.metricColumns,S==null?void 0:S.detailColumns]);(Yn=(qn=S==null?void 0:S.joinPlan)==null?void 0:qn.baseEntity)==null||Yn.name,(zs=(Zr=T==null?void 0:T.resolvedJoinPlan)==null?void 0:Zr.baseEntity)==null||zs.name,Lae();const Y=t==="editor",q=(E==null?void 0:E.type)==="organization",H=Y?P:M,K=F,G=s.toLowerCase(),J=(S==null?void 0:S.metricColumns)||[],re=(S==null?void 0:S.groupByColumns)||[],me=w.useCallback(async ve=>{try{await I(ve),await R(),Ge.success(`${ve.overwrite?"Updated":"Saved"} ${ve.label||ve.name} in the semantic domain`)}catch(Ke){const wt=(Ke==null?void 0:Ke.message)||(Ke==null?void 0:Ke.error)||"Failed to save to semantic domain";throw Ge.error(wt),Ke}},[I,R]),ee=w.useCallback(async ve=>{try{await W(ve),await R(),Ge.success(`${ve.overwrite?"Updated":"Saved"} ${ve.label||ve.name} in the semantic domain`)}catch(Ke){const wt=(Ke==null?void 0:Ke.message)||(Ke==null?void 0:Ke.error)||"Failed to save to semantic domain";throw Ge.error(wt),Ke}},[W,R]),xe=ve=>ve.name.toLowerCase().includes(G)||ve.dataType.toLowerCase().includes(G)||ve.label&&ve.label.toLowerCase().includes(G)||ve.qualifiedEntityName&&ve.qualifiedEntityName.toLowerCase().includes(G),oe=w.useCallback(ve=>(ve.label||ve.name).toLowerCase().trim(),[]),de=w.useCallback((ve,Ke)=>oe(ve).localeCompare(oe(Ke),void 0,{numeric:!0,sensitivity:"base"}),[oe]),Ce=H.filter(xe).sort(de),je=ve=>{if(ve.role==="metric"&&Eh(ve)||ve.role==="groupby"&&ve.expression)return"calculated";if(ve.dataType==="number"||ve.dataType==="integer"||ve.dataType==="float"||ve.dataType==="decimal"||ve.dataType==="currency")return"metrics";const Ke=Nn(ve.dataType);return["date","string","boolean"].includes(Ke)?"dimensions":Ke==="number"?"metrics":"dimensions"},Ae=ve=>{const Ke=ve.filter(xe);return i==="all"?Ke:Ke.filter(wt=>je(wt)===i)},ge=i==="all"?Ce:Ce.filter(ve=>je(ve)===i),Oe=Y?[...D,...L,...z]:[],Ee=Y?Ae(Oe).sort(de):[],le=Y?M.filter(ve=>ve.fieldScope!=="domain"):M,Se=Ae(le).sort(de).reduce((ve,Ke)=>{const wt=Ke.qualifiedEntityName||"Other Fields";return ve[wt]||(ve[wt]={label:Uf(Ke.entityName),fields:[]}),ve[wt].fields.push(Ke),ve},{}),he=w.useMemo(()=>Object.entries(Se).map(([ve,Ke])=>{const wt=K.find(mr=>mr.entityName===ve)||{entityName:ve,label:Ke.label},wn=ve===Ao?"Domain Calculated Fields":wt.label||wt.entityName;return{groupName:ve,groupLabel:wn,fields:[...Ke.fields].sort(de)}}).sort((ve,Ke)=>ve.groupLabel.localeCompare(Ke.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Se,K,de]),fe=ve=>ve.id||`${ve.entityName}-${ve.qualifiedEntityName}-${ve.name}-${ve.role||"field"}`,Fe=w.useMemo(()=>{const ve=new Map;return(Y?P:M).forEach(wt=>{ve.set(fe(wt),rP(wt,{joinabilityMap:(O==null?void 0:O.joinabilityMap)||null,selectedFields:$,cardConfig:S,autoJoinMetadata:T}))}),ve},[Y,P,M,O==null?void 0:O.joinabilityMap,$,S,T]),ye=Y?[{key:"scope-calculated",label:"Calculated Fields",fields:Ee}].filter(ve=>ve.fields.length>0):[],$e=[...ye.map(ve=>ve.key),...he.map(ve=>ve.groupName)],Re=Ce.filter(ve=>je(ve)==="dimensions").length,Ue=Ce.filter(ve=>je(ve)==="metrics").length,He=Ce.filter(ve=>je(ve)==="calculated").length,Ye=Ce.length>0&&t!=="inline-filter",et=t==="inline-filter"?"w-full":"w-[290px]";if(U)return l.jsx("div",{className:Q("flex h-full flex-col items-center justify-center py-8",et),children:l.jsx(nd,{size:"md",color:"muted","aria-label":"Loading data"})});if(B)return l.jsxs("div",{className:Q("flex h-full flex-col items-center justify-center py-8",et),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:B.message||"Failed to load column data"})]});if(!C||!C.selectedEntities||C.selectedEntities.length===0)return l.jsxs("div",{className:Q("flex flex-col items-center justify-center py-8 text-center",et),children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const ie=t==="inline-filter"?"px-3 pb-3":"px-3 pb-6",Te=t==="inline-filter"?"overflow-hidden":"",Pe=ve=>ve!=null&&ve.startsWith("card-source-")?ve.replace("card-source-",""):ve,Ie=(ve,Ke,wt)=>{const wn=Pe(ve.id),mr=Pe(Ke.id);return wn&&mr&&wn===mr?!0:!wn||!mr||wt!=null&&wt.allowNameFallback?ve.name===Ke.name&&ve.role===Ke.role:!1},Ze=(ve,Ke,wt)=>ve.findIndex(wn=>Ie(wn,Ke,wt)),ke=ve=>{if(!j)return ve;const Ke=j.calculatedFields||[],wt=Ze(Ke,ve),wn=wt>=0&&Ke[wt].id!==ve.id?{...ve,id:Ke[wt].id}:ve,mr=wt>=0?Ke.map((Xs,Uo)=>Uo===wt?wn:Xs):[...Ke,wn];return _({calculatedFields:mr}),wn},We=(ve,Ke,wt,wn)=>{var Xs;const mr=Ze(ve,wt||Ke,wn);if(mr>=0){const Uo=(Xs=ve[mr])==null?void 0:Xs.id,yt=Uo&&Uo!==Ke.id?{...Ke,id:Uo}:Ke;return ve.map((be,Qe)=>Qe===mr?yt:be)}return[...ve,Ke]},ct=ve=>{if(ve.role==="metric")return J.find(Ke=>Ie(Ke,ve));if(ve.role==="groupby")return re.find(Ke=>Ie(Ke,ve))},Be=ve=>{var Ke;return(Ke=j==null?void 0:j.calculatedFields)==null?void 0:Ke.find(wt=>Ie(wt,ve))},Je=ve=>{if(ve.role==="metric"){k(N.id,{metricColumns:J.filter(Ke=>!Ie(Ke,ve,{allowNameFallback:ve.fieldScope==="dashboard"}))});return}ve.role==="groupby"&&k(N.id,{groupByColumns:re.filter(Ke=>!Ie(Ke,ve,{allowNameFallback:ve.fieldScope==="dashboard"}))})},ft=ve=>{if(!j)return;const Ke=(j.calculatedFields||[]).filter(wt=>!Ie(wt,ve));_({calculatedFields:Ke})},kt=ve=>{if(!q)return;if(ve.fieldScope==="domain"){f(ve),m("domain"),g(ve.role==="metric"?"metric":"dimension"),u(!0);return}if(ve.fieldScope==="dashboard"){const wt=Be(ve);if(!wt)return;f(wt),m("dashboard"),g(wt.role==="metric"?"metric":"dimension"),u(!0);return}const Ke=ct(ve);Ke&&(f(Ke),m("card"),g(Ke.role==="metric"?"metric":"dimension"),u(!0))},en=async ve=>{if(q){if(ve.fieldScope==="domain"){if(!V){Ge.error("Domain context is unavailable");return}try{ve.role==="metric"?await X({name:ve.name}):ve.role==="groupby"&&await Z({name:ve.name}),Je(ve),await R(),Ge.success(`Removed ${ve.label||ve.name} from the semantic domain`)}catch(Ke){throw Ge.error((Ke==null?void 0:Ke.message)||"Failed to delete domain calculated field"),Ke}return}if(ve.fieldScope==="dashboard"){ft(ve),Je(ve);return}Je(ve)}},Bn=async()=>{if(b){v(!0);try{await en(b),x(null)}catch{}finally{v(!1)}}},ar=ve=>{if(!q)return null;const wt=ve.fieldScope==="domain"&&!V;return l.jsxs(ud,{children:[l.jsx(dd,{asChild:!0,children:l.jsx(ne,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-full","aria-label":"Calculated field actions",children:l.jsx(vh,{className:"h-3.5 w-3.5"})})}),l.jsxs(Uc,{align:"end",className:"w-36",children:[l.jsx(lo,{onClick:()=>kt(ve),children:"Edit"}),l.jsx(lo,{className:"text-destructive focus:text-destructive",disabled:wt,onClick:()=>x(ve),children:"Delete"})]})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:Q("mt-2 flex h-full w-full grow flex-col gap-2",ie,Te),children:[l.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[H.length>0&&l.jsxs("div",{className:"relative",children:[l.jsx(Zs,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),l.jsx(Hn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:ve=>o(ve.target.value)}),s&&l.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:l.jsx(Tt,{className:"size-3.5"})})]}),Ye&&l.jsx($s,{defaultValue:"all",value:i,onValueChange:ve=>a(ve),className:"mb-4",children:l.jsxs(js,{className:"grid h-11 w-full grid-cols-4 rounded-lg border border-border/60 bg-muted/50 p-1",children:[l.jsxs(sn,{value:"all",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:["All",l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ce.length})]}),l.jsxs(sn,{value:"dimensions",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(rN,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Re})]}),l.jsxs(sn,{value:"metrics",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(QS,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:Ue})]}),l.jsxs(sn,{value:"calculated",className:"h-8 gap-1 rounded-md px-2 text-[13px] font-medium text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none",children:[l.jsx(iA,{className:"size-3.5 shrink-0"}),l.jsx("span",{className:"ml-1 text-xs font-semibold tabular-nums",children:He})]})]})}),t==="editor"&&i==="calculated"&&q&&l.jsx("div",{className:"flex items-center justify-end gap-2",children:l.jsxs(ne,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[l.jsx(qr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),l.jsxs(Ba,{className:"min-h-0 flex-1",children:[l.jsxs(SE,{type:"multiple",defaultValue:$e,className:"space-y-2",children:[ye.map(ve=>l.jsxs(Rp,{value:ve.key,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:ve.label}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:ve.fields.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:ve.fields.map(Ke=>{const wt=Fe.get(fe(Ke)),wn=t==="editor"&&q&&je(Ke)==="calculated";return l.jsx(zV,{field:Ke,context:t,fieldState:wt,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:wn?ar(Ke):void 0},Ke.id)})})})]},ve.key)),he.map(({groupName:ve,groupLabel:Ke,fields:wt})=>l.jsxs(Rp,{value:ve,className:"border-none",children:[l.jsx(Pp,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:l.jsxs("div",{title:Ke,className:"flex items-center gap-2",children:[l.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:Ke}),l.jsx(tt,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:wt.length})]})}),l.jsx(Fp,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:wt.map(wn=>{const mr=Fe.get(fe(wn)),Xs=t==="editor"&&q&&je(wn)==="calculated";return l.jsx(zV,{field:wn,context:t,fieldState:mr,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:Xs?ar(wn):void 0},wn.id)})})})]},ve))]}),H.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),H.length>0&&ge.length===0&&l.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),l.jsx(Ra,{orientation:"horizontal"}),l.jsx(Ra,{orientation:"vertical"})]})]}),l.jsx(Wc,{open:!!b,onOpenChange:ve=>{ve||x(null)},children:l.jsxs(Ol,{children:[l.jsxs(Ll,{children:[l.jsx(zl,{children:"Delete calculated field?"}),l.jsxs(Vl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(b==null?void 0:b.label)||(b==null?void 0:b.name)||"this calculated field"})," ",(b==null?void 0:b.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs($l,{children:[l.jsx(Ul,{disabled:y,children:"Cancel"}),l.jsx(Bl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:y,onClick:ve=>{ve.preventDefault(),Bn()},children:y?"Deleting...":"Delete"})]})]})}),l.jsx(cle,{open:c,onOpenChange:ve=>{u(ve),ve||(f(null),m("card"))},availableFields:P,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:ve=>{if(ve.role==="metric"){if(d&&h==="card"){k(N.id,{metricColumns:We(J,ve,d)});return}k(N.id,{metricColumns:We(J,ve)});return}if(d&&h==="card"){k(N.id,{groupByColumns:We(re,ve,d)});return}k(N.id,{groupByColumns:We(re,ve)})},onSaveToDashboard:ve=>{const Ke=!!(d&&h==="dashboard"),wt=Ke?d:void 0;if(ve.role==="metric"){const mr=ke(ve);k(N.id,{metricColumns:We(J,mr,wt,{allowNameFallback:Ke})});return}const wn=ke(ve);k(N.id,{groupByColumns:We(re,wn,wt,{allowNameFallback:Ke})})},cardId:N.id,onPromoteMetricToDomain:V?me:void 0,onPromoteDimensionToDomain:V?ee:void 0,domainId:V})]})}),fle=w.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(dle,{context:t})," "]})});function hle(){const e=ze(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=_r();w.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:c,connectionId:u}=A5(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(c||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function Tdt(){hle();const e=te(c=>c.selectedSheetId),t=te(c=>c.selectedFrameId),n=te(c=>c.dashboard),r=te(c=>c.actions.getSelectedFrame),{setSelectedFrameId:s}=Jt(),{setCard:o}=_r(),i=ze(c=>c.card.dataSource);return w.useEffect(()=>{var u,d;let c=r();if(!c){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),c=h)}if(c){const f=c.cards.find(h=>h.id===c.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function Idt(){const e=te(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Jt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return l.jsxs(ns,{children:[l.jsx(rs,{asChild:!0,children:l.jsx(ne,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:l.jsx(gl,{className:"h-4 w-4"})})}),l.jsx(ss,{className:"w-[280px]",align:"end",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),l.jsxs(Po,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Rn,{value:"canvas",id:"canvas",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(pe,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),l.jsxs("div",{className:"flex items-start space-x-3",children:[l.jsx(Rn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),l.jsxs("div",{className:"grid gap-0.5",children:[l.jsx(pe,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[l.jsx(Qt,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),l.jsx(pe,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),l.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[l.jsx(Qt,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),l.jsx(pe,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),l.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function Mdt(){const e=te(n=>n.actions.setShowFilters),{hasEntities:t}=Tdt();return l.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[l.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[l.jsx(pe,{className:"px-2 text-base",children:"Dashboard Filters"}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Idt,{}),l.jsx(ne,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:l.jsx(hre,{})})]})]}),!t&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[l.jsx(pl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&l.jsx("div",{className:"flex grow overflow-y-auto",children:l.jsx(cv,{collisionDetection:iv,children:l.jsx(uv,{items:[],strategy:FO,children:l.jsx(fle,{context:"filter"})})})})]})}function Ddt(){const e=te(r=>r.dashboard.filters),t=te(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:Q("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)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(TO,{filter:r}),l.jsx(Dg,{filter:r})]},r.id))}):null}function Adt(){const e=te(r=>r.showFilters),t=te(r=>r.isVisualEditing),n=te(r=>r.isDashboardEditing);return l.jsxs("div",{role:"dashboard-plus-main",className:Q("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[l.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&l.jsx(Ddt,{}),l.jsx(Tae,{})]}),e&&l.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:l.jsx(Mdt,{})})]})}const Rdt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BRv37g5w.js"))),Pdt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-D6RokBEF.js"))),Fdt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-DjNS3G-C.js"))),Odt=w.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-ZK4SWoad.js")).then(e=>({default:e.ResourceManagementPanel})));function Ldt({showControls:e=!1,showFooter:t=!0,...n}){const r=te(c=>c.isDashboardPanelOpen),s=te(c=>c.isVisualEditing),o=te(c=>c.showDashboardJSON),i=te(c=>c.actions.setIsDashboardPanelOpen),{preferences:a}=n;return l.jsx(Fa,{FallbackComponent:zj,children:l.jsxs(sA,{dashboardProps:n,children:[l.jsx(sye,{}),l.jsx(T5,{componentType:"surfboard",componentId:n.id}),l.jsx(_5,{children:l.jsxs(Iae,{preferences:a,children:[o&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Fdt,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Rdt,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Odt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(TP,{...n,type:"dashboard",children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(Pdt,{})}),l.jsx(Adt,{})]})})]})]})]})})]})})}const mle=A.forwardRef(({className:e,...t},n)=>l.jsx(ev,{className:Q("peer inline-flex h-[22px] w-[36px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:l.jsx(mO,{className:Q("pointer-events-none block size-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));mle.displayName=ev.displayName;var $dt=Object.defineProperty,zdt=(e,t,n)=>t in e?$dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Jw=(e,t,n)=>zdt(e,typeof t!="symbol"?t+"":t,n);const Vdt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Bdt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},Udt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Hdt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function ple(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Wdt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=ple(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},qdt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Ydt={stringify:e=>e,parse:e=>e},F_={string:Ydt,number:qdt,boolean:Vdt,function:Bdt,method:Wdt,json:Udt},xb=Symbol.for("r2wc.render"),e1=Symbol.for("r2wc.connected"),zd=Symbol.for("r2wc.context"),ci=Symbol.for("r2wc.props");function Gdt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const p=Hdt(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),Jw(this,o,!0),Jw(this,s),Jw(this,r,{}),Jw(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[ci].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=c[p],y=x?F_[x]:null;if(x==="method"){const v=ple(g);Object.defineProperty(this[ci].container,v,{enumerable:!0,configurable:!0,get(){return this[ci][v]},set(C){this[ci][v]=C,this[xb]()}}),this[ci][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[ci][p]=y.parse(b,g,this))}for(const p of a)this[ci][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[e1]=!0,this[xb]()}disconnectedCallback(){this[e1]=!1,this[zd]&&n.unmount(this[zd]),delete this[zd]}attributeChangedCallback(p,g,b){const x=f[p],y=c[x],v=y?F_[y]:null;x in c&&v!=null&&v.parse&&b&&(this[ci][x]=v.parse(b,p,this),this[xb]())}[(o=e1,s=zd,r=ci,xb)](){this[e1]&&(this[zd]?n.update(this[zd],this[ci]):this[zd]=n.mount(this.container,e,this[ci]))}}for(const m of i){const p=d[m],g=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[ci][m]},set(b){this[ci][m]=b;const x=g?F_[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[xb]()}})}return h}function Kdt(e,t,n){const r=hce.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function Zdt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function Xdt({root:e}){e.unmount()}function Qdt(e,t={}){return Gdt(e,t,{mount:Kdt,update:Zdt,unmount:Xdt})}const Jdt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},eft=Qdt(Mae,{props:Jdt});function KV(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function tft(e){if(Array.isArray(e))return e}function nft(e,t,n){return(t=cft(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rft(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],c=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(c=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(d){u=!0,s=d}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function sft(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1197
1197
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ZV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function XV(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ZV(Object(n),!0).forEach(function(r){nft(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZV(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function oft(e,t){if(e==null)return{};var n,r,s=ift(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function ift(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function aft(e,t){return tft(e)||rft(e,t)||uft(e,t)||sft()}function lft(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cft(e){var t=lft(e,"string");return typeof t=="symbol"?t:t+""}function uft(e,t){if(e){if(typeof e=="string")return KV(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?KV(e,t):void 0}}function dft(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function QV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function JV(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?QV(Object(n),!0).forEach(function(r){dft(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):QV(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function fft(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function ex(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function FS(e){return{}.toString.call(e).includes("Object")}function hft(e){return!Object.keys(e).length}function Ly(e){return typeof e=="function"}function mft(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pft(e,t){return FS(t)||Vu("changeType"),Object.keys(t).some(function(n){return!mft(e,n)})&&Vu("changeField"),t}function gft(e){Ly(e)||Vu("selectorType")}function bft(e){Ly(e)||FS(e)||Vu("handlerType"),FS(e)&&Object.values(e).some(function(t){return!Ly(t)})&&Vu("handlersType")}function xft(e){e||Vu("initialIsRequired"),FS(e)||Vu("initialType"),hft(e)&&Vu("initialContent")}function yft(e,t){throw new Error(e[t]||e.default)}var vft={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},Vu=ex(yft)(vft),t1={changes:pft,selector:gft,handler:bft,initial:xft};function wft(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t1.initial(e),t1.handler(t);var n={current:e},r=ex(Nft)(n,t),s=ex(Sft)(n),o=ex(t1.changes)(e),i=ex(Cft)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return t1.selector(u),u(n.current)}function c(u){fft(r,s,o,i)(u)}return[a,c]}function Cft(e,t){return Ly(t)?t(e.current):t}function Sft(e,t){return e.current=JV(JV({},e.current),t),t}function Nft(e,t,n){return Ly(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var jft={create:wft},Eft={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function kft(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),c=0;c<i;c++)a[c]=arguments[c];return t.apply(n,[].concat(s,a))}}}function _ft(e){return{}.toString.call(e).includes("Object")}function Tft(e){return e||eB("configIsRequired"),_ft(e)||eB("configType"),e.urls?(Ift(),{paths:{vs:e.urls.monacoBase}}):e}function Ift(){console.warn(gle.deprecation)}function Mft(e,t){throw new Error(e[t]||e.default)}var gle={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1198
1198
  You are using deprecated way of configuration.
1199
1199