react-semaphor 0.1.443 → 0.1.444

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 (24) hide show
  1. package/dist/chunks/{dashboard-Bd1Quco-.js → dashboard-CJNVq8XI.js} +3 -3
  2. package/dist/chunks/{dashboard-cB3xmTNn.js → dashboard-DxZuqe8t.js} +1 -1
  3. package/dist/chunks/{dashboard-briefing-launcher-C60n8LqW.js → dashboard-briefing-launcher-Bg_SeBV8.js} +2 -2
  4. package/dist/chunks/{dashboard-briefing-launcher-BYMLjZxG.js → dashboard-briefing-launcher-Do6ZcOj4.js} +1 -1
  5. package/dist/chunks/{dashboard-controls-BH_fZYDU.js → dashboard-controls-CYBi_mes.js} +1 -1
  6. package/dist/chunks/{dashboard-controls-ti9Rcel2.js → dashboard-controls-Da9MkPaf.js} +3 -3
  7. package/dist/chunks/{dashboard-json-Bturr634.js → dashboard-json-BtrdGo1U.js} +1 -1
  8. package/dist/chunks/{dashboard-json-Dw_55vSZ.js → dashboard-json-ezLyW7AK.js} +1 -1
  9. package/dist/chunks/edit-dashboard-visual-DEb9MeSM.js +182 -0
  10. package/dist/chunks/{edit-dashboard-visual-DglMds57.js → edit-dashboard-visual-kE6_3R3j.js} +147 -125
  11. package/dist/chunks/{editor-action-buttons-Cxo7_tNG.js → editor-action-buttons-8_CQa8Hb.js} +1 -1
  12. package/dist/chunks/{editor-action-buttons-CRi0fhVW.js → editor-action-buttons-DROkx4PS.js} +1 -1
  13. package/dist/chunks/{report-preferences-dialog-CCvFqH4Q.js → report-preferences-dialog-D5sIaFnb.js} +1 -1
  14. package/dist/chunks/{report-preferences-dialog-TtwdAuNn.js → report-preferences-dialog-Dq7rmN93.js} +1 -1
  15. package/dist/dashboard/index.cjs +1 -1
  16. package/dist/dashboard/index.js +1 -1
  17. package/dist/data-app-builder/index.cjs +1 -1
  18. package/dist/data-app-builder/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/surfboard/index.cjs +1 -1
  22. package/dist/surfboard/index.js +2 -2
  23. package/package.json +1 -1
  24. package/dist/chunks/edit-dashboard-visual-BUc3NBQ4.js +0 -182
@@ -1317,7 +1317,7 @@ prismjs/prism.js:
1317
1317
  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")?`
1318
1318
 
1319
1319
  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 Lz({errorMessage:e}){return l.jsxs("div",{className:"flex items-start gap-2 rounded-control border border-red-300 bg-red-50/60 p-2 text-[12px] text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300",children:[l.jsx(xi,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),l.jsx("span",{className:"whitespace-pre-wrap break-words leading-[1.55]",children:mNt(e)})]})}function pNt({error:e,resetErrorBoundary:t}){return l.jsxs("div",{className:"my-3 space-y-2 rounded-control border border-border/60 bg-muted/20 p-2.5",children:[l.jsx(Lz,{errorMessage:e==null?void 0:e.message}),l.jsx("button",{type:"button",className:"text-[11px] font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",onClick:t,children:"Try again"})]})}function gNt({text:e,files:t}){return l.jsxs(abe,{who:"You",children:[e&&l.jsx("div",{className:"whitespace-pre-line text-[13px] leading-[1.55] text-foreground",children:e}),t&&t.length>0&&l.jsx("div",{className:"flex flex-wrap gap-2 pt-0.5",children:t.map(n=>l.jsx(tCt,{file:n},n.id))})]})}function bNt({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(wCt,{children:JSON.stringify(s,null,2)})]})]})}function lbe(e,t){return!e||e.role!=="assistant"?!1:(e.parts??[]).some(r=>{if(!r)return!1;switch(r.type){case"text":return typeof r.text=="string"&&r.text.trim().length>0;case"reasoning":return typeof r.text=="string"&&r.text.trim().length>0||r.state==="streaming";case"error":return!0;default:return typeof r.type=="string"&&(r.type.startsWith("tool-")||r.type==="dynamic-tool")?Oz(r,t):!1}})}function SK(){return l.jsx("span",{className:"relative grid h-2 w-2 shrink-0 place-items-center",children:l.jsx("span",{className:"absolute inset-0 animate-pulse rounded-full bg-muted-foreground/70"})})}function xNt({status:e,errorMessage:t,activeToolText:n}){return n?l.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[l.jsx(SK,{}),l.jsx("span",{children:n})]}):e==="submitted"||e==="streaming"?l.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[l.jsx(SK,{}),l.jsx("span",{children:e==="submitted"?"Thinking":"Generating"})]}):e==="error"?l.jsx(Lz,{errorMessage:t}):null}function yNt(e){var t;return e?(t=[...e].reverse().find(n=>{var r;return n.role==="assistant"&&((r=n.parts)==null?void 0:r.some(s=>s.type==="text"&&typeof s.text=="string"&&s.text.trim().length>0))}))==null?void 0:t.id:void 0}function vNt({message:e,messageIndex:t,messages:n,showTools:r=!1,onAddToDashboard:s,showSystemMessage:o=!1,handleRun:i,onQuickReply:a,disableQuickReplies:c=!1}){var y,v,S,N;const u=yNt(n),d=e.id===u;if(e.role==="user"){const C=((y=e.parts)==null?void 0:y.filter(I=>I.type==="text"))||[],j=((v=e.parts)==null?void 0:v.filter(I=>I.type==="file"))||[],_=C.map(I=>I.text).join(`
1320
- `).trim(),k=j.map((I,T)=>{var M,A;let E="",D;if((M=I.url)!=null&&M.startsWith("data:")){const P=I.url.match(/data:[^;]+;base64,(.+)/);P&&(E=P[1],(A=I.mediaType)!=null&&A.startsWith("image/")&&(D=I.url))}return{id:`${e.id||t}-file-${T}`,name:I.filename||`File ${T+1}`,size:0,type:I.mediaType||"application/octet-stream",data:E,preview:D}});return l.jsx(gNt,{text:_||void 0,files:k.length>0?k:void 0})}const f=((S=e.parts)==null?void 0:S.filter(C=>C.type==="reasoning"))||[],h=f.length>0,p=f.some(C=>C.state==="streaming"),g=f.filter(C=>C.text&&C.text.trim().length>0),b=h&&(g.length>0||p)?l.jsxs(fu,{className:"space-y-2",defaultOpen:!1,children:[l.jsx(hu,{asChild:!0,children:l.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),l.jsx("span",{className:p?"animate-pulse":"",children:p?"Reasoning":"Show reasoning"}),g.length>1&&l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),l.jsx(mu,{children:l.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((C,j)=>l.jsxs("li",{className:"relative",children:[l.jsx("span",{className:"absolute -left-[15px] top-[3px] grid h-4 w-4 place-items-center rounded-full bg-muted font-mono text-[9px] text-muted-foreground",children:j+1}),l.jsx(mK,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:C.text})]},`${e.id||t}-reasoning-${j}`))})})]},`${e.id||t}-reasoning`):null,x=(N=e.parts)==null?void 0:N.map((C,j)=>{var k;const _=`${e.id||t}-${j}`;switch(C.type){case"text":{const I=typeof C.text=="string"?C.text:JSON.stringify(C.text??"",null,2);if(e.role==="assistant"){const{cleanedText:T,quickReplies:E}=fNt(I),D=T.trim().length>0;return l.jsxs("div",{className:"space-y-2.5",children:[D&&l.jsx(mK,{text:T,handleRun:i,onAddToDashboard:s,messageId:e.id,messages:n}),E.length>0&&a&&d&&l.jsxs("div",{className:"space-y-1.5",children:[E.length>=3&&l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),l.jsx("div",{className:"flex flex-wrap gap-1",children:E.map(({label:M,value:A},P)=>l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-6 max-w-[220px] rounded-control border-border/60 bg-background px-2 text-[11px] font-normal text-foreground/85 transition-colors hover:border-border hover:bg-muted/40 hover:text-foreground disabled:opacity-50",disabled:c,onClick:()=>a(A),children:l.jsx("span",{className:"truncate",children:M})})}),l.jsx(m.TooltipContent,{side:"top",align:"center",children:l.jsx("p",{className:"max-w-xs text-xs",children:A})})]},`${_}-qr-${P}`))})]})]},_)}return e.role==="system"&&o?l.jsx(bNt,{text:I},_):null}case"error":{const I=C,T=I.errorText??I.error??I.message;return l.jsx("div",{className:"my-4",children:l.jsx(Lz,{errorMessage:T})},_)}case"reasoning":return null;default:return((k=C.type)!=null&&k.startsWith("tool-")||C.type==="dynamic-tool")&&Oz(C,r)?l.jsx(Za,{FallbackComponent:({error:I,resetErrorBoundary:T})=>l.jsx(pNt,{error:I,resetErrorBoundary:T}),children:l.jsx(aNt,{part:C,idx:_,messageId:e.id,showTools:r,onAddToDashboard:s,messages:n})},_):null}});return e.role==="assistant"?lbe(e,r)?l.jsxs(abe,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:l.jsxs("div",{className:"space-y-2",children:[b,x]})}const wNt=8,SNt=24,CNt=20;function NNt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function cbe({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i=!1,status:a,errorMessage:c,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:p,scrollToEndSignal:g=0}){const b=w.useRef(null),x=w.useRef(null),y=w.useRef(e.length),v=w.useRef(!1),S=w.useRef(null),N=w.useRef(!1),C=w.useRef(g),[j,_]=w.useState(!0),[k,I]=w.useState(0),[T,E]=w.useState(SNt);C.current!==g&&(C.current=g,N.current=!0);const D=e[e.length-1],M=lbe(D,t),A=NNt(a,c,u,M),P=X_({count:e.length,getScrollElement:()=>b.current,estimateSize:U=>{const R=e[U];return(R==null?void 0:R.role)==="user"?88:180},getItemKey:U=>{const R=e[U];return(R==null?void 0:R.id)||`message-${U}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:wNt,overscan:6,gap:20,paddingEnd:A?T+CNt:0,useAnimationFrameWithResizeObserver:!0,onChange:U=>{const R=U.isAtEnd();_(q=>q===R?q:R),R&&I(0)}}),O=w.useCallback((U="smooth")=>{S.current!==null&&cancelAnimationFrame(S.current),S.current=requestAnimationFrame(()=>{S.current=null,P.scrollToEnd({behavior:U})}),I(0),_(!0)},[P]);w.useLayoutEffect(()=>{v.current||(v.current=!0,O("auto"))},[O]),w.useLayoutEffect(()=>{N.current&&(N.current=!1,O("auto"))},[e.length,g,O]),w.useEffect(()=>{const U=y.current;y.current=e.length,e.length>U&&!P.isAtEnd()&&I(R=>R+e.length-U),e.length===0&&(I(0),_(!0),v.current=!1,N.current=!1)},[e.length,P]);const $=P.getVirtualItems(),V=P.getTotalSize();return w.useEffect(()=>()=>{S.current!==null&&cancelAnimationFrame(S.current)},[]),w.useLayoutEffect(()=>{const U=x.current;if(!U||!A)return;const R=()=>{const W=Math.ceil(U.getBoundingClientRect().height);W>0&&E(F=>F===W?F:W)};if(R(),typeof ResizeObserver>"u")return;const q=new ResizeObserver(R);return q.observe(U),()=>q.disconnect()},[A,a,c,u]),l.jsxs(l.Fragment,{children:[l.jsx(il,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:m.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:l.jsxs("div",{className:"relative w-full",style:{height:V},children:[$.map(U=>{const R=e[U.index];return R?l.jsx("div",{ref:P.measureElement,"data-index":U.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${U.start}px)`},children:l.jsx("div",{className:m.cn("min-w-0",f),children:l.jsx(vNt,{message:R,messageIndex:U.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i})})},U.key):null}),A&&l.jsx("div",{ref:x,className:m.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max(V-T,0)}px)`},children:l.jsx("div",{className:m.cn("min-w-0",f),children:l.jsx(xNt,{status:a,errorMessage:c,activeToolText:u})})})]})}),!j&&l.jsxs("button",{type:"button",onClick:()=>O("smooth"),"aria-label":"Scroll to latest",className:m.cn("absolute right-4 z-10 inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-[11px] text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.08)] transition-colors hover:bg-muted/40",p),children:[l.jsx(ro,{className:"h-3 w-3"}),"Latest",k>0&&l.jsx("span",{className:"grid h-4 min-w-[16px] place-items-center rounded-full bg-foreground px-1 font-mono text-[9px] tabular-nums text-background",children:k>9?"9+":k})]})]})}function jNt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";const t=e;return(typeof t.userSql=="string"?t.userSql:"")||(typeof t.sourceSql=="string"?t.sourceSql:"")||(typeof t.sql=="string"?t.sql:"")}const kNt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function _Nt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(m.isDevEnv),[u,d]=w.useState(!1),[f,h]=w.useState("auto"),[p,g]=w.useState(!1),[b,x]=w.useState(!1),[y,v]=w.useState(0),S=n??b,{isLocalDev:N,isConsoleMode:C}=Vm(),j=N||C||a,_=w.useRef(null);m.useDashboardStore(ne=>ne.dashboard.aiScopeTables),m.useDashboardStore(ne=>ne.isDashboardEditing);const k=m.useDashboardStore(ne=>ne.selectedSheetId),{setDataSource:I}=m.useEditorActions(),{setSelectedFrameId:T,setIsDashboardEditing:E}=m.useDashboardActions(),D=U$(),{clearAssistantMessageContexts:M}=m.useAIActions(),{clearQueue:A}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:O}=m.useFileActions(),$=m.useFileAttachments("dashboard"),V=m.useEditorStore(ne=>ne.card.dataSource),{assistantProfile:U}=Nge(),R=m.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{selectedEntities:q,applyDashboardDefaultEntities:W}=XI("dashboard"),{sendMessage:F,isLoading:Z,messages:K,setMessages:Y,status:X,stop:z,errorMessage:B,clearError:H}=OSt({dynamicVisualMode:f}),L=w.useCallback(()=>{v(ne=>ne+1)},[]),G=w.useCallback(ne=>{r==null||r(ne),n===void 0&&x(ne)},[n,r]),J=w.useCallback(()=>{G(!S)},[S,G]);w.useEffect(()=>{if(!S)return;function ne(he){he.key==="Escape"&&G(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[S,G]);const[oe,Q]=w.useState(""),ae=ne=>{Q(ne.target.value)};async function ie({sql:ne,cardTitle:he,connectionId:_e,cardType:Le,python:Ue,cardConfig:je,dataSource:Xe,customVisualPreferences:Ze,visualizationMode:at,dynamicCardPreferences:Be}){if(!k)return;const lt=at==="dynamic",Te=Zl.hasValidCardConfig(je),nt=_e||(Xe==null?void 0:Xe.connectionId)||"",Oe=Xe?{...Xe,connectionId:nt||Xe.connectionId,connectionType:Xe.connectionType||"",mode:Xe.mode||"database",selectedEntities:Xe.selectedEntities||[]}:nt?{connectionId:nt,connectionType:"",mode:"database",selectedEntities:[]}:eb,qe=!(Te&&(!lt||(Be==null?void 0:Be.provenance)==="card-config"||(Be==null?void 0:Be.provenance)==="query_spec")),Ae=qe?jNt(ne):"",Qe=qe?Ue:"",ct={id:m.v4(),title:he||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Le==="horizontalBar"?"y":"x"},...lt&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Le,sql:Ae,python:Qe,dataSource:Oe,config:je,connectionId:nt,visualizationMode:at,dynamicCardPreferences:Be,customCardPreferences:Ze?{url:Ze.url,componentName:Ze.componentName,pluginChartType:Ze.pluginChartType,settings:Ze.settings,type:"component"}:void 0},It={id:m.v4(),cards:[ct],activeCardId:ct.id};try{await D(k,It,"end"),E(!0),T(It.id)}catch(yt){console.error("Failed to add assistant visual to dashboard:",yt),it.error(yt instanceof Error?yt.message:"Failed to prepare semantic metadata for the new visual")}}const le=ne=>{ne.preventDefault();const he=oe.trim();if(!he&&$.length===0)return;const _e=[];he&&_e.push({type:"text",text:he}),$.forEach(Le=>{Le.data&&_e.push({type:"file",mediaType:Le.type,filename:Le.name,url:`data:${Le.type};base64,${Le.data}`})}),F({role:"user",parts:_e}),Q(""),P("dashboard"),L()};w.useEffect(()=>{var ne;e&&((ne=_.current)==null||ne.focus())},[e]),zge({assistantType:"dashboard",status:X,isLoading:Z,sendMessage:F});const{hasActiveTools:ue,activeToolText:fe}=Bge(K);function pe(ne){const he={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};F(he),L()}function ge(ne){F({role:"user",parts:[{type:"text",text:ne}]}),L()}function de(ne){F({role:"user",parts:[{type:"text",text:ne}]}),L()}const ye=w.useCallback(async()=>{const ne=JSON.stringify(K??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),it.success("Conversation copied")}catch(he){console.error("Failed to copy conversation",he),it.error("Unable to copy conversation")}},[K]),ce=(oe==null?void 0:oe.length)===0&&(K==null?void 0:K.filter(ne=>ne.role==="user").length)===0;function re(){return l.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:l.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ee(){return l.jsxs(Ys,{children:[l.jsx(Zs,{asChild:!0,children:l.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(ym,{className:"size-3.5"})})}),l.jsxs(Es,{align:"end",children:[l.jsx($a,{children:"Options"}),l.jsx(Sa,{}),l.jsx(Gu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(Gu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(Gu,{checked:u,onCheckedChange:d,children:"System Message"}),(N||C)&&l.jsxs(l.Fragment,{children:[l.jsx(Sa,{}),l.jsx($a,{children:"Dynamic Visuals"}),l.jsx(Gu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(Gu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(Gu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const se=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("relative flex h-full grow flex-col break-words bg-background",S&&"rounded-card border border-border/60 shadow-xl"),children:[l.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[re(),R&&l.jsxs("button",{type:"button",onClick:R,className:"inline-flex h-6 items-center gap-1 rounded-[4px] border border-border/60 bg-muted/40 px-1.5 text-[11px] text-muted-foreground transition-colors hover:border-border hover:text-foreground",title:"Edit assistant profile",children:[l.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),l.jsx("span",{className:"max-w-[180px] truncate",children:(U==null?void 0:U.name)||"Default profile"})]}),l.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[C&&ee(),j&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 px-1.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:ye,children:"Copy Conversation"}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:S?"Exit fullscreen":"Expand",onClick:J,children:S?l.jsx(Ot.Minimize2,{className:"h-3.5 w-3.5"}):l.jsx(Ot.Maximize2,{className:"h-3.5 w-3.5"})}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"New chat",onClick:()=>{const ne=K.filter(he=>he.role==="assistant").map(he=>he.id).filter(he=>!!he);Y([]),A("dashboard"),H(),M(ne)},children:l.jsx(lO,{className:"h-3.5 w-3.5"})}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"Close",onClick:()=>{t(!1)},children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]})]}),l.jsx(cbe,{messages:K,showTools:a,showSystemMessage:u,onAddToDashboard:ie,onQuickReply:de,disableQuickReplies:Z,status:X,errorMessage:B,activeToolText:Z&&ue?fe:void 0,className:m.cn(S?"px-6 py-5":"px-3 py-3"),rowContentClassName:m.cn(S&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),l.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!U&&ce&&l.jsx(ope,{onClick:pe,placeholders:kNt}),ce&&U&&l.jsx(jge,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:ge}),l.jsx($ge,{assistantType:"dashboard"}),l.jsx(Pz,{ref:_,setInput:Q,stop:z,input:oe,handleInputChange:ae,handleSubmit:ne=>{le(ne)},isLoading:Z,status:X,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(Rz,{incomingSelectedEntities:q,open:p,onOpenChange:g,dataSource:V||eb,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ne=>W()})]});return S&&s?Dr.createPortal(l.jsx(Vb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background/95 px-4 pb-4 pt-[calc(var(--app-header-height,15px)+0.5rem)] backdrop-blur-sm",children:l.jsx("div",{className:"flex h-full w-full",children:se})}),s):se}function INt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=ice(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(p){if(TNt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),it.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=ENt(p);if(g!=null&&g.id){const b=rce(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),it.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function TNt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function ENt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function ube(e){const t=w.useCallback(o=>`semaphor-default-sheet-${o}`,[]),n=w.useCallback(()=>{if(!e)return null;try{const o=t(e);return localStorage.getItem(o)}catch(o){return console.error("Error reading default sheet preference:",o),null}},[e,t]),r=w.useCallback(o=>{if(!(!e||!o))try{const i=t(e);localStorage.setItem(i,o)}catch(i){console.error("Error saving default sheet preference:",i)}},[e,t]),s=w.useCallback(()=>{if(e)try{const o=t(e);localStorage.removeItem(o)}catch(o){console.error("Error clearing default sheet preference:",o)}},[e,t]);return{getDefaultSheetId:n,setDefaultSheetId:r,clearDefaultSheetId:s}}function DNt(e,t){switch(e.interactionMode){case"drillToDetail":MNt(e,t);break;case"drillThrough":ANt(e,t);break;case"drillToURL":RNt(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 MNt(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 ANt(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 RNt(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 PNt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Jo,{children:[l.jsx(Ts,{children:i||"Insight Detail"}),l.jsx(Ks,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(dce,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Qde,{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 FNt(){const e=m.useInteractionStore(N=>N.interactionStates),t=m.useInteractionStore(N=>N.setInteractionState),n=m.useInteractionStore(N=>N.clearLastInteractionEvent),r=m.useInteractionStore(N=>N.replaceCardWithInsight),s=m.useInteractionStore(N=>N.setPendingDrillThrough),o=m.useInteractionStore(N=>N.pendingDrillThrough),i=m.useInteractionStore(N=>N.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=_m(),d=m.useDashboardStore(N=>N.dashboard),f=m.useDashboardStore(N=>N.filterValues),{data:h,isLoading:p}=Kde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=w.useState({open:!1,insightId:""}),x=Jde(g.insightId,{enabled:g.open&&!!g.insightId}),y=w.useRef(new Set),v=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:N,filters:C,contextMode:j})=>{b({open:!0,insightId:N,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:j})},replaceCardContent:({cardId:N,insightId:C,filters:j,contextMode:_})=>{r(N,C,j,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:N,contextMode:C,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k})=>{const I={filters:N},T={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[I]},E={...m.createInitialInteractionState(),appliedClickFilters:[T],contextMode:C,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k};t(m.DRILL_CONTEXT_CARD_ID,E)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([N,C])=>{if(C!=null&&C.lastInteractionEvent){const j=C.lastInteractionEvent,_=`${N}-${j.interactionMode}-${j.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{DNt(j,v)}catch(k){console.error("Error executing interaction event:",k)}finally{n(N),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,v]),w.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(N){console.error("[DrillThrough] Error during automatic navigation:",N),i()}},[o,h,p,u,c,i]);const S=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(PNt,{open:g.open,onOpenChange:S,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&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-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function ONt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=LNt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function LNt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function $Nt(e){return e?`Back to ${e}`:"Back"}function zNt(){var y,v,S,N,C;const e=m.useInteractionStore(j=>j.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(j=>j.actions.goBackFromDrill),n=m.useDashboardStore(j=>j.actions.clearDrillContext),{selectDashboard:r}=_m(),[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 j=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((N=(S=(v=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:v.filterGroups)==null?void 0:S[0])==null?void 0:N.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||!((C=e.appliedClickFilters)!=null&&C.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(j){console.error("[DrillBack] Error during back navigation:",j)}},g=()=>{n()},b=j=>{j.target.closest("button")||(a(!0),c.current={x:j.clientX-s.x,y:j.clientY-s.y})};ONt(f);const x=$Nt(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:b,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((j,_)=>{const k=j.field.label||j.field.name,I=String(j.value);return l.jsxs($s,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",I]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Ce.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(Ov,{className:"mr-2 h-4 w-4"}),x]})})]})})}function BNt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function VNt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=Xb({id:`filter:${e.id}`,disabled:n||!t}),x={transform:Ki.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(j$,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const CK="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",HNt=[];function dbe({open:e,onOpenChange:t}){const[n,r]=w.useState(!1),[s,o]=w.useState(!1),[i,a]=w.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(Y=>{var X;return(X=Y.dashboard)==null?void 0:X.sheets}),u=m.useDashboardStore(Y=>Y.dashboard),d=m.useDashboardStore(Y=>Y.dashboardInputValues),f=m.useDashboardStore(Y=>Y.filterValues),h=m.useDashboardStore(Y=>Y.controlValues),p=m.useDashboardStore(Y=>Y.inlineFilterValuesMap),g=m.useDashboardStore(Y=>Y.cardControlValuesMap),b=m.useDashboardStore(Y=>Y.selectedSheetId),x=m.useDashboardStore(Y=>Y.selectedSheetId?Y.documentInputRuntimeBySheetId[Y.selectedSheetId]:void 0),y=m.useDashboardStore(Y=>Y.isDownloadingPdf),v=m.useDashboardStore(Y=>Y.reportContext),{authToken:S,tokenProps:N}=Tt(),C=c==null?void 0:c.find(Y=>Y.id===b),j=w.useMemo(()=>m.getDashboardExportSheets(c),[c]),_=m.isDocumentSheet(C),k=_&&C?C.document:void 0,I=w.useMemo(()=>_&&C?Jb(u,C.id):[],[C,_,u]),T=I.length>0,E=w.useMemo(()=>_&&C?Rme(u,C.id):!1,[C,_,u]),D=w.useMemo(()=>T?I.map(iS):(k==null?void 0:k.inputs)||HNt,[k,I,T]),M=v==null?void 0:v.calendar.tz,A=w.useMemo(()=>Rhe(D),[D]),P=w.useMemo(()=>Mhe(D,M),[D,M]),O=w.useMemo(()=>Ahe(D),[D]),$=x?x.filterValuesByInputId:P,V=x?x.controlValuesByInputId:O,U=w.useMemo(()=>_?E&&C&&k?oQ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:k.sections.map(Y=>Y.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:M}):Ohe(D,$,V,A,A):[],[k,D,C,_,u,g,h,f,p,d,V,$,A,M,E]),R=!!C,q=j.length>0,W=((c==null?void 0:c.length)||0)>1||_,F=i.sheetSelection==="current"&&(!R||_&&U.length>0)||i.sheetSelection==="all"&&!q;w.useEffect(()=>{e&&i.sheetSelection==="all"&&!q&&a(Y=>({...Y,sheetSelection:"current"}))},[q,e,i.sheetSelection]);const Z=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function K(){if(y){it.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){it.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!R){it.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!q){it.error("No dashboard sheets are available to export");return}o(!0);const Y=i.sheetSelection==="current"&&_,X=Y?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",z=it.loading(X);try{if(Y){if(!k||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){it.dismiss(z),it.error(`Set ${U.join(", ")} before exporting`);return}const H=new Date().toISOString(),L=E?iQ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:k.sections.map(G=>G.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:H,timezone:M}).snapshot:void 0;await M5(N.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:k.page.size,orientation:k.page.orientation,timezone:M,password:i.protectPdf?i.password:void 0,inputSnapshot:L,...L?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:$,controlValuesByInputId:V,generatedAt:H}}})}else{const H=Ete();await hQ(N.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,H)}it.dismiss(z);const B=Y?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";it.success(B,{duration:2e3}),Z()}catch(B){it.dismiss(z),it.error("Failed to download PDF",{description:i_(B,"Please try again or contact support."),descriptionClassName:o_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",B)}finally{o(!1)}}return l.jsx(Gs,{open:e,onOpenChange:Y=>{if(!Y){Z();return}t(!0)},children:l.jsxs(Is,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(Jo,{children:[l.jsx(Ts,{className:"text-[15px]",children:_?"Export document":"Export dashboard"}),l.jsx(Ks,{className:"text-[13px] leading-5",children:_?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[W&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:CK,children:"Export scope"}),l.jsxs(Ja,{value:i.sheetSelection,onValueChange:Y=>a({...i,sheetSelection:Y}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!R&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(Us,{value:"current",id:"scope-current",disabled:!R}),_?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!q&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(Us,{value:"all",id:"scope-all",disabled:!q}),"Dashboard sheets (",j.length," ",j.length===1?"sheet":"sheets",")"]})]}),_&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Tn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:Y=>{a({...i,protectPdf:Y,password:Y?i.password:""}),Y||r(!1)}}),l.jsx(Bv,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:CK,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:Y=>a({...i,password:Y.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:Y=>{Y.key==="Enter"&&i.password&&K()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(kk,{className:"h-3.5 w-3.5"}):l.jsx(Ot.Eye,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Qa,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:Z,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:K,disabled:s||y||F,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(gu,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function fbe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=w.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(gu,{className:m.cn("size-4",e)})}),l.jsx(dbe,{open:i,onOpenChange:a})]})}function NK(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function UNt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=Xb({id:`control:${e.id}`,disabled:!n}),d={transform:Ki.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Xhe,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function jK(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function kK(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function qNt(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return kK(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=kK(t,n).filter(a=>!o.has(a));return[...s,...i]}function WNt(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function GNt(e){return Wh(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>Wh(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function AM(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function KNt(e){return hbe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function hbe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=WNt(e.dashboard,t);return Bk(rb({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!GNt({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function YNt(e,t){return"toolbar"}function ZNt(){const e=ku("interactive"),t=m.useDashboardStore(B=>B.selectedSheetId),n=m.useDashboardStore(B=>B.dashboard.filters),r=m.useDashboardStore(B=>B.dashboard.filterLayout),s=m.useDashboardStore(B=>B.isDashboardEditing),o=m.useDashboardStore(B=>B.controlValues),i=m.useDashboardStore(B=>B.filterValues);m.useDashboardStore(B=>B.filteringCards);const a=m.useDashboardStore(B=>B.inlineFilterValuesMap),c=m.useDashboardStore(B=>B.dashboardInputValues),u=m.useInteractionStore(B=>B.clearAllClickFilters),d=m.useInteractionStore(B=>Object.entries(B.interactionStates).reduce((H,[L,G])=>{var J;return L===m.DRILL_CONTEXT_CARD_ID?H:H+(((J=G.appliedClickFilters)==null?void 0:J.length)??0)},0)),f=m.useDashboardStore(B=>B.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:v,setFilteringCards:S,upsertDashboardInput:N}=m.useDashboardActions(),C=tT(Xg(Yb,{activationConstraint:{distance:5}})),j=m.useDashboardStore(B=>B.dashboard),_=KNt({dashboard:j,selectedSheetId:t}).filter(B=>YNt(B.filter)==="toolbar"),k=hbe({dashboard:j,selectedSheetId:t}),I=_.map(B=>B.filter),T=new Map(_.map(B=>[`filter:${B.filter.id}`,B])),E=kXe(j),D=E.filter(B=>!B.hidden&&nv(B)==="toolbar"),M=E.filter(B=>!B.hidden&&nv(B)==="advanced"),A=qNt(r==null?void 0:r.toolbarItemOrder,I,D),P=new Map(I.map(B=>[`filter:${B.id}`,B])),O=new Map(D.map(B=>[`control:${B.id}`,B]));function $(B){const{active:H,over:L}=B;if(!L||H.id===L.id)return;const G=String(H.id),J=String(L.id),oe=A.findIndex(ge=>ge===G),Q=A.findIndex(ge=>ge===J);if(oe===-1||Q===-1)return;const ae=Zb(A,oe,Q);y({toolbarItemOrder:ae});const ie=new Set((n||[]).map(ge=>ge.id)),le=A.filter(ge=>ge.startsWith("filter:")).map(ge=>ge.replace("filter:","")).filter(ge=>ie.has(ge)),ue=ae.filter(ge=>ge.startsWith("filter:")).map(ge=>ge.replace("filter:","")).filter(ge=>ie.has(ge)),fe=A.filter(ge=>ge.startsWith("control:")).map(ge=>ge.replace("control:","")),pe=ae.filter(ge=>ge.startsWith("control:")).map(ge=>ge.replace("control:",""));h(NK(n||[],le,ue)),g(NK(j.controls||[],fe,pe))}const V=(r==null?void 0:r.toolbarWrap)??!1,U=(r==null?void 0:r.showDownloadButton)??!1,R=k.filter(AM),q=k.filter(B=>{if(AM(B))return!1;const H=m.getDashboardInputRuntimeSlot(c,B,{sheetId:t});return(H==null?void 0:H.status)==="set"||(H==null?void 0:H.status)==="cleared"}),W=new Set([...R,...q].map(B=>B.filter.id)),F=(i==null?void 0:i.filter(B=>!W.has(B.filterId)&&jK(B)).length)??0,Z=[...R,...q],K=Z.filter(B=>{const H=m.hydrateAuthoredDashboardInputSlot({dashboard:j,input:B,runtimeValues:c,target:{sheetId:t}});return(H==null?void 0:H.status)==="set"&&H.value.kind==="filter"&&jK(H.value.filterValue)}).length,Y=a?Object.values(a).reduce((B,H)=>B+((H==null?void 0:H.length)??0),0):0,X=F+K+Y+d,z=()=>{v([]),Z.forEach(B=>{p(B,{sheetId:t})}),S([]),u(),a&&Object.entries(a).forEach(([B,H])=>{H==null||H.forEach(L=>{f(B,L.filterId)})})};return!I.length&&!D.length&&!M.length&&!U&&X===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(eS,{sensors:C,collisionDetection:Xw,onDragEnd:$,children:l.jsxs("div",{className:m.cn("flex items-center",V?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(tS,{items:A,strategy:T4,children:l.jsx(IF,{className:"gap-3 pr-0",wrap:V,children:A.map(B=>{const H=P.get(B);if(H){const G=T.get(B),J=G&&AM(G);return l.jsx(VNt,{filter:H,isEditing:s,storageOptions:J?{storageTarget:"dashboardInput",dashboardInput:G,sheetId:t??void 0}:void 0,inputVariableName:J?G.variableName:void 0,onUpdateFilter:J?(oe,Q)=>{N({...G,variableName:(Q==null?void 0:Q.variableName)||G.variableName,filter:oe})}:void 0,onRemoveFilter:J?()=>{v((i||[]).filter(oe=>oe.filterId!==H.id)),b(G.id)}:void 0},B)}const L=O.get(B);return L?l.jsx(UNt,{control:L,value:o==null?void 0:o[L.id],isEditing:s,onChange:G=>x(L.id,G)},B):null})})}),M.length>0&&l.jsx(Sce,{title:"",controls:M,values:o,onChange:(B,H)=>x(B.id,H),immediatePlacement:"toolbar",advancedLabel:"More controls"}),X>0&&l.jsxs("button",{type:"button",onClick:z,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(Ce.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:X})]}),U&&l.jsx("div",{className:m.cn(X>0?"ml-1.5":"ml-auto"),children:l.jsx(fbe,{})})]})})})}function mbe(){var de,ye;const{showAssistant:e,tokenProps:t,renderMode:n}=Tt(),r=BNt((de=t.config)==null?void 0:de.showDashboardAssistant,e),{preferences:s}=Vm(),o=(ye=s==null?void 0:s.cardDisplay)==null?void 0:ye.mode,i=nf(o),a=jX({displayMode:o,renderMode:n}),c=w.useRef(null),u=w.useRef(null),[d,f]=w.useState(!1),{handleDragStart:h,isDraggingRef:p,getStyle:g,getPositionClasses:b}=_bt({initialPosition:"bottom-right"}),x=Th(ce=>ce.setFullscreen),y=Th(ce=>ce.setPanelOpen),v=Th(ce=>ce.setContainer),S=ure("dashboard"),N=dre(),C=fre("dashboard"),j=S.isOpen,_=N==="dashboard",k=m.useDashboardStore(ce=>ce.isVisualEditing),I=m.useDashboardStore(ce=>ce.themeStyle),T=Fu(),E=m.useDashboardStore(ce=>{var re;return(re=ce.dashboard)==null?void 0:re.sheets}),D=m.useDashboardStore(ce=>ce.showFilters),M=m.useDashboardStore(ce=>ce.isDashboardEditing),A=m.useDashboardStore(ce=>ce.selectedSheetId),P=E==null?void 0:E.find(ce=>ce.id===A),O=m.useDashboardStore(ce=>{var re,ee,se;return(se=(ee=(re=ce.dashboard)==null?void 0:re.sheets)==null?void 0:ee.find(ne=>ne.id===ce.selectedSheetId))==null?void 0:se.kind}),$=m.useDashboardStore(ce=>{var re,ee;return((ee=(re=ce.dashboard)==null?void 0:re.summary)==null?void 0:ee.position)||"top"}),V=O==="document",U=m.useDashboardStore(ce=>{var re;return(re=ce.dashboard)==null?void 0:re.id}),{getDefaultSheetId:R,setDefaultSheetId:q,clearDefaultSheetId:W}=ube(U),[F,Z]=w.useState(null),{setSelectedSheetId:K,setSheetTitle:Y,addSheet:X,setSheets:z}=m.useDashboardActions();INt(u);const{setActiveAssistantType:B}=m.useAIActions();w.useEffect(()=>{if(U){const ce=R();Z(ce)}},[U,R]),w.useEffect(()=>{j?B("dashboard"):N==="dashboard"&&x(null)},[j,B,N,x]),w.useEffect(()=>{var ce;j||(ce=c.current)==null||ce.resize(0)},[j]);function H(ce){var re,ee;ce?((re=c.current)==null||re.resize(40),y("dashboard",!0),x("dashboard"),B("dashboard")):(y("dashboard",!1),x(null),(ee=c.current)==null||ee.resize(0),B(null))}function L(ce="dashboard"){const re={id:m.v4(),title:ce==="document"?"New Document":"New Sheet",...ce==="document"?{kind:ce,document:m.createDefaultDocumentDefinition()}:{}};X(re),K(re.id)}function G(ce,re){if(!U)return;F===ce?(W(),Z(null),it.success("Default sheet cleared")):(q(ce),Z(ce),it.success(`"${re}" set as default sheet`))}function J(ce){var re;ce<1?(y("dashboard",!1),x(null),B(null),(re=c.current)==null||re.resize(0)):(j||y("dashboard",!0),B("dashboard"))}function oe(){return(I==null?void 0:I.canvasTheme)==="muted"||!(I!=null&&I.canvasTheme)?"hsl(var(--semaphor-muted))":(I==null?void 0:I.canvasTheme)==="clear"?"":I==null?void 0:I.canvasTheme}const Q=(ce,re)=>{ce.dataTransfer.setData("tabIndex",re.toString())},ae=ce=>{ce.preventDefault()},ie=(ce,re)=>{const ee=ce.dataTransfer.getData("tabIndex");if(ee===re.toString())return;const se=Array.from(E||[]),[ne]=se.splice(parseInt(ee),1);se.splice(re,0,ne),z(se)},le=r===!0&&!i&&!j&&!k&&!D;function ue(){if(E&&E.length>1||M)return l.jsx("div",{className:"relative flex w-full items-stretch border-b border-border",children:l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[E==null?void 0:E.map((ce,re)=>{const ee=A===ce.id,se=F===ce.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:ne=>Q(ne,re),onDragOver:ae,onDrop:ne=>ie(ne,re),onClick:()=>K(ce.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:ce.id,children:[ce.kind==="document"&&l.jsx(Qo,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(Tj,{enabled:M&&ee,text:ce.title,onSave:ne=>Y(ce.id,ne),children:ce.title},ce.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":se?"Clear default sheet":"Set as default sheet",title:se?"Clear default sheet":"Set as default sheet",onClick:ne=>{ne.stopPropagation(),G(ce.id,ce.title||"Sheet")},onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),ne.stopPropagation(),G(ce.id,ce.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ee||se?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(DY,{className:m.cn("h-3 w-3 transition-colors",se?"fill-current text-amber-500":"text-muted-foreground")})}),M&&ee&&E.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:ne=>{ne.stopPropagation(),f(!0)},onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),ne.stopPropagation(),f(!0))},children:l.jsx(Ce.X,{className:"h-3 w-3"})})]},ce.id)}),M&&l.jsxs(Ys,{children:[l.jsx(Zs,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(Ar,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(Es,{align:"start",className:"w-48",children:[l.jsxs(Nn,{onSelect:()=>L("dashboard"),children:[l.jsx(Hh,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(Nn,{onSelect:()=>L("document"),children:[l.jsx(Qo,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})})}function fe(){return l.jsx("div",{ref:u,style:{},className:"h-full min-h-0 grow",children:E==null?void 0:E.map(ce=>l.jsx(m.TabsContent,{style:{backgroundColor:oe(),...T.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:ce.id,children:l.jsx(cG,{sheet:ce})},ce.id))})}function pe(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",I==null?void 0:I.dashboardTabsContainer),onValueChange:ce=>{K(ce)},value:A||void 0,children:[ue(),$==="top"&&!V&&l.jsx(UP,{}),A&&!V&&l.jsx(ZNt,{}),V?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:fe()}):l.jsx(il,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:fe()}),$==="bottom"&&!V&&l.jsx(UP,{}),l.jsx(Ibt,{open:d,setOpen:f})]})}const ge=w.useCallback(ce=>{v("dashboard",ce)},[v]);return E?a&&A&&!V?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):a&&V&&P?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(cG,{sheet:P})}):l.jsxs(l.Fragment,{children:[l.jsx(FNt,{}),l.jsx(zNt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(spe,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",_&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(AF,{children:pe()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(kbt,{open:j,onTabClick:H,withHandle:!0,disabled:!j}),l.jsx(AF,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:J,defaultSize:j?40:0,ref:c,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(_Nt,{open:j,setOpen:H,isFullscreen:_,onFullscreenChange:ce=>x(ce?"dashboard":null),fullscreenContainer:C})})})]})]}),l.jsx("div",{ref:ge,className:m.cn("absolute inset-0",!_&&"pointer-events-none")}),le&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",b().horizontal,b().vertical),style:g(),children:l.jsx(m.Button,{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:()=>{p.current||H(!0)},onMouseDown:h,onTouchStart:h,title:"Open Assistant (drag to move)",children:l.jsx(Pxe,{className:"h-5 w-5"})})})]})]}):null}function XNt(e=[]){const t=w.useRef(null),n=w.useRef(null),r=w.useRef(null),[s,o]=w.useState(),i=w.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return w.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function QNt({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Vm(),r=nf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=XNt([t,o,r]);return w.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(bi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(N$,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(Ce.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function JNt(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":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(QNt,{filter:r}),l.jsx(jI,{filter:r})]},r.id))}):null}function ejt(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(JNt,{}),l.jsx(mbe,{})]})})}function pbe({children:e,preferences:t}){const{currentUser:n}=ti(),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(ace.Provider,{value:r,children:l.jsx(FI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}const gbe=w.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=w.useId(),f=w.useMemo(()=>tjt(d),[d]),{theme:h}=pO(),p=njt(h),g=w.useMemo(()=>s??pu.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=w.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=w.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(Vb,{...c,ref:u,className:i,style:a,children:o})})});gbe.displayName="AppearanceProvider";function tjt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function njt(e){const t=cN(e),[n,r]=w.useState(()=>rjt());return w.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function rjt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const bbe=w.createContext({openBrandStudioPreview:()=>{}}),sjt=bbe.Provider;function ojt(){return w.useContext(bbe)}function ijt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=cN(t),[o,i]=w.useState(()=>ajt(n)||s),a=w.useCallback(u=>{const d=cN(u);ljt(n,d),i(d)},[n]),c=w.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(PY.Provider,{...r,value:c,children:e})}function ajt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=cN(t,"system");return n===t?n:null}catch{return null}}function ljt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const cjt=w.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function $z({appearance:e,children:t}){var E,D;const{authToken:n,id:r,tokenProps:s}=Tt(),o=fS(),i=(E=o.data)==null?void 0:E.organizationAppearance,a=(D=s.config)==null?void 0:D.appearance,[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,p]=w.useState(null),[g,b]=w.useState(null),[x,y]=w.useState(null),v=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,S=Gn({queryKey:Hde({resourceType:cs.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:M=>(M==null?void 0:M.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});w.useEffect(()=>{i!==void 0&&y({scopeKey:v,appearance:i})},[i,v]),w.useEffect(()=>{S.data!==void 0&&y({scopeKey:v,appearance:S.data})},[S.data,v]);const N=(x==null?void 0:x.scopeKey)===v?x.appearance:null,C=i!==void 0?i:S.data!==void 0?S.data:N,j=w.useMemo(()=>pu.resolveAppearance({organizationAppearance:C,tokenAppearance:a,reactAppearance:e}),[e,C,a]),_=w.useCallback(()=>{f(g??h??j),u(!0)},[g,h,j]),k=w.useCallback(()=>{u(!1)},[]);w.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const I=w.useMemo(()=>({openBrandStudioPreview:_}),[_]),T=g??h??e;return l.jsx(ijt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(sjt,{value:I,children:l.jsx(gbe,{organizationAppearance:C,tokenAppearance:a,reactAppearance:T,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(w.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(cjt,{appearance:d,onDraftChange:b,onSave:M=>{p(M),b(M),f(M)},onCancel:k})})})]})})})})}function ujt(e=2e3,t=500){const n=c0e(),[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 zz({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=ujt(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":""})}const djt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BH_fZYDU.js"))),fjt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BUc3NBQ4.js"))),hjt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-Dw_55vSZ.js")));function mjt({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(a=>a.isVisualEditing),s=m.useDashboardStore(a=>a.showDashboardJSON),{appearance:o,preferences:i}=n;return l.jsx(Za,{FallbackComponent:RI,children:l.jsx(Gz,{dashboardProps:n,children:l.jsxs(GI,{children:[l.jsx(zz,{componentType:"surfboard",componentId:n.id}),l.jsxs($z,{appearance:o,children:[l.jsx(L0e,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(pbe,{preferences:i,children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(hjt,{})}),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(djt,{})}),l.jsx("div",{className:"flex grow overflow-hidden",children:l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(Kz,{...n,type:"dashboard",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(fjt,{})}),l.jsx(ejt,{})]})})})]})]})]})]})})})}const _K=[{value:"en-US",label:"English (United States)"},{value:"en-GB",label:"English (United Kingdom)"},{value:"de-DE",label:"German (Germany)"},{value:"fr-FR",label:"French (France)"},{value:"es-ES",label:"Spanish (Spain)"},{value:"it-IT",label:"Italian (Italy)"},{value:"nl-NL",label:"Dutch (Netherlands)"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"ja-JP",label:"Japanese (Japan)"},{value:"en-IN",label:"English (India)"},{value:"en-NZ",label:"English (New Zealand)"},{value:"mi-NZ",label:"Māori (New Zealand)"}],xbe=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","INR","BRL","KWD"]),pjt=iu.getSupportedCurrencyCodes(),gjt=pjt.filter(e=>!xbe.has(e));function IK(e){switch(e){case"viewer_tenant":return"tenant";case"viewer_organization":return"organization";case"session_initial":return"embedded";case"system_default":return"system";default:return"inherited"}}function bjt({value:e,inherited:t,inheritedSources:n,onChange:r,disabled:s}){const o=w.useId(),a=(e.locale===void 0?void 0:iu.canonicalizeSupportedLocale(e.locale))??t.locale,c=e.defaultCurrency??t.defaultCurrency,u=new Intl.NumberFormat(a,{style:"currency",currency:c}).format(1e3);return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{htmlFor:o,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Locale"}),l.jsxs(m.Select,{value:e.locale??"inherit",disabled:s,onValueChange:d=>r({...e,locale:d==="inherit"?void 0:d}),children:[l.jsx(m.SelectTrigger,{id:o,size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:"inherit",children:["Use ",IK(n.locale)," default —"," ",t.locale]}),e.locale&&!_K.some(d=>d.value===e.locale)&&l.jsx(m.SelectItem,{value:e.locale,children:e.locale}),_K.map(d=>l.jsxs(m.SelectItem,{value:d.value,children:[d.label," — ",d.value]},d.value))]})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default currency"}),l.jsxs(m.Select,{value:e.defaultCurrency??"inherit",disabled:s,onValueChange:d=>r({...e,defaultCurrency:d==="inherit"?void 0:d}),children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:"inherit",children:["Use ",IK(n.defaultCurrency)," default —"," ",t.defaultCurrency]}),[...xbe].map(d=>l.jsx(m.SelectItem,{value:d,children:d},d)),gjt.map(d=>l.jsx(m.SelectItem,{value:d,children:d},d))]})]})]}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2",children:[l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsx("p",{className:"mt-1 text-[14px] font-medium text-foreground",children:u}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Currency display only; values are not converted."})]})]})}function xjt(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=cs.DASHBOARD,userType:s,tenantId:o}=e,i=w.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:c,isError:u}=$I(i),d=sat(r,n);return{allUsers:a,isLoadingUsers:c,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function yjt({open:e,onOpenChange:t,title:n,subtitle:r,topContent:s,children:o}){return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{showCloseButton:!1,className:"z-[51] flex max-h-[80vh] w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:rounded-[6px]",children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(EY,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx(Ts,{className:"truncate text-[13px] font-medium text-foreground",title:n,children:n}),l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r})]}),l.jsx("button",{type:"button","aria-label":"Close",onClick:()=>t(!1),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]}),l.jsx("div",{className:"relative z-20 shrink-0 border-b border-border/60",children:s}),l.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:o}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-background px-4 py-2.5",children:l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>t(!1),children:"Close"})})]})})}function OT(e){return e==="org_broadcast"||e==="all_tenants_broadcast"||e==="tenant_broadcast"}function vjt(e){const t=e.role==="VIEWER"?"view":"edit";switch(e.entity.type){case"org_broadcast":return`Anyone in your organization can ${t}`;case"all_tenants_broadcast":return`Anyone across all tenants can ${t}`;case"tenant_broadcast":return`Anyone in ${e.entity.tenantName??"this workspace"} can ${t}`;default:return""}}function wjt({shares:e,viewerType:t}){const n=e.filter(o=>OT(o.entity.type)),r=n.length===0,s=t==="tenant"?"Restricted — only invited people and groups in your workspace have access":"Restricted — only the people, tenants, and groups below have access";return l.jsxs("div",{className:"flex items-start gap-2 border-b border-border/60 bg-muted/40 px-4 py-2",children:[r?l.jsx(Bv,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):l.jsx(vm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("div",{className:"min-w-0 flex-1 text-[12px] text-foreground/80",children:r?l.jsx("span",{children:s}):n.map((o,i)=>l.jsxs("span",{children:[i>0?" · ":"",vjt(o)]},o.id))})]})}const sN={VIEWER:"Viewer",EDITOR:"Editor",CONTRIBUTOR:"Contributor"},Sjt={VIEWER:"Can view and use",EDITOR:"Can edit, share, and delete",CONTRIBUTOR:"Can edit but not share or delete"},Cjt={org_user:"ORG",tenant_user:"TENANT USER",tenant:"TENANT",org_group:"ORG GROUP",tenant_group:"TENANT GROUP"};function Bz({type:e,viewerType:t}){if(t!=="organization")return null;const n=Cjt[e];return n?l.jsx("span",{className:"rounded-[4px] bg-muted px-1 py-0.5 text-[9px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n}):null}function kv({entity:e}){return OT(e.type)?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground",children:l.jsx(vm,{className:"h-3 w-3"})}):e.type==="tenant"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border bg-background text-muted-foreground",children:l.jsx(rY,{className:"h-3 w-3"})}):e.type==="org_group"||e.type==="tenant_group"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border/60 bg-muted text-muted-foreground",children:l.jsx(_k,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground",children:e.initial||"?"})}function jk({value:e,onChange:t,disabled:n,includeRemove:r,onRemove:s,displayLabelOverride:o,loading:i}){const a=n||i,c=l.jsxs("button",{type:"button",disabled:a,className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[12px] text-foreground hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-transparent",children:[o??sN[e],i?l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):l.jsx(Ce.ChevronDown,{className:m.cn("h-3 w-3 text-muted-foreground",n&&"invisible")})]});return a?c:l.jsxs(m.Popover,{modal:!0,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:c}),l.jsxs(m.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-56 rounded-[6px] border border-border/60 bg-popover p-1 shadow-md",children:[Object.keys(sN).map(u=>l.jsx(Njt,{label:sN[u],description:Sjt[u],selected:e===u,onSelect:()=>t(u)},u)),r&&s?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"my-1 h-px bg-border/60"}),l.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] text-destructive hover:bg-destructive/10",children:[l.jsx(va,{className:"h-3.5 w-3.5"}),"Remove access"]})]}):null]})]})}function Njt({label:e,description:t,selected:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:r,className:"flex w-full items-start justify-between gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] hover:bg-muted",children:[l.jsxs("div",{children:[l.jsx("div",{className:"font-medium text-foreground",children:e}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:t})]}),n?l.jsx(m.Check,{className:"mt-0.5 h-3.5 w-3.5 text-foreground"}):null]})}const jjt=5;function kjt(e){const{directory:t,groupConfig:n,excludeIds:r,placeholder:s,invites:o,defaultRole:i,onAdd:a,onRemoveInvite:c,onChangeInviteRole:u,onChangeDefaultRole:d,onSubmit:f,isSubmitting:h,viewerType:p}=e,[g,b]=w.useState(""),[x,y]=w.useState(!1),[v,S]=w.useState("all"),[N,C]=w.useState(new Set),[j,_]=w.useState(null),k=w.useRef(null),I=w.useRef(null),T=w.useRef(null),E=g.trim(),D=E.length>0,M=w.useMemo(()=>{const X=E.toLowerCase(),z=t.filter(B=>!r.has(B.id));return X?z.filter(B=>B.name.toLowerCase().includes(X)||B.sublabel.toLowerCase().includes(X)||(B.tenantName??"").toLowerCase().includes(X)):z},[E,r,t]),A=w.useMemo(()=>{if(v==="all")return M;const X=n.find(z=>z.key===v);return X?M.filter(z=>X.types.includes(z.type)):M},[M,v,n]),P=w.useMemo(()=>t.filter(X=>OT(X.type)&&!r.has(X.id)),[t,r]),O=w.useMemo(()=>{const X={all:M.length};for(const z of n)X[z.key]=M.filter(B=>z.types.includes(B.type)).length;return X},[M,n]),$=w.useMemo(()=>t.filter(z=>z.type==="tenant").map(z=>({tenant:z,userCount:t.filter(B=>B.type==="tenant_user"&&B.tenantName===z.name).length})),[t]),V=w.useMemo(()=>j?t.find(X=>X.id===j&&X.type==="tenant")??null:null,[t,j]),U=w.useMemo(()=>{if(!V)return[];const X=E.toLowerCase();return t.filter(z=>z.type!=="tenant_user"||z.tenantName!==V.name||r.has(z.id)?!1:X?z.name.toLowerCase().includes(X)||z.sublabel.toLowerCase().includes(X):!0)},[t,V,E,r]);function R(X){b(X),X.trim()!==E&&C(new Set)}function q(X){S(X),X!==v&&C(new Set)}function W(X){var z;a(X),R(""),!(j&&X.type==="tenant_user")&&(q("all"),C(new Set),_(null),(z=k.current)==null||z.focus())}function F(X){_(X),R(""),q("all"),C(new Set)}function Z(){var X;_(null),R(""),(X=k.current)==null||X.focus()}function K(X){var z;if(X.key==="Backspace"&&g.length===0){if(j){Z(),X.preventDefault();return}o.length>0&&c(o[o.length-1].entity.id)}else X.key==="Escape"&&((z=k.current)==null||z.blur())}function Y(X){C(z=>{const B=new Set(z);return B.has(X)?B.delete(X):B.add(X),B})}return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Popover,{open:x,onOpenChange:y,modal:!1,children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(m.Anchor2,{asChild:!0,children:l.jsx("div",{ref:I,className:"flex-1",children:l.jsx(_jt,{ref:k,placeholder:V?`Filter ${V.name} users…`:s,query:g,onQueryChange:X=>{R(X),y(!0)},onFocus:()=>y(!0),onKeyDown:K})})}),l.jsx(Ijt,{value:i,onChange:d}),l.jsx(m.Button,{type:"button",size:"xs",onClick:f,disabled:o.length===0||h,children:h?"Sharing…":"Share"})]}),l.jsx(m.Portal$2,{children:l.jsx(m.PortalScope,{children:l.jsxs(m.Content2,{ref:T,align:"start",sideOffset:4,onOpenAutoFocus:X=>X.preventDefault(),onCloseAutoFocus:X=>X.preventDefault(),onPointerDownOutside:X=>{var B;const z=X.target;z instanceof Node&&((B=I.current)!=null&&B.contains(z))&&X.preventDefault()},onInteractOutside:X=>{var B;const z=X.target;z instanceof Node&&((B=I.current)!=null&&B.contains(z))&&X.preventDefault()},onWheel:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),className:m.cn("pointer-events-auto z-[60] flex flex-col w-[var(--radix-popover-trigger-width)] min-w-[360px]","max-h-[min(360px,var(--radix-popover-content-available-height))]","overflow-hidden rounded-[6px] border border-border/60 bg-popover text-popover-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"),children:[V?l.jsx(Tjt,{tenant:V,userCount:U.length,onBack:Z}):n.length>1?l.jsx(Ejt,{groupConfig:n,groupCounts:O,activeFilter:v,onChangeFilter:q}):null,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-1",onWheel:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),children:l.jsx(Mjt,{drilledInTenant:V,drilledInTenantUsers:U,hasQuery:D,query:E,activeFilter:v,groupConfig:n,filteredMatches:A,broadcastItems:P,tenantsWithUserCounts:$,expandedGroups:N,directory:t,viewerType:p,onPick:W,onDrillInto:F,onToggleExpand:Y})})]})})})]}),o.length>0&&l.jsx(Rjt,{invites:o,viewerType:p,onChangeRole:u,onRemove:c})]})}const _jt=({ref:e,placeholder:t,query:n,onQueryChange:r,onFocus:s,onKeyDown:o})=>l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-input bg-background px-2 focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/10",onClick:()=>{var i;return(i=e.current)==null?void 0:i.focus()},children:[l.jsx(Ot.Search,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("input",{ref:e,type:"text",value:n,onChange:i=>r(i.target.value),onFocus:s,onKeyDown:o,placeholder:t,className:"h-full flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground"})]});function Ijt({value:e,onChange:t}){return l.jsx("div",{className:"flex h-7 shrink-0 items-center rounded-[5px] border border-input bg-background px-1",children:l.jsx(jk,{value:e,onChange:t})})}function Tjt({tenant:e,userCount:t,onBack:n}){return l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b border-border/60 px-2 py-1.5",children:[l.jsxs("button",{type:"button",onClick:n,"aria-label":"Back",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(xm,{className:"h-3 w-3"}),"Back"]}),l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx(rY,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e.name}),l.jsxs("span",{className:"text-[11px] text-muted-foreground/70",children:["· ",t," ",t===1?"user":"users"]})]})}function Ejt({groupConfig:e,groupCounts:t,activeFilter:n,onChangeFilter:r}){return l.jsx("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border/60 bg-popover px-2 py-1.5",children:e.map(s=>{const o=t[s.key]??0;if(o===0)return null;const i=n===s.key;return l.jsx(Djt,{label:s.pillLabel,count:o,active:i,onClick:()=>r(i?"all":s.key)},s.key)})})}function Djt({label:e,count:t,active:n,onClick:r}){return l.jsxs("button",{type:"button",onClick:r,className:m.cn("inline-flex h-6 shrink-0 items-center gap-1 rounded-[4px] px-2 text-[11px] transition-colors",n?"bg-foreground text-background":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e,typeof t=="number"?l.jsx("span",{className:m.cn("tabular-nums",n?"text-background/70":"text-muted-foreground/70"),children:t}):null]})}function Mjt(e){const{drilledInTenant:t,drilledInTenantUsers:n,hasQuery:r,query:s,activeFilter:o,groupConfig:i,filteredMatches:a,broadcastItems:c,tenantsWithUserCounts:u,expandedGroups:d,directory:f,viewerType:h,onPick:p,onDrillInto:g,onToggleExpand:b}=e;return t?l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",onClick:()=>p(t),className:"mb-2 flex w-full items-center gap-2 rounded-[5px] border border-dashed border-border/60 px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"truncate text-[13px] text-foreground",children:["Share ",l.jsx("strong",{className:"font-medium",children:t.name})," ","as a whole tenant instead"]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:"Grants every user in the workspace, present and future"})]}),l.jsx(Ot.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),n.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${s}" inside ${t.name}.`:`No users in ${t.name} to browse.`}):l.jsx(RM,{label:`Users in ${t.name}`,items:n,viewerType:h,onPick:p})]}):!r&&o==="tenant_users"&&u.length>0?l.jsxs("div",{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Browse by tenant"}),u.map(({tenant:x,userCount:y})=>l.jsxs("button",{type:"button",onClick:()=>g(x.id),className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:x}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] text-foreground",children:x.name}),l.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[y," ",y===1?"user":"users"]})]}),l.jsx(Ot.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},x.id)),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Click a tenant to filter to its users, or start typing to search across all tenants."})]}):!r&&o==="all"?l.jsxs(l.Fragment,{children:[c.length>0&&l.jsx(RM,{label:"General access",items:c,viewerType:h,onPick:p}),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Type to search, or pick a category above to browse."})]}):a.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${s}".`:"Nothing to browse in this category."}):l.jsx(l.Fragment,{children:i.map(x=>{if(o!=="all"&&o!==x.key)return null;const y=a.filter(C=>x.types.includes(C.type));if(y.length===0)return null;const v=d.has(x.key),S=o===x.key||v?y:y.slice(0,jjt),N=y.length-S.length;return x.key==="tenant_users"?l.jsx(Ajt,{label:x.label,items:y,visible:S,hiddenCount:N,directory:f,viewerType:h,onPick:p,onDrillInto:g,onToggleExpand:()=>b(x.key)},x.key):l.jsx(RM,{label:x.label,count:y.length,items:S,viewerType:h,onPick:p,showMoreCount:N,onShowMore:()=>b(x.key)},x.key)})})}function Ajt({label:e,items:t,visible:n,hiddenCount:r,directory:s,viewerType:o,onPick:i,onDrillInto:a,onToggleExpand:c}){const u=w.useMemo(()=>{const d=new Map;for(const f of n){const h=f.tenantName??"—";d.has(h)||d.set(h,[]),d.get(h).push(f)}return d},[n]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t.length>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t.length]}):null]}),Array.from(u.entries()).map(([d,f])=>{const h=s.find(p=>p.type==="tenant"&&p.name===d);return l.jsxs("div",{className:"mb-1",children:[l.jsxs("div",{className:"flex items-center justify-between px-2 py-0.5",children:[l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:d}),h?l.jsx("button",{type:"button",onClick:()=>a(h.id),className:"text-[10px] text-muted-foreground hover:text-foreground",children:"Browse all →"}):null]}),f.map(p=>l.jsx(ybe,{entity:p,viewerType:o,onPick:()=>i(p)},p.id))]},d)}),r>0?l.jsxs("button",{type:"button",onClick:c,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3"}),"Show ",r," more"]}):null]})}function RM({label:e,count:t,items:n,viewerType:r,onPick:s,showMoreCount:o,onShowMore:i}){return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),typeof t=="number"&&t>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t]}):null]}),n.map(a=>l.jsx(ybe,{entity:a,viewerType:r,onPick:()=>s(a)},a.id)),o&&o>0&&i?l.jsxs("button",{type:"button",onClick:i,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3"}),"Show ",o," more"]}):null]})}function ybe({entity:e,viewerType:t,onPick:n}){return l.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:e}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.name}),l.jsx(Bz,{type:e.type,viewerType:t}),t==="organization"&&e.tenantName?l.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground/70",children:["· ",e.tenantName]}):null]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:e.sublabel})]})]})}function Rjt({invites:e,viewerType:t,onChangeRole:n,onRemove:r}){return l.jsx("div",{className:"space-y-0.5 rounded-[5px] bg-muted/40 px-1 py-1",children:e.map(s=>l.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[l.jsx(kv,{entity:s.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:s.entity.name}),l.jsx(Bz,{type:s.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&s.entity.tenantName?`${s.entity.sublabel} · ${s.entity.tenantName}`:s.entity.sublabel||(OT(s.entity.type)?`Will be granted as ${sN[s.role]}`:"")})]}),l.jsx(jk,{value:s.role,onChange:o=>n(s.entity.id,o)}),l.jsx("button",{type:"button",onClick:()=>r(s.entity.id),"aria-label":"Remove",className:"flex h-6 w-6 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]},s.entity.id))})}function Pjt({shares:e,sections:t,onChangeRole:n,onRemove:r,viewerType:s,pendingShareIds:o}){return l.jsx("div",{className:"space-y-3",children:t.map(i=>{const a=e.filter(c=>i.matches(c.entity));return a.length===0&&!i.emptyLabel?null:l.jsxs("section",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5 px-2 py-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:i.label}),l.jsxs("span",{className:"text-muted-foreground/70",children:["· ",a.length]})]}),a.length===0?l.jsx("p",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:i.emptyLabel}):a.map(c=>l.jsx(Fjt,{share:c,viewerType:s,loading:o.has(c.id),onChangeRole:u=>n(c,u),onRemove:()=>r(c)},c.id))]},i.label)})})}function Fjt({share:e,viewerType:t,loading:n,onChangeRole:r,onRemove:s}){return l.jsxs("div",{className:"group flex items-center gap-2 rounded-[5px] px-2 py-1.5 hover:bg-muted/40",children:[l.jsx(kv,{entity:e.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.entity.name}),e.isSelf?l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(you)"}):l.jsx(Bz,{type:e.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&e.entity.tenantName?`${e.entity.sublabel} · ${e.entity.tenantName}`:e.entity.sublabel})]}),e.isSelf?l.jsx(jk,{value:e.role,onChange:()=>{},disabled:!0,displayLabelOverride:"Owner"}):l.jsx(jk,{value:e.role,onChange:r,includeRemove:!0,onRemove:s,loading:n})]})}function Gm(e){if(!e)return"?";const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}function vbe(e){const t=e.type==="organization",n=e.name||e.email||"Unknown user";return{id:e.id,type:t?"org_user":"tenant_user",name:n,sublabel:e.email||"",initial:Gm(n),tenantId:e.tenantId,tenantName:e.tenantName}}function wbe(e){return{id:e.id,type:e.type==="ORG_GROUP"?"org_group":"tenant_group",name:e.name,sublabel:e.memberCount!==void 0?`${e.memberCount} member${e.memberCount===1?"":"s"}`:e.description||"",initial:Gm(e.name),tenantId:e.tenantId??void 0,tenantName:e.tenantName??void 0}}function Ojt(e){return{id:e.id,type:"tenant",name:e.name,sublabel:"Tenant workspace",initial:Gm(e.name),tenantId:e.id,tenantName:e.name}}const Sbe={id:"__broadcast:org",type:"org_broadcast",name:"Everyone in the organization",sublabel:"Any user in your organization can open this dashboard",initial:""},Cbe={id:"__broadcast:all-tenants",type:"all_tenants_broadcast",name:"Everyone across all tenants",sublabel:"Every tenant user in every tenant can open this dashboard",initial:""};function Nbe(e){return{id:"__broadcast:tenant",type:"tenant_broadcast",name:e.tenantName?`Everyone in ${e.tenantName}`:"Everyone in your workspace",sublabel:"Anyone who can sign in to your workspace can open this dashboard",tenantId:e.tenantId,tenantName:e.tenantName,initial:""}}function Ljt(e){return[Sbe,Cbe,...e.users.map(vbe),...e.tenants.map(Ojt),...e.groups.map(wbe)]}function $jt(e){var n,r;return[Nbe({tenantId:(n=e.currentUser)==null?void 0:n.tenantId,tenantName:(r=e.currentUser)==null?void 0:r.tenantName}),...e.users.filter(s=>s.type==="tenant").map(vbe),...e.groups.filter(s=>s.type==="TENANT_GROUP").map(wbe)]}function zjt({existingShares:e,userDirectory:t,groupDirectory:n,tenantDirectory:r,currentUser:s}){if(!(e!=null&&e.shares))return[];const o=new Map(t.map(f=>[f.id,f])),i=new Map(n.map(f=>[f.id,f])),a=new Map(r.map(f=>[f.id,f])),c=[];(e.shares.specificOrgUsers??[]).forEach(f=>c.push(Bjt(f,o,s))),(e.shares.specificTenantUsers??[]).forEach(f=>c.push(Vjt(f,o,s))),(e.shares.tenantWide??[]).forEach(f=>c.push(Hjt(f,a)));const u=[...e.shares.specificGroups??[],...e.shares.groups??[]],d=new Set;if(u.forEach(f=>{d.has(f.id)||(d.add(f.id),c.push(Ujt(f,i)))}),(s==null?void 0:s.type)==="organization"&&((e.shares.orgUsersOnly??[]).forEach(f=>c.push(qjt(f))),(e.shares.allTenantsOnly??[]).forEach(f=>c.push(Wjt(f)))),(s==null?void 0:s.type)==="tenant"&&s.tenantId){const f=(e.shares.tenantWide??[]).find(h=>h.tenantId===s.tenantId);if(f){const h=c.findIndex(p=>p.id===f.id&&p.entity.type==="tenant");h>=0&&c.splice(h,1),c.push(Gjt(f,s.tenantName))}}return(e.shares.allOrgGroups??[]).forEach(f=>c.push(Kjt(f))),(e.shares.allTenantGroups??[]).forEach(f=>c.push(Yjt(f))),c}function Bjt(e,t,n){var i,a,c;const r=t.get(e.orgUserId),s=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Org user",o=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.orgUserId,entity:{id:e.orgUserId,type:"org_user",name:s,sublabel:o,initial:Gm(s)}}}function Vjt(e,t,n){var i,a,c,u,d;const r=t.get(e.tenantUserId),s=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Tenant user",o=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.tenantUserId,entity:{id:e.tenantUserId,type:"tenant_user",name:s,sublabel:o,initial:Gm(s),tenantId:e.tenantId??((u=e.tenant)==null?void 0:u.id),tenantName:(d=e.tenant)==null?void 0:d.name}}}function Hjt(e,t){var s;const n=e.tenantId?t.get(e.tenantId):void 0,r=((s=e.tenant)==null?void 0:s.name)||(n==null?void 0:n.name)||"Tenant";return{id:e.id,role:e.role,entity:{id:e.tenantId??e.id,type:"tenant",name:r,sublabel:"All users in this tenant",initial:Gm(r),tenantId:e.tenantId,tenantName:r}}}function Ujt(e,t){var a,c,u;const n=t.get(e.groupId),r=((a=e.group)==null?void 0:a.name)||(n==null?void 0:n.name)||"Group",o=(((c=e.group)==null?void 0:c.type)||(n==null?void 0:n.type))==="ORG_GROUP",i=((u=e.group)==null?void 0:u.memberCount)??(n==null?void 0:n.memberCount);return{id:e.id,role:e.role,entity:{id:e.groupId,type:o?"org_group":"tenant_group",name:r,sublabel:i!==void 0?`${i} member${i===1?"":"s"}`:"",initial:Gm(r),tenantId:(n==null?void 0:n.tenantId)??void 0}}}function qjt(e){return{id:e.id,role:e.role,entity:{...Sbe}}}function Wjt(e){return{id:e.id,role:e.role,entity:{...Cbe}}}function Gjt(e,t){var r;const n=Nbe({tenantId:e.tenantId,tenantName:t??((r=e.tenant)==null?void 0:r.name)});return{id:e.id,role:e.role,entity:n}}function Kjt(e){return{id:e.id,role:e.role,entity:{id:`__all_org_groups:${e.id}`,type:"org_group",name:"All organization groups",sublabel:"Every org group",initial:"G"}}}function Yjt(e){return{id:e.id,role:e.role,entity:{id:`__all_tenant_groups:${e.id}`,type:"tenant_group",name:"All tenant groups",sublabel:"Every tenant group",initial:"G"}}}function Zjt(e,t){switch(e.type){case"org_user":return{scope:"specific_org_user",orgUserId:e.id,role:t};case"tenant_user":return{scope:"specific_tenant_user",tenantUserId:e.id,tenantId:e.tenantId,role:t};case"tenant":return{scope:"all_tenant_users",tenantId:e.id,role:t};case"org_group":case"tenant_group":return{scope:"group",groupId:e.id,role:t};case"org_broadcast":return{scope:"org_users_only",role:t};case"all_tenants_broadcast":return{scope:"all_tenants_only",role:t};case"tenant_broadcast":return{scope:"all_tenant_users",tenantId:e.tenantId,role:t}}}function Xjt(e){return e.invites.length===0?null:{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:e.invites.map(t=>Zjt(t.entity,t.role))}}}function Qjt(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[jbe(e.share,e.newRole,e.existingShares)]}}}function Jjt(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[jbe(e.share,e.share.role,e.existingShares)]}}}function jbe(e,t,n){if(e.entity.type==="org_broadcast")return{scope:"org_users_only",role:t};if(e.entity.type==="all_tenants_broadcast")return{scope:"all_tenants_only",role:t};if(e.entity.type==="tenant_broadcast")return{scope:"all_tenant_users",tenantId:e.entity.tenantId,role:t};if(e.entity.id.startsWith("__all_org_groups:"))return{scope:"all_org_groups",role:t};if(e.entity.id.startsWith("__all_tenant_groups:"))return{scope:"all_tenant_groups",role:t};switch(e.entity.type){case"org_user":{const r=((n==null?void 0:n.shares.specificOrgUsers)??[]).find(s=>s.orgUserId===e.entity.id);return{scope:"specific_org_user",orgUserId:(r==null?void 0:r.orgUserId)??e.entity.id,role:t}}case"tenant_user":{const r=((n==null?void 0:n.shares.specificTenantUsers)??[]).find(s=>s.tenantUserId===e.entity.id);return{scope:"specific_tenant_user",tenantUserId:(r==null?void 0:r.tenantUserId)??e.entity.id,tenantId:(r==null?void 0:r.tenantId)??e.entity.tenantId,role:t}}case"tenant":{const r=((n==null?void 0:n.shares.tenantWide)??[]).find(s=>s.tenantId===e.entity.id);return{scope:"all_tenant_users",tenantId:(r==null?void 0:r.tenantId)??e.entity.id,role:t}}case"org_group":case"tenant_group":{const s=[...(n==null?void 0:n.shares.specificGroups)??[],...(n==null?void 0:n.shares.groups)??[]].find(o=>o.groupId===e.entity.id);return{scope:"group",groupId:(s==null?void 0:s.groupId)??e.entity.id,role:t}}}}function TK(e){const{open:t,resource:n,resourceType:r,currentUser:s,config:o,onClose:i}=e,[a,c]=w.useState([]),[u,d]=w.useState("VIEWER"),[f,h]=w.useState(()=>new Set),[p,g]=w.useState(!1);function b(V){h(U=>{const R=new Set(U);return R.add(V),R})}function x(V){h(U=>{const R=new Set(U);return R.delete(V),R})}const y=$I({type:o.unifiedUsersType,limit:50}),v=Z$({type:o.groupsType,limit:50}),S=eat({enabled:o.fetchTenants}),N=w.useMemo(()=>{if(!o.fetchTenants)return[];const V=S.data;return(V==null?void 0:V.tenants)??[]},[o.fetchTenants,S.data]),{existingShares:C}=xjt({debouncedSearchQuery:"",resourceId:(n==null?void 0:n.id)||"",resourceType:r,userType:(s==null?void 0:s.type)??"tenant"}),j=qde(),_=Wde(),k=w.useMemo(()=>o.buildDirectory({users:y.users,groups:v.groups,tenants:N,currentUser:s}),[o,y.users,v.groups,N,s]),I=w.useMemo(()=>zjt({existingShares:C,userDirectory:y.users,groupDirectory:v.groups,tenantDirectory:N,currentUser:s}),[C,y.users,v.groups,N,s]),T=w.useMemo(()=>new Set([...a.map(V=>V.entity.id),...I.map(V=>V.entity.id)]),[a,I]);function E(V){c(U=>[...U,{entity:V,role:u}])}function D(V){c(U=>U.filter(R=>R.entity.id!==V))}function M(V,U){c(R=>R.map(q=>q.entity.id===V?{...q,role:U}:q))}function A(){const V=Xjt({resourceType:r,resourceId:n.id,invites:a});V&&(g(!0),j.mutate(V,{onSuccess:()=>c([]),onSettled:()=>g(!1)}))}function P(V,U){const R=Qjt({resourceType:r,resourceId:n.id,share:V,newRole:U,existingShares:C});b(V.id),j.mutate(R,{onSettled:()=>x(V.id)})}function O(V){const U=Jjt({resourceType:r,resourceId:n.id,share:V,existingShares:C});b(V.id),_.mutate(U,{onSettled:()=>x(V.id)})}const $=r==="visual"?"VISUAL":"DASHBOARD";return l.jsx(yjt,{open:t,onOpenChange:V=>{V||i()},title:`Share "${(n==null?void 0:n.title)??"resource"}"`,subtitle:$,topContent:l.jsxs(l.Fragment,{children:[l.jsx(wjt,{shares:I,viewerType:s==null?void 0:s.type}),l.jsx("div",{className:"px-4 py-3",children:l.jsx(kjt,{directory:k,groupConfig:o.groupConfig,excludeIds:T,placeholder:o.invitePlaceholder,invites:a,defaultRole:u,onChangeDefaultRole:d,onAdd:E,onRemoveInvite:D,onChangeInviteRole:M,onSubmit:A,isSubmitting:p,viewerType:s==null?void 0:s.type})})]}),children:l.jsx(Pjt,{shares:I,sections:o.sections,onChangeRole:P,onRemove:O,viewerType:s==null?void 0:s.type,pendingShareIds:f})})}const ekt={buildDirectory:({users:e,groups:t,tenants:n})=>Ljt({users:e,groups:t,tenants:n??[]}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["org_broadcast","all_tenants_broadcast"]},{key:"org_users",pillLabel:"People",label:"Org users",types:["org_user"]},{key:"tenants",pillLabel:"Tenants",label:"Tenants (whole workspace)",types:["tenant"]},{key:"tenant_users",pillLabel:"Tenant users",label:"Tenant users",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["org_group","tenant_group"]}],sections:[{label:"General access",matches:e=>e.type==="org_broadcast"||e.type==="all_tenants_broadcast"},{label:"People with access",matches:e=>e.type==="org_user"||e.type==="tenant_user",emptyLabel:"No individual people have been added."},{label:"Tenants with access",matches:e=>e.type==="tenant"},{label:"Groups with access",matches:e=>e.type==="org_group"||e.type==="tenant_group"}],fetchTenants:!0,invitePlaceholder:"Add people, tenants, groups, or broadcast access…",unifiedUsersType:"all",groupsType:"all"};function tkt(e){return{buildDirectory:({users:t,groups:n,currentUser:r})=>$jt({users:t,groups:n,currentUser:r}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["tenant_broadcast"]},{key:"people",pillLabel:"People",label:"People in your workspace",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["tenant_group"]}],sections:[{label:"General access",matches:t=>t.type==="tenant_broadcast"},{label:"People with access",matches:t=>t.type==="tenant_user",emptyLabel:"No teammates have been added yet."},{label:"Groups with access",matches:t=>t.type==="tenant_group"}],fetchTenants:!1,invitePlaceholder:"Add teammates, groups, or broadcast access…",unifiedUsersType:"tenant",groupsType:"TENANT_GROUP"}}function kbe({resource:e,resourceType:t,onClose:n}){const{currentUser:r}=ti();return(r==null?void 0:r.type)==="organization"?l.jsx(TK,{open:!0,resource:e,resourceType:t,currentUser:r,config:ekt,onClose:n}):l.jsx(TK,{open:!0,resource:e,resourceType:t,currentUser:r,config:tkt(),onClose:n})}function _be({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,c]=w.useState(n),[u,d]=w.useState(r??"");w.useEffect(()=>{e&&(c(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const p=a.trim();p&&o({title:p,description:u.trim()})};return l.jsx(Gs,{open:e,onOpenChange:h=>h?null:s(),children:l.jsx(Is,{className:"sm:max-w-md",children:l.jsxs("form",{onSubmit:f,className:"space-y-4",children:[l.jsxs(Jo,{children:[l.jsxs(Ts,{children:["Edit ",t]}),l.jsxs(Ks,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"resource-title",children:"Title"}),l.jsx(m.Input,{id:"resource-title",value:a,onChange:h=>c(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"resource-description",children:"Description"}),l.jsx(Hm,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),l.jsxs(Qa,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[l.jsx(m.Button,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),l.jsx(m.Button,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}const KF=new Set;function Ibe(e){return KF.add(e),()=>{KF.delete(e)}}function Vz(){KF.forEach(e=>{e()})}const nkt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},rkt={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}},skt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function okt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function ikt(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const EK=Symbol.for("r2wc.bound"),akt={parse:(e,t,n)=>{const r=ikt(t),s=n;if(typeof s<"u"&&r in s&&typeof s[r]<"u"){let o=s[r];return EK in s[r]||(o=o.bind(s),Object.defineProperty(o,EK,{value:!0})),o}else return}},lkt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},ckt={stringify:e=>e,parse:e=>e},PM={string:ckt,number:lkt,boolean:nkt,function:rkt,method:akt,json:skt},l1=Symbol.for("r2wc.render"),c1=Symbol.for("r2wc.connected"),Pf=Symbol.for("r2wc.context"),bl=Symbol.for("r2wc.props");function ukt(e,t,n){var d,f,h;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const r=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),s=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),o={},i={},a={},c={};for(const p of r){o[p]=Array.isArray(t.props)?"string":t.props[p];const g=okt(p);a[p]=g,c[g]=p}for(const p of s)i[p]=Array.isArray(t.events)?{}:t.events[p];class u extends HTMLElement{constructor(){super();ve(this,h,!0);ve(this,f);ve(this,d,{});ve(this,"container");t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[bl].container=this.container;for(const b of r){const x=a[b],y=this.getAttribute(x),v=o[b],S=v?PM[v]:null;S!=null&&S.parse&&(y||v==="method")&&(this[bl][b]=S.parse(y,x,this))}for(const b of s)this[bl][b]=x=>{const y=b.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(y,{detail:x,...i[b]}))}}static get observedAttributes(){return Object.keys(c)}connectedCallback(){this[c1]=!0,this[l1]()}disconnectedCallback(){this[c1]=!1,this[Pf]&&n.unmount(this[Pf]),delete this[Pf]}attributeChangedCallback(b,x,y){const v=c[b],S=o[v],N=S?PM[S]:null;v in o&&(N!=null&&N.parse)&&(y||S==="method")&&(this[bl][v]=N.parse(y,b,this),this[l1]())}[(h=c1,f=Pf,d=bl,l1)](){this[c1]&&(this[Pf]?n.update(this[Pf],this[bl]):this[Pf]=n.mount(this.container,e,this[bl]))}}for(const p of r){const g=a[p],b=o[p];Object.defineProperty(u.prototype,p,{enumerable:!0,configurable:!0,get(){return this[bl][p]},set(x){this[bl][p]=x;const y=b?PM[b]:null;if(y!=null&&y.stringify){const v=y.stringify(x,g,this);this.getAttribute(g)!==v&&(v==null?this.removeAttribute(g):this.setAttribute(g,v))}else p in o&&(y!=null&&y.parse)&&(x||b==="method")&&(this[bl][p]=y.parse(x,g,this)),this[l1]()}})}return u}function dkt(e,t,n){const r=hxe.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function fkt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function hkt({root:e}){e.unmount()}function mkt(e,t={}){return ukt(e,t,{mount:dkt,update:fkt,unmount:hkt})}const pkt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},gkt=mkt(cxe,{props:pkt}),bkt=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(J4,{context:t})," "]})});var Tbe="Toggle",Ebe=te.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:s,...o}=e,[i,a]=m.useControllableState({prop:n,onChange:s,defaultProp:r??!1,caller:Tbe});return l.jsx(m.Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...o,ref:t,onClick:m.composeEventHandlers(e.onClick,()=>{e.disabled||a(!i)})})});Ebe.displayName=Tbe;var Dbe=Ebe;const xkt=m.cva("inline-flex items-center justify-center rounded-control text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Mbe=te.forwardRef(({className:e,variant:t,size:n,...r},s)=>l.jsx(Dbe,{ref:s,className:m.cn(xkt({variant:t,size:n,className:e})),...r}));Mbe.displayName=Dbe.displayName;function Hz(){var c,u;const e=m.useEditorStore(d=>d.card),t=m.useEditorStore(d=>d.frame),n=w.useMemo(()=>EI(t,e),[t,e]),{manifest:r}=mf(((c=n==null?void 0:n.customCardPreferences)==null?void 0:c.url)||""),s=w.useMemo(()=>{var d;return(d=r==null?void 0:r.visuals)==null?void 0:d.find(f=>{var h;return f.name===((h=n==null?void 0:n.customCardPreferences)==null?void 0:h.componentName)})},[r,(u=n==null?void 0:n.customCardPreferences)==null?void 0:u.componentName]),o=zb(n,s),i=w.useMemo(()=>TI({frame:t,configCard:n,isMultiInputVisual:o==="multiple"}),[t,n,o]),a=w.useMemo(()=>{const d=i.findIndex(f=>(f==null?void 0:f.id)===e.id);return d<0?-1:Yg(e,d)},[i,e]);return w.useMemo(()=>!n||o!=="multiple"||a<0?e.type:Lh(e,a,s==null?void 0:s.slots)??e.type,[n,o,a,e,s==null?void 0:s.slots])}function Abe({storeValue:e,defaultValue:t="",onStoreUpdate:n,delay:r=300}){const[s,o]=w.useState(e??t),i=w.useRef(null),a=w.useRef(s),c=w.useRef(e),u=w.useRef(!1),d=w.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null),u.current&&a.current!==(c.current??t)&&(n(a.current),c.current=a.current)},[t,n]);w.useEffect(()=>{if(e!==c.current){i.current&&(clearTimeout(i.current),i.current=null);const h=e??t;o(h),a.current=h,c.current=e,u.current=!1}},[e,t]),w.useEffect(()=>{if(u.current)return i.current=setTimeout(()=>{d()},r),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[r,d,s]),w.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=w.useCallback(h=>{const p=h??t;u.current=!0,a.current=p,o(p)},[t]);return{value:s,onChange:f,flush:d}}const ykt=300;function vkt({onExpand:e},t){const n=m.useEditorStore(S=>S.card.sql),r=m.useEditorStore(S=>S.sqlGen),s=m.useEditorStore(S=>S.card),o=Hz(),{setCardSql:i,setSqlGen:a,setRunSql:c}=m.useEditorActions(),u=w.useMemo(()=>o!==s.type?{...s,type:o}:s,[s,o]),{queryKey:d}=ob(u),f=Kr(),h=w.useRef(d);h.current=d;const p=w.useRef(r);p.current=r;const g=w.useCallback(S=>{i(S)},[i]),{value:b,onChange:x,flush:y}=Abe({storeValue:n,defaultValue:"",onStoreUpdate:g,delay:ykt});w.useEffect(()=>Ibe(y),[y]);function v(S){x(S),m.isObjectEmpty(p.current)||a({})}return l.jsxs("div",{className:"relative h-full w-full",children:[l.jsx(m.CodeEditor,{ref:t,value:b??"",onValueChange:v,language:"sql-jinja",embedded:!0,hideLineNumbers:!0,wrapLines:!0,placeholder:"Write your SQL here",onKeyDown:S=>{S.key==="Enter"&&S.shiftKey&&(S.preventDefault(),Vz(),setTimeout(()=>{f.removeQueries({queryKey:h.current,exact:!0}),c(!0)},0))}}),e?l.jsx(m.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2.5 top-2 z-20 h-7 w-7 bg-background/80 p-0 opacity-60 backdrop-blur-sm transition-opacity hover:bg-accent hover:opacity-100 focus-visible:opacity-100",onClick:e,"aria-label":"Expand SQL editor",title:"Expand SQL editor",children:l.jsx(Ot.Maximize2,{className:"h-3.5 w-3.5"})}):null]})}const wkt=w.forwardRef(vkt),Skt=300;function Ckt(e,t){const n=m.useEditorStore(g=>g.card.python),r=m.useEditorStore(g=>g.card),s=Hz(),{setCardPython:o,setRunSql:i}=m.useEditorActions(),a=w.useMemo(()=>s!==r.type?{...r,type:s}:r,[r,s]),{queryKey:c}=ob(a),u=Kr(),d=w.useRef(c);d.current=c;const{value:f,onChange:h,flush:p}=Abe({storeValue:n,defaultValue:mO,onStoreUpdate:o,delay:Skt});return w.useEffect(()=>Ibe(p),[p]),l.jsx(m.CodeEditor,{ref:t,value:f??"",onValueChange:h,language:"python",embedded:!0,hideLineNumbers:!0,wrapLines:!0,className:"[&_.code-editor-pre]:!pt-2 [&_.code-editor-textarea]:!pt-2",onKeyDown:g=>{g.key==="Enter"&&g.shiftKey&&(g.preventDefault(),Vz(),setTimeout(()=>{u.removeQueries({queryKey:d.current,exact:!0}),i(!0)},0))}})}const Nkt=w.forwardRef(Ckt),Rbe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),jkt=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),kkt=Array.from(Rbe).join(", "),_kt=3,Ikt="Self-heal",Tkt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function Ekt({card:e}){var U,R,q,W,F;const[t,n]=w.useState({}),{authToken:r}=Tt(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=w.useMemo(()=>Pw(o),[o]),a=m.useEditorStore(Z=>Z.frame),c=m.useEditorStore(Z=>Z.inlineFilterValuesMap[e.id]),u=m.useEditorStore(Z=>Z.actions.setCardInlineFilterValue),d=m.useEditorStore(Z=>Z.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=mf(((U=f.customCardPreferences)==null?void 0:U.url)||""),g=(R=p==null?void 0:p.visuals)==null?void 0:R.find(Z=>{var K;return Z.name===((K=f.customCardPreferences)==null?void 0:K.componentName)}),b=zb(f,g)??"single",x=w.useMemo(()=>TI({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=w.useMemo(()=>{const Z=x.findIndex(K=>(K==null?void 0:K.id)===e.id);return Z<0?-1:Yg(e,Z)},[x,e]),v=w.useMemo(()=>b!=="multiple"||y<0?e.type:Lh(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),S=w.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:v!==e.type?{...e,type:v}:e,[e,v,b]),{data:N}=ob(S),C=m.useInteractionStore(Z=>Z.interactionStates),j=m.useDashboardStore(Z=>{var K;return(K=Z.dashboard)==null?void 0:K.id}),_=m.useDashboardStore(Z=>Z.dashboard.filters),k=m.useDashboardStore(Z=>Z.filterValues),I=m.useDashboardStore(Z=>Z.selectedSheetId),T=w.useMemo(()=>k$({card:e,sheetId:I||"",inlineFilterValues:c,setInlineFilterValue:Z=>u(e.id,Z),removeInlineFilterValue:Z=>d(e.id,Z)}),[e,I,c,u,d]),{cardFilters:E,cardFilterValues:D}=w.useMemo(()=>Wv({card:e,interactionStates:C,currentDashboardId:j,filters:_,filterValues:k,selectedSheetId:I}),[e,C,j,_,k,I]),M=w.useCallback((Z,K)=>{const Y=T$(K);n(X=>({...X,[Z]:Y}))},[]),A=(q=f.customCardPreferences)==null?void 0:q.componentName,P=A?h(A):null,O=_j((W=f.customCardPreferences)==null?void 0:W.settings,f),$=w.useMemo(()=>I$(x),[x]),V=w.useMemo(()=>$.map((Z,K)=>Lh(Z,K,g==null?void 0:g.slots)),[$,g==null?void 0:g.slots]);return A?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(w.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[P&&b==="single"&&l.jsx(P,{editing:!0,params:s,theme:i,settings:O,cardMetadata:Ole({card:e,dataMetadata:N==null?void 0:N.metadata}),onDataChange:M,data:(N==null?void 0:N.records)||[],filters:E,filterValues:[...D||[],...c||[]],inlineFilters:T}),P&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((Z,K)=>{if(!Z)return null;const Y=Yg(Z,K),X=Lh(Z,Y,g==null?void 0:g.slots);return l.jsx(Z3,{onDataChange:M,card:Z,effectiveCardType:X},`${Z.id}-${Y}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(P,{editing:!0,onDataChange:M,...E$({configCard:f,slotOrderedCards:$,slotTypes:V,multiInputData:t,params:s,theme:i,chartSettings:O,filters:E,filterValues:[...D||[],...c||[]],inlineFilters:T})})})]})]},(F=f.customCardPreferences)==null?void 0:F.componentName)}):null}const Dkt=w.memo(Ekt,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),Mkt=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Pbe=["PageUp","PageDown"],Fbe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Obe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},rx="Slider",[YF,Akt,Rkt]=m.createCollection(rx),[Uz]=m.createContextScope(rx,[Rkt]),[Pkt,uS]=Uz(rx),qz=te.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=te.useRef(new Set),y=te.useRef(0),v=te.useRef(!1),N=i==="horizontal"?Fkt:Okt,[C,j]=te.useState(null),_=m.useComposedRefs(t,j),[k=[],I]=m.useControllableState({prop:d,defaultProp:u,onChange:O=>{var V;(V=[...x.current][y.current])==null||V.focus({preventScroll:!0,focusVisible:v.current}),v.current=!1,f(O)}}),T=te.useRef(k),E=te.useRef(k);te.useEffect(()=>{const O=g?C==null?void 0:C.ownerDocument.getElementById(g):C==null?void 0:C.closest("form");if(O instanceof HTMLFormElement){const $=()=>I(E.current);return O.addEventListener("reset",$),()=>O.removeEventListener("reset",$)}},[C,g,I]);function D(O){const $=Bkt(k,O);P(O,$)}function M(O){P(O,y.current)}function A(){const O=T.current[y.current];k[y.current]!==O&&h(k)}function P(O,$,{commit:V}={commit:!1}){const U=Jbe(o),R=iN(Math.round((O-r)/o)*o+r,U),q=m.clamp(R,[r,s]);I((W=[])=>{const F=$kt(W,q,$);if(Ukt(F,c*o)){y.current=F.indexOf(q);const Z=String(F)!==String(W);return Z&&V&&h(F),Z?F:W}else return W})}return l.jsx(Pkt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:k,orientation:i,form:g,children:l.jsx(YF.Provider,{scope:e.__scopeSlider,children:l.jsx(YF.Slot,{scope:e.__scopeSlider,children:l.jsx(N,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:_,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(T.current=k,v.current=!1)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:D,onSlideMove:a?void 0:M,onSlideEnd:a?void 0:A,onHomeKeyDown:()=>{a||(v.current=!0,P(r,0,{commit:!0}))},onEndKeyDown:()=>{a||(v.current=!0,P(s,k.length-1,{commit:!0}))},onStepKeyDown:({event:O,direction:$})=>{if(!a){v.current=!0;const R=Pbe.includes(O.key)||O.shiftKey&&Fbe.includes(O.key)?10:1,q=y.current,W=k[q],F=qkt(W,{min:r,step:o,direction:$,multiplier:R});P(F,q,{commit:!0})}}})})})})});qz.displayName=rx;var[Lbe,$be]=Uz(rx,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Fkt=te.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=te.useState(null),p=m.useComposedRefs(t,h),g=te.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function v(S){const N=g.current||f.getBoundingClientRect(),C=[0,N.width],_=Wz(C,y?[n,r]:[r,n]);return g.current=N,_(S-N.left)}return l.jsx(Lbe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(zbe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const N=v(S.clientX);i==null||i(N)},onSlideMove:S=>{const N=v(S.clientX);a==null||a(N)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:S=>{const C=Obe[y?"from-left":"from-right"].includes(S.key);u==null||u({event:S,direction:C?-1:1})}})})}),Okt=te.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=te.useRef(null),f=m.useComposedRefs(t,d),h=te.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],S=Wz(y,p?[r,n]:[n,r]);return h.current=x,S(b-x.top)}return l.jsx(Lbe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(zbe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Obe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),zbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=uS(rx,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Pbe.concat(Fbe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus({preventScroll:!0,focusVisible:!1}):r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),Bbe="SliderTrack",Vbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(Bbe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});Vbe.displayName=Bbe;var ZF="SliderRange",Hbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(ZF,n),o=$be(ZF,n),i=te.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>Qbe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Hbe.displayName=ZF;var Ube="SliderThumb",[Lkt,qbe]=Uz(Ube),Wbe="SliderThumbProvider";function Gbe(e){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:s}=e,o=uS(Wbe,t),i=Akt(t),[a,c]=te.useState(null),u=te.useMemo(()=>a?i().findIndex(x=>x.ref.current===a):-1,[i,a]),d=m.useSize(a),f=a?!!o.form||!!a.closest("form"):!0,h=o.values[u],p=n??(o.name?o.name+(o.values.length>1?"[]":""):void 0),g=h===void 0?0:Qbe(h,o.min,o.max);te.useEffect(()=>{if(a)return o.thumbs.add(a),()=>{o.thumbs.delete(a)}},[a,o.thumbs]);const b={value:h,name:p,form:o.form,isFormControl:f,index:u,thumb:a,onThumbChange:c,percent:g,size:d};return l.jsx(Lkt,{scope:t,...b,children:Wkt(s)?s(b):r})}Gbe.displayName=Wbe;var oN="SliderThumbTrigger",Kbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(oN,n),o=$be(oN,n),{index:i,value:a,percent:c,size:u,onThumbChange:d}=qbe(oN,n),f=m.useComposedRefs(t,d),h=zkt(i,s.values.length),p=u==null?void 0:u[o.size],g=p?Vkt(p,c,o.direction):0;return l.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${c}% + ${g}px)`},children:l.jsx(YF.ItemSlot,{scope:n,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||h,"aria-valuemin":s.min,"aria-valuenow":a,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:f,style:a===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{s.valueIndexToChangeRef.current=i})})})})});Kbe.displayName=oN;var Ybe=te.forwardRef((e,t)=>{const{__scopeSlider:n,name:r,...s}=e;return l.jsx(Gbe,{__scopeSlider:n,name:r,internal_do_not_use_render:({index:o,isFormControl:i})=>l.jsxs(l.Fragment,{children:[l.jsx(Kbe,{...s,ref:t,__scopeSlider:n}),i?l.jsx(Xbe,{__scopeSlider:n},o):null]})})});Ybe.displayName=Ube;var Zbe="SliderBubbleInput",Xbe=te.forwardRef(({__scopeSlider:e,...t},n)=>{const{value:r,name:s,form:o}=qbe(Zbe,e),i=te.useRef(null),a=m.useComposedRefs(i,n),c=m.usePrevious(r);return te.useEffect(()=>{const u=i.current;if(!u)return;const d=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(d,"value").set;if(c!==r&&h){const p=new Event("input",{bubbles:!0});h.call(u,r),u.dispatchEvent(p)}},[c,r]),l.jsx(m.Primitive.input,{style:{display:"none"},name:s,form:o,...t,ref:a,defaultValue:r})});Xbe.displayName=Zbe;function $kt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Qbe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function zkt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Bkt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function Vkt(e,t,n){const r=e/2,o=Wz([0,50],[0,r]);return(r-o(t)*n)*n}function Hkt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Ukt(e,t){if(t>0){const n=Hkt(e);return Math.min(...n)>=t}return!0}function Wz(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Jbe(e){if(!Number.isFinite(e))return 0;const t=e.toString();if(t.includes("e")){const[r,s]=t.split("e"),o=r.split(".")[1]||"",i=Number(s);return Math.max(0,o.length-i)}const n=t.split(".")[1];return n?n.length:0}function iN(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function qkt(e,{min:t,step:n,direction:r,multiplier:s}){const o=Jbe(n),i=(e-t)/n,a=Math.round(i),c=iN(a*n+t,o)===iN(e,o);let u;return c?u=a+s*r:r>0?u=Math.ceil(i):u=Math.floor(i),iN(u*n+t,o)}function Wkt(e){return typeof e=="function"}const exe=te.forwardRef(({className:e,...t},n)=>l.jsxs(qz,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(Vbe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(Hbe,{className:"absolute h-full bg-primary"})}),l.jsx(Ybe,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));exe.displayName=qz.displayName;function aN(e,t){return`${e.replace(/\/$/,"")}/dashboard-authoring${t}`}function Gkt(e=!0){const{authToken:t,tokenProps:n}=Tt();return Gn({queryKey:["dashboard-authoring-sources",n.apiServiceUrl,n.project_id,n.tenantId,n.endUserId,n.orgUserId,t==null?void 0:t.accessToken],enabled:e&&!!(t!=null&&t.accessToken)&&!!n.apiServiceUrl,queryFn:async()=>(await m.getRequest(aN(n.apiServiceUrl,"/sources"),(t==null?void 0:t.accessToken)||"")).sources||[]})}function Kkt(){const{authToken:e,tokenProps:t}=Tt(),n=(e==null?void 0:e.accessToken)||"",r=t.apiServiceUrl,s=Ao({mutationFn:async a=>(await m.postRequestRegular(aN(r,"/plan"),n,a)).plan}),o=Ao({mutationFn:async a=>{const c="domainId"in a?{mode:"suggestions",domainId:a.domainId,datasetNames:a.datasetNames,instruction:a.instruction}:{mode:"suggestions",dataset:a.dataset,instruction:a.instruction};return(await m.postRequestRegular(aN(r,"/plan"),n,c)).suggestions||[]}}),i=Ao({mutationFn:async a=>{const c="plan"in a?{plan:a.plan,sharing:a.sharing}:{plan:a};return m.postRequestRegular(aN(r,"/create"),n,{...c})}});return{planDashboard:s,suggestDashboards:o,createDashboardFromPlan:i}}const FM="__describe_own__",qx=6,Ykt=350;function OM(e){return e.kind==="semantic"?e.label||e.datasetName:e.label||[e.databaseName,e.schemaName,e.tableName].filter(Boolean).join(".")||e.tableName}function DK(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"){const t=e;return typeof t.label=="string"&&t.label||typeof t.name=="string"&&t.name||typeof t.qualifiedFieldName=="string"&&t.qualifiedFieldName||void 0}}}function MK(e){return e.kind==="semantic"?{kind:"semantic",domainId:e.domainId,datasetName:e.datasetName,datasetId:e.datasetId,label:e.label,connectionId:e.connectionId}:{kind:"physical",connectionId:e.connectionId,databaseName:e.databaseName,schemaName:e.schemaName,tableName:e.tableName,label:e.label}}function Zkt(e){const t=new Map;for(const n of e){if(n.kind!=="semantic")continue;const r=n.domainId;t.has(r)||t.set(r,{id:r,label:n.domainLabel||n.domainName||"Semantic domain",items:[]}),t.get(r).items.push(n)}return Array.from(t.values())}function u1(e){return Array.from(new Set(Array.from(e).map(t=>t.trim()).filter(Boolean)))}function Xkt(e){switch(e){case"kpi":return"KPI";case"line":return"Trend";case"bar":case"stackedBar":return"Breakdown";case"table":return"Table";case"text":return"Text";default:return e?e.replace(/([A-Z])/g," $1"):"Card"}}function Qkt(e){return(e==null?void 0:e.kind)==="semantic"?e.datasetName:void 0}function txe(e){var s,o,i,a,c,u,d;const t=e.analyticsIntent,n=new Set,r=f=>{const h=Qkt(f);h&&n.add(h)};return t&&(r(t.source),t.kind==="metric"&&((s=t.measures)==null||s.forEach(f=>r(f.source)),r((o=t.primaryMeasure)==null?void 0:o.source),(i=t.dimensions)==null||i.forEach(f=>r(f.source)),r((a=t.dateField)==null?void 0:a.source),(c=t.filters)==null||c.forEach(f=>r(f.field.source))),t.kind==="records"&&((u=t.fields)==null||u.forEach(f=>r(f.source)),r((d=t.dateField)==null?void 0:d.source))),n}function Jkt(e){var o;const t=e.sheets.flatMap(i=>i.cards),n=t.filter(i=>i.type!=="text"),r=n.filter(i=>txe(i).size>1),s=((o=e.filterInputs)==null?void 0:o.length)||0;return{cards:t,dataCards:n,joinedCards:r,filterCount:s,datasetCount:e.datasets.length}}function nxe({open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,sources:o,sourcesLoading:i=!1,suggestDashboards:a,planDashboard:c,createDashboardFromPlan:u,settingsSlot:d,blankDescription:f="",description:h="Start blank, or pick a dataset to see starter ideas tailored to your data.",canCreate:p=!0,initialDomainId:g}){const[b,x]=w.useState(()=>g?"dataset":"blank"),[y,v]=w.useState(null),[S,N]=w.useState([]),[C,j]=w.useState(!1),[_,k]=w.useState(null),[I,T]=w.useState(""),[E,D]=w.useState(""),[M,A]=w.useState(""),[P,O]=w.useState(""),[$,V]=w.useState(""),[U,R]=w.useState("idle"),[q,W]=w.useState("choose"),[F,Z]=w.useState(null),K=w.useRef(!1),Y=w.useRef(0),X=w.useRef(null),z=w.useRef(!1),[B,H]=w.useState(!1),L=()=>{Y.current+=1,W("choose"),Z(null)},G=w.useMemo(()=>o.filter(De=>De.kind==="semantic"),[o]),J=G.length>0,oe=b,Q=x,ae=oe==="blank",ie=oe==="dataset",le=i?"Checking datasets...":J?void 0:"No datasets found",ue=w.useMemo(()=>{const De=new Set;for(const mt of G)mt.kind==="semantic"&&De.add(mt.domainId);return De.size===1},[G]),fe=w.useMemo(()=>Zkt(G),[G]);w.useEffect(()=>{if(!e){X.current=null,z.current=!1;return}if(!g||z.current||X.current===g)return;if((y==null?void 0:y.kind)==="semantic"&&y.domainId===g){X.current=g;return}const De=G.filter(Ct=>Ct.kind==="semantic"&&Ct.domainId===g),mt=De[0];mt&&(X.current=g,Q("dataset"),v(mt),N(De.map(Ct=>Ct.datasetName)),j(De.length>1),k(null),Y.current+=1,W("choose"),Z(null),V(""))},[g,e,y,G,Q]),w.useEffect(()=>{!y&&ue&&G.length>0&&(v(G[0]),N([G[0].datasetName]))},[y,ue,G]);const pe=w.useMemo(()=>!y||y.kind!=="semantic"?[]:G.filter(De=>De.kind==="semantic"&&De.domainId===y.domainId),[y,G]);w.useEffect(()=>{if(!y||y.kind!=="semantic"){S.length>0&&N([]),C&&j(!1);return}const De=new Set(pe.map(Ct=>Ct.datasetName));let mt=u1(S).filter(Ct=>De.has(Ct));C||(mt=mt.slice(0,qx)),mt.length===0&&mt.push(y.datasetName),mt.join("|")!==S.join("|")&&N(mt),pe.length<=1&&C&&j(!1)},[S,pe,y,C]);const ge=w.useMemo(()=>new Set(S),[S]),de=w.useMemo(()=>!y||y.kind!=="semantic"?[]:pe.filter(De=>ge.has(De.datasetName)),[ge,pe,y]),ye=C?pe.length:de.length,ce=ie&&!!y&&ye>0,re=w.useMemo(()=>C?new Set(pe.map(De=>De.datasetName)):ge,[C,pe,ge]),ee=w.useMemo(()=>new Set(pe.map(De=>De.datasetName)),[pe]),se=!C&&S.length<qx,ne=ce&&!C&&de.length>1?de.map(De=>De.datasetName):void 0,he=w.useMemo(()=>!y||!ce?"":y.kind==="semantic"?C?`${y.domainId}:whole`:`${y.domainId}:${de.map(De=>De.datasetName).join(",")}`:[y.connectionId,y.databaseName,y.schemaName,y.tableName].filter(Boolean).join(":"),[ce,de,y,C]),[_e,Le]=w.useState(he);w.useEffect(()=>{const De=window.setTimeout(()=>{Le(he)},Ykt);return()=>window.clearTimeout(De)},[he]);const Ue=he===_e;w.useEffect(()=>{e||(Q("blank"),v(null),N([]),j(!1),k(null),T(""),D(""),A(""),O(""),V(""),R("idle"),L())},[e,Q]);const je=w.useMemo(()=>{if(!y||!ce||!Ue)return null;if(y.kind==="semantic"&&(C||de.length>1))return["dashboard-suggestions","semantic-domain",y.domainId,C?"whole":de.map(De=>De.datasetName).join(","),E];if(y.kind==="semantic"){const De=de[0]||y;return["dashboard-suggestions","semantic",De.domainId,De.datasetName,E]}return["dashboard-suggestions","physical",y.connectionId,y.databaseName,y.schemaName,y.tableName,E]},[E,ce,de,y,Ue,C]),Xe=w.useMemo(()=>!y||!ce||!Ue?null:y.kind==="semantic"&&(C||de.length>1)?{domainId:y.domainId,datasetNames:ne,instruction:E||void 0}:{dataset:MK(de[0]||y),instruction:E||void 0},[E,ce,ne,de,y,Ue,C]),Ze=Gn({queryKey:je??["dashboard-suggestions","idle"],queryFn:()=>a(Xe),enabled:!!Xe&&e,staleTime:5*60*1e3,gcTime:10*60*1e3}),at=Ze.data??null,Be=(je==null?void 0:je.join("|"))??"";w.useEffect(()=>{k(null),L()},[Be]);const lt=()=>{!y||!ce||(k(null),L(),Ze.refetch())},Te=w.useMemo(()=>(at==null?void 0:at.find(De=>De.id===_))||null,[at,_]),nt=(y==null?void 0:y.kind)==="semantic"&&fe.find(De=>De.id===y.domainId)||null,Oe=(nt==null?void 0:nt.label)||"this domain",He=y?C?`All ${pe.length} datasets in ${Oe}`:`${ye} of ${pe.length} datasets in ${Oe}`:le||"Pick data to see recommendations",qe=De=>{if(De.kind!=="semantic")return;z.current=!0;const mt=(y==null?void 0:y.kind)==="semantic"&&y.domainId===De.domainId;v(De),j(!1),N(Ct=>mt&&Ct.length>0&&!C?Ct.slice(0,qx):[De.datasetName]),k(null),L(),V("")},Ae=De=>{if(De.kind!=="semantic")return;z.current=!0;const mt=(y==null?void 0:y.kind)==="semantic"&&y.domainId===De.domainId;v(De),j(!1),N(Ct=>{const Kt=mt&&!C?Ct:[],Bt=new Set(Kt);if(Bt.has(De.datasetName))Bt.delete(De.datasetName);else{if(Bt.size>=qx)return u1(Bt);Bt.add(De.datasetName)}return Bt.size===0&&Bt.add(De.datasetName),u1(Bt)}),k(null),L(),V("")},Qe=De=>{const mt=De.items[0];mt&&(z.current=!0,v(mt),N(De.items.map(Ct=>Ct.datasetName)),j(!0),k(null),L(),V(""))},ct=De=>{const mt=pe.find(Ct=>Ct.datasetName===De);mt&&(re.has(De)||Ae(mt))},It=I.trim(),yt=ce&&It!==E,kt=()=>{yt&&(D(It),k(null),L(),V(""))},Mt=De=>{De.key!=="Enter"||De.shiftKey||De.nativeEvent.isComposing||(De.preventDefault(),kt())},vt=_===FM,St=_!==null&&!vt,ke=M.trim().length>0,Ee=St||vt&&ke,Pe=P.trim().length>0,Fe=ie&&ce&&!C&&de.length===1,Ge=ie&&ce&&!Ee&&!Fe,Pt=ae||ie&&!Ee&&Fe,_t=q==="review"&&!!F,Ft=ae?Pe:ie&&ce&&(Ee||Pe&&Fe),Vt=B||c.isPending||u.isPending||s,Ht=Ee&&Vt?U==="validating"?"Validating cards against your data.":"This usually takes about 30 seconds.":null,Qn=()=>{var Kt;if(!y)return null;const De=(Te==null?void 0:Te.prompt)||M.trim()||"Create a starter dashboard.",mt=u1(((Kt=Te==null?void 0:Te.datasets)==null?void 0:Kt.map(Bt=>Bt.name))||[]),Ct=y.kind==="semantic"?mt.length>1?mt:ne:void 0;return y.kind==="semantic"&&(C||de.length>1)?{prompt:De,domainId:y.domainId,datasetNames:Ct}:{prompt:De,dataset:MK(de[0]||y)}},st=async()=>{if(K.current||Vt)return;K.current=!0,H(!0),V("");let De=null;try{if(ae){await n({title:P.trim()||"Untitled dashboard",description:f});return}if(!y)return;if(!Ee){if(!Fe)return;await n({title:P.trim()||"Untitled dashboard",description:f,dataset:de[0]||y});return}if(!F){const Kt=Qn();if(!Kt)return;const Bt=Y.current+1;Y.current=Bt,De=Bt,R("planning");const Xt=await c.mutateAsync(Kt);if(Y.current!==Bt)return;Z(Xt),W("review");return}const mt=P.trim()?{...F,title:P.trim()}:F;R("validating");const Ct=await u.mutateAsync(mt);r(Ct)}catch(mt){if(De!==null&&Y.current!==De)return;V(m.getRequestErrorMessage(mt,"The dashboard could not be created from this recommendation."))}finally{K.current=!1,H(!1),R("idle")}};return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{className:`flex max-w-[94vw] flex-col gap-0 overflow-hidden p-0 transition-[width,height] duration-300 ease-out motion-reduce:transition-none ${ie?"h-[720px] max-h-[88vh] w-[1120px]":"h-[440px] w-[520px]"}`,children:[l.jsx("div",{className:"shrink-0 border-b border-border px-5 pt-4 pb-3.5",children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx(Ts,{className:"text-[15px] font-semibold tracking-tight",children:"New dashboard"}),l.jsx(Ks,{className:"mt-1 text-[12px] leading-[1.5] text-muted-foreground",children:ie?le||"Pick data on the left, then choose a starter idea.":h})]}),ie&&l.jsx("button",{type:"button",onClick:()=>{z.current=!0,Q("blank"),k(null),A(""),L(),V("")},className:"mr-6 mt-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:"Start blank instead"})]})}),ae?l.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[l.jsx(AK,{kind:"blank",selected:!0,onClick:()=>{z.current=!0,Q("blank"),k(null),A(""),V("")}}),l.jsx(AK,{kind:"dataset",selected:!1,hint:le,onClick:()=>{Q("dataset"),V("")}})]}),l.jsxs("div",{className:"mt-4",children:[l.jsx(RK,{children:"Title"}),l.jsx("input",{type:"text",value:P,onChange:De=>O(De.target.value),placeholder:"Name your dashboard",className:"mt-1 block h-7 w-full rounded-[5px] border border-border bg-background px-2 text-[12px] text-foreground focus:border-foreground/40 focus:outline-none"})]}),d?l.jsx("div",{className:"mt-4",children:d}):null]}):l.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[320px_1fr] overflow-hidden",children:[l.jsx(r_t,{groups:fe,loading:i,selectedSource:y,selectedDatasetNames:ge,useWholeDomain:C,selectionLimit:qx,onPickSource:qe,onToggleDataset:Ae,onUseWholeDomain:Qe,summary:ce?He:null}),l.jsxs("div",{className:"flex min-w-0 flex-col overflow-hidden",children:[q==="choose"&&l.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:l.jsxs("div",{className:"flex items-end gap-2 rounded-[6px] border border-border bg-background px-3 py-2 focus-within:border-foreground/40",children:[l.jsx("textarea",{rows:2,value:I,onChange:De=>T(De.target.value),onKeyDown:Mt,placeholder:"Add context to steer every idea. e.g. focus on last quarter, use USD, exclude internal accounts.",className:"block flex-1 resize-none bg-transparent text-[12px] leading-[1.55] text-foreground placeholder:text-muted-foreground focus:outline-none"}),l.jsx(m.Button,{type:"button",size:"xs",variant:It?"default":"secondary",disabled:!yt,onClick:kt,children:"Update ideas"})]})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-4 border-b border-border px-4 py-2",children:[l.jsx(t_t,{step:_t?"review":"choose"}),!_t&&l.jsxs("button",{type:"button",onClick:lt,disabled:!ce||at===null,className:"ml-auto inline-flex h-6 items-center gap-1 rounded-[3px] px-1.5 text-[10.5px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50",children:[l.jsx(Xl,{className:"h-2.5 w-2.5"}),"Suggest more"]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[_t?l.jsx(n_t,{plan:F,titleOverride:P.trim()}):ce?l.jsx("div",{children:at===null?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Fetching recommendations…"]}),l.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Array.from({length:4}).map((De,mt)=>l.jsx(a_t,{},mt))})]}):l.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[at.slice(0,4).map(De=>l.jsx(s_t,{suggestion:De,selected:_===De.id,selectedDatasetNames:re,domainDatasetNames:ee,canAddDataset:se,onAddDataset:ct,onClick:()=>{k(mt=>mt===De.id?null:De.id),A(""),L(),V("")}},De.id)),l.jsx(i_t,{selected:vt,onClick:()=>{k(De=>De===FM?null:FM),L(),V("")}})]})}):l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-1 text-center",children:[l.jsx(fo,{className:"h-5 w-5 text-muted-foreground"}),l.jsx("div",{className:"mt-2 text-[12.5px] font-medium text-foreground",children:i?"Loading datasets…":"Pick data to see recommendations"}),l.jsx("div",{className:"max-w-[320px] text-[11.5px] leading-relaxed text-muted-foreground",children:"Pick one or more datasets on the left, or All datasets in a domain."})]}),vt&&l.jsx("div",{className:"mt-3 rounded-[5px] border border-border bg-background focus-within:border-foreground/40",children:l.jsx("textarea",{rows:3,autoFocus:!0,value:M,onChange:De=>{A(De.target.value),L(),V("")},placeholder:"e.g. Executive view with revenue KPIs, weekly trend, and a top-customers table.",className:"block w-full resize-none bg-transparent px-2.5 py-2 text-[12px] leading-[1.55] text-foreground placeholder:text-muted-foreground focus:outline-none"})}),ce&&(Ee||Fe)&&l.jsxs("div",{className:"mt-4",children:[l.jsx(RK,{children:Pt?"Title":"Title (optional)"}),l.jsx("input",{type:"text",value:P,onChange:De=>O(De.target.value),placeholder:Pt?"Name your dashboard":(Te==null?void 0:Te.title)||"We will suggest one",className:"mt-1 block h-7 w-full rounded-[5px] border border-border bg-background px-2 text-[12px] text-foreground focus:border-foreground/40 focus:outline-none"})]}),Ge&&l.jsx("div",{className:"mt-4 rounded-[5px] border border-border bg-muted/30 px-3 py-2 text-[11.5px] leading-relaxed text-muted-foreground",children:"Choose a recommendation or describe what you want to create from this data scope."}),$&&l.jsx("div",{className:"mt-4 rounded-[5px] border border-destructive/30 bg-destructive/5 px-3 py-2 text-[11.5px] leading-relaxed text-destructive",children:$}),d?l.jsx("div",{className:"mt-4",children:d}):null]})]})]}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-3 border-t border-border bg-muted/30 px-5 py-2.5",children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Ht?l.jsx("span",{className:"truncate text-right text-[11px] text-muted-foreground",children:Ht}):null,l.jsx(m.Button,{type:"button",variant:"ghost",size:"xs",onClick:()=>t(!1),disabled:Vt,children:"Cancel"}),_t?l.jsx(m.Button,{type:"button",variant:"secondary",size:"xs",onClick:()=>{L(),V("")},disabled:Vt,children:"Back to ideas"}):null,l.jsx(m.Button,{type:"button",size:"xs",disabled:!Ft||!p||Vt,onClick:st,children:Vt?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),Ee?U==="planning"?"Planning Insights…":U==="validating"?"Validating cards…":"Building dashboard…":"Creating…"]}):l.jsxs(l.Fragment,{children:[Ee&&!_t?"Review plan":"Create dashboard",l.jsx(Lv,{className:"h-3 w-3"})]})})]})})]})})}function e_t({open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,initialDomainId:o}){const i=Gkt(e),{suggestDashboards:a,planDashboard:c,createDashboardFromPlan:u}=Kkt();return l.jsx(nxe,{open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,sources:i.data||[],sourcesLoading:i.isLoading,suggestDashboards:a.mutateAsync,planDashboard:c,createDashboardFromPlan:u,initialDomainId:o})}function t_t({step:e}){const t=[{id:"choose",label:"Choose idea"},{id:"review",label:"Review plan"}],n=t.findIndex(r=>r.id===e);return l.jsx("div",{className:"flex items-center gap-2",children:t.map((r,s)=>{const o=r.id===e,i=s<n;return l.jsxs("div",{className:"flex items-center gap-2",children:[s>0&&l.jsx("span",{className:"h-px w-4 bg-border","aria-hidden":"true"}),l.jsxs("span",{className:`inline-flex h-5 items-center gap-1 rounded-full px-2 text-[10px] font-medium ${o?"bg-foreground text-background":i?"bg-muted text-foreground":"bg-transparent text-muted-foreground"}`,children:[i?l.jsx(m.Check,{className:"h-2.5 w-2.5"}):l.jsx("span",{children:s+1}),r.label]})]},r.id)})})}function n_t({plan:e,titleOverride:t}){const n=Jkt(e),r=e.datasets.map(o=>o.kind==="semantic"?o.label||o.datasetName:o.kind==="physical"?o.label||[o.databaseName,o.schemaName,o.tableName].filter(Boolean).join(".")||o.tableName:o.label||"Dataset"),s=[...(e.warnings||[]).map(o=>o.message),...e.unresolvedRequests||[]].filter(Boolean);return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:t||e.title||"Dashboard plan"}),e.description&&l.jsx("div",{className:"mt-1 max-w-[680px] text-[11.5px] leading-relaxed text-muted-foreground",children:e.description})]}),l.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[l.jsx(d1,{label:"Cards",value:n.dataCards.length}),l.jsx(d1,{label:"Datasets",value:n.datasetCount}),l.jsx(d1,{label:"Filters",value:n.filterCount}),l.jsx(d1,{label:"Joined cards",value:n.joinedCards.length})]}),l.jsxs("div",{children:[l.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Cards to create"}),l.jsx("div",{className:"divide-y divide-border rounded-[6px] border border-border",children:n.cards.slice(0,mxe.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS).map(o=>{const i=Array.from(txe(o));return l.jsxs("div",{className:"grid grid-cols-[88px_1fr_auto] items-center gap-2 px-2.5 py-2",children:[l.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:Xkt(o.type)}),l.jsx("span",{className:"min-w-0 truncate text-[12px] text-foreground",children:o.title}),i.length>0&&l.jsx("span",{className:"max-w-[220px] truncate text-[10.5px] text-muted-foreground",children:i.join(" + ")})]},o.id)})})]}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsx(LM,{title:"Datasets",empty:"No datasets selected",items:r}),l.jsx(LM,{title:"Filters",empty:"No dashboard filters planned",items:(e.filterInputs||[]).map(o=>o.label)})]}),n.joinedCards.length>0&&l.jsx(LM,{title:"Relationship-based cards",empty:"No relationship-based cards planned",items:n.joinedCards.map(o=>o.title)}),s.length>0&&l.jsx("div",{className:"rounded-[6px] border border-amber-300/60 bg-amber-50/60 px-3 py-2 text-[11.5px] leading-relaxed text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300",children:s.slice(0,3).map(o=>l.jsx("div",{children:o},o))})]})}function d1({label:e,value:t}){return l.jsxs("div",{className:"rounded-[6px] border border-border bg-muted/20 px-2.5 py-2",children:[l.jsx("div",{className:"text-[15px] font-semibold tabular-nums text-foreground",children:t}),l.jsx("div",{className:"mt-0.5 truncate text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:e})]})}function LM({title:e,empty:t,items:n}){return l.jsxs("div",{children:[l.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),l.jsx("div",{className:"min-h-10 rounded-[6px] border border-border px-2.5 py-2 text-[11.5px] leading-relaxed",children:n.length>0?l.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.slice(0,8).map(r=>l.jsx("span",{className:"max-w-full truncate rounded-[3px] bg-muted px-1.5 py-0.5 text-muted-foreground",children:r},r))}):l.jsx("span",{className:"text-muted-foreground",children:t})})]})}function r_t({groups:e,loading:t,selectedSource:n,selectedDatasetNames:r,useWholeDomain:s,selectionLimit:o,onPickSource:i,onToggleDataset:a,onUseWholeDomain:c,summary:u}){const[d,f]=w.useState(""),[h,p]=w.useState({}),g=d.trim().toLowerCase(),b=(n==null?void 0:n.kind)==="semantic"?n.domainId:null,x=!s&&r.size>=o,y=N=>!g||(N||"").toLowerCase().includes(g),v=e.filter(N=>y(N.label)||N.items.some(C=>y(OM(C)))),S=N=>h[N.id]!==void 0?h[N.id]:g||e.length===1?!0:N.id===b;return l.jsxs("div",{className:"flex min-w-0 flex-col overflow-hidden border-r border-border",children:[l.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2.5",children:[l.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 focus-within:border-foreground/40",children:[l.jsx(Ot.Search,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("input",{value:d,onChange:N=>f(N.target.value),placeholder:"Search datasets…",className:"h-7 flex-1 bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),d&&l.jsx("button",{type:"button",onClick:()=>f(""),className:"flex h-4 w-4 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-accent hover:text-foreground",children:l.jsx(Ce.X,{className:"h-2.5 w-2.5"})})]}),l.jsxs("div",{className:"mt-2.5 flex items-center justify-between gap-2",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Dashboard scope"}),x&&l.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Max ",o," · clear one to swap"]})]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto px-2 py-2",children:[t&&l.jsxs("div",{className:"flex items-center gap-2 px-1 py-2 text-[11px] text-muted-foreground",children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Loading datasets…"]}),!t&&v.length===0&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[l.jsx("div",{className:"text-[12px] text-foreground",children:"No datasets found"}),l.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:"Try a different search or connect a semantic domain."})]}),v.map(N=>{const C=S(N),j=b===N.id&&s,_=j?N.items.length:N.items.filter(T=>b===N.id&&r.has(T.datasetName)).length,k=y(N.label),I=g&&!k?N.items.filter(T=>y(OM(T))):N.items;return l.jsxs("div",{className:"mb-0.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5 rounded-[4px] px-1.5 py-1.5 hover:bg-accent/60",children:[l.jsxs("button",{type:"button",onClick:()=>p(T=>({...T,[N.id]:!C})),className:"flex min-w-0 flex-1 items-center gap-1.5 text-left",children:[C?l.jsx(Ce.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):l.jsx(Ot.ChevronRight,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx(fo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:N.label}),l.jsx("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:_>0?`${_}/${N.items.length}`:N.items.length})]}),j?l.jsxs("button",{type:"button",onClick:()=>i(N.items[0]),className:"inline-flex h-5 items-center gap-1 rounded-[3px] bg-foreground px-1.5 text-[10px] font-medium text-background",title:"All datasets in this domain are selected. Click to go back to picking datasets.",children:[l.jsx(zv,{className:"h-2.5 w-2.5"}),"All datasets"]}):l.jsx("button",{type:"button",onClick:()=>c(N),className:"inline-flex h-5 items-center rounded-[3px] border border-border px-1.5 text-[10px] font-medium text-muted-foreground hover:border-foreground/40 hover:text-foreground",title:"Use every dataset in this domain",children:"All datasets"})]}),C&&l.jsx("div",{className:"ml-3.5 border-l border-border pl-1.5",children:I.map(T=>{const E=j||b===N.id&&r.has(T.datasetName),D=b===N.id&&!s&&!E&&r.size>=o;return l.jsxs("button",{type:"button",onClick:()=>a(T),disabled:D,"aria-pressed":E,className:`flex w-full items-center gap-2 rounded-[4px] px-1.5 py-1.5 text-left ${E?"bg-accent":"hover:bg-accent/60"} ${D?"cursor-not-allowed opacity-45 hover:bg-transparent":""}`,children:[l.jsx("span",{className:`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-[4px] border ${E?"border-foreground bg-foreground text-background":"border-border"}`,children:E&&l.jsx(m.Check,{className:"h-2.5 w-2.5"})}),l.jsx(m.Table2,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"flex-1 truncate text-[12px] text-foreground/90",children:OM(T)}),DK(T.primaryDateField)&&l.jsx("span",{className:"truncate text-[10px] text-muted-foreground",children:DK(T.primaryDateField)})]},`${N.id}:${T.datasetName}`)})})]},N.id)})]}),l.jsx("div",{className:"shrink-0 border-t border-border px-3 py-2.5 text-[11px] leading-relaxed",children:u?l.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground",children:[l.jsx(Exe,{className:"h-3 w-3 shrink-0"}),l.jsx("span",{className:"font-medium text-foreground",children:u})]}):l.jsx("span",{className:"text-muted-foreground",children:"Pick data to see recommendations."})})]})}function s_t({suggestion:e,selected:t,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o,onClick:i}){var a;return l.jsxs("div",{className:`group relative flex flex-col overflow-hidden rounded-[5px] border bg-background transition-colors ${t?"border-foreground":"border-border hover:border-foreground/30"}`,children:[l.jsxs("button",{type:"button",onClick:i,className:"block w-full px-2.5 pt-2.5 pb-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground/40",children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"truncate text-[12.5px] font-medium text-foreground",title:e.title,children:e.title}),l.jsx("div",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",title:e.description,children:e.description})]}),t&&l.jsx("div",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full bg-foreground",children:l.jsx(m.Check,{className:"h-2.5 w-2.5 text-background"})})]}),l.jsx("div",{className:"mt-2 flex gap-1",children:e.preview.slice(0,5).map((c,u)=>l.jsx(l_t,{kind:c},u))})]}),l.jsx("div",{className:"flex flex-wrap items-center gap-1.5 px-2.5 pb-2.5 pt-1.5 text-[10px] text-muted-foreground",children:(a=e.datasets)!=null&&a.length?l.jsx(o_t,{datasets:e.datasets,relationshipHints:e.relationshipHints,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o}):l.jsxs(l.Fragment,{children:[l.jsxs("span",{children:[e.cardCount," cards"]}),e.filterCount>0&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-border",children:"·"}),l.jsxs("span",{children:[e.filterCount," filter",e.filterCount>1?"s":""]})]})]})})]})}function o_t({datasets:e,relationshipHints:t,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o}){const i=t!=null&&t.length?t.join(`
1320
+ `).trim(),k=j.map((I,T)=>{var M,A;let E="",D;if((M=I.url)!=null&&M.startsWith("data:")){const P=I.url.match(/data:[^;]+;base64,(.+)/);P&&(E=P[1],(A=I.mediaType)!=null&&A.startsWith("image/")&&(D=I.url))}return{id:`${e.id||t}-file-${T}`,name:I.filename||`File ${T+1}`,size:0,type:I.mediaType||"application/octet-stream",data:E,preview:D}});return l.jsx(gNt,{text:_||void 0,files:k.length>0?k:void 0})}const f=((S=e.parts)==null?void 0:S.filter(C=>C.type==="reasoning"))||[],h=f.length>0,p=f.some(C=>C.state==="streaming"),g=f.filter(C=>C.text&&C.text.trim().length>0),b=h&&(g.length>0||p)?l.jsxs(fu,{className:"space-y-2",defaultOpen:!1,children:[l.jsx(hu,{asChild:!0,children:l.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),l.jsx("span",{className:p?"animate-pulse":"",children:p?"Reasoning":"Show reasoning"}),g.length>1&&l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),l.jsx(mu,{children:l.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((C,j)=>l.jsxs("li",{className:"relative",children:[l.jsx("span",{className:"absolute -left-[15px] top-[3px] grid h-4 w-4 place-items-center rounded-full bg-muted font-mono text-[9px] text-muted-foreground",children:j+1}),l.jsx(mK,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:C.text})]},`${e.id||t}-reasoning-${j}`))})})]},`${e.id||t}-reasoning`):null,x=(N=e.parts)==null?void 0:N.map((C,j)=>{var k;const _=`${e.id||t}-${j}`;switch(C.type){case"text":{const I=typeof C.text=="string"?C.text:JSON.stringify(C.text??"",null,2);if(e.role==="assistant"){const{cleanedText:T,quickReplies:E}=fNt(I),D=T.trim().length>0;return l.jsxs("div",{className:"space-y-2.5",children:[D&&l.jsx(mK,{text:T,handleRun:i,onAddToDashboard:s,messageId:e.id,messages:n}),E.length>0&&a&&d&&l.jsxs("div",{className:"space-y-1.5",children:[E.length>=3&&l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),l.jsx("div",{className:"flex flex-wrap gap-1",children:E.map(({label:M,value:A},P)=>l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-6 max-w-[220px] rounded-control border-border/60 bg-background px-2 text-[11px] font-normal text-foreground/85 transition-colors hover:border-border hover:bg-muted/40 hover:text-foreground disabled:opacity-50",disabled:c,onClick:()=>a(A),children:l.jsx("span",{className:"truncate",children:M})})}),l.jsx(m.TooltipContent,{side:"top",align:"center",children:l.jsx("p",{className:"max-w-xs text-xs",children:A})})]},`${_}-qr-${P}`))})]})]},_)}return e.role==="system"&&o?l.jsx(bNt,{text:I},_):null}case"error":{const I=C,T=I.errorText??I.error??I.message;return l.jsx("div",{className:"my-4",children:l.jsx(Lz,{errorMessage:T})},_)}case"reasoning":return null;default:return((k=C.type)!=null&&k.startsWith("tool-")||C.type==="dynamic-tool")&&Oz(C,r)?l.jsx(Za,{FallbackComponent:({error:I,resetErrorBoundary:T})=>l.jsx(pNt,{error:I,resetErrorBoundary:T}),children:l.jsx(aNt,{part:C,idx:_,messageId:e.id,showTools:r,onAddToDashboard:s,messages:n})},_):null}});return e.role==="assistant"?lbe(e,r)?l.jsxs(abe,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:l.jsxs("div",{className:"space-y-2",children:[b,x]})}const wNt=8,SNt=24,CNt=20;function NNt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function cbe({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i=!1,status:a,errorMessage:c,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:p,scrollToEndSignal:g=0}){const b=w.useRef(null),x=w.useRef(null),y=w.useRef(e.length),v=w.useRef(!1),S=w.useRef(null),N=w.useRef(!1),C=w.useRef(g),[j,_]=w.useState(!0),[k,I]=w.useState(0),[T,E]=w.useState(SNt);C.current!==g&&(C.current=g,N.current=!0);const D=e[e.length-1],M=lbe(D,t),A=NNt(a,c,u,M),P=X_({count:e.length,getScrollElement:()=>b.current,estimateSize:U=>{const R=e[U];return(R==null?void 0:R.role)==="user"?88:180},getItemKey:U=>{const R=e[U];return(R==null?void 0:R.id)||`message-${U}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:wNt,overscan:6,gap:20,paddingEnd:A?T+CNt:0,useAnimationFrameWithResizeObserver:!0,onChange:U=>{const R=U.isAtEnd();_(q=>q===R?q:R),R&&I(0)}}),O=w.useCallback((U="smooth")=>{S.current!==null&&cancelAnimationFrame(S.current),S.current=requestAnimationFrame(()=>{S.current=null,P.scrollToEnd({behavior:U})}),I(0),_(!0)},[P]);w.useLayoutEffect(()=>{v.current||(v.current=!0,O("auto"))},[O]),w.useLayoutEffect(()=>{N.current&&(N.current=!1,O("auto"))},[e.length,g,O]),w.useEffect(()=>{const U=y.current;y.current=e.length,e.length>U&&!P.isAtEnd()&&I(R=>R+e.length-U),e.length===0&&(I(0),_(!0),v.current=!1,N.current=!1)},[e.length,P]);const $=P.getVirtualItems(),V=P.getTotalSize();return w.useEffect(()=>()=>{S.current!==null&&cancelAnimationFrame(S.current)},[]),w.useLayoutEffect(()=>{const U=x.current;if(!U||!A)return;const R=()=>{const W=Math.ceil(U.getBoundingClientRect().height);W>0&&E(F=>F===W?F:W)};if(R(),typeof ResizeObserver>"u")return;const q=new ResizeObserver(R);return q.observe(U),()=>q.disconnect()},[A,a,c,u]),l.jsxs(l.Fragment,{children:[l.jsx(il,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:m.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:l.jsxs("div",{className:"relative w-full",style:{height:V},children:[$.map(U=>{const R=e[U.index];return R?l.jsx("div",{ref:P.measureElement,"data-index":U.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${U.start}px)`},children:l.jsx("div",{className:m.cn("min-w-0",f),children:l.jsx(vNt,{message:R,messageIndex:U.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i})})},U.key):null}),A&&l.jsx("div",{ref:x,className:m.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max(V-T,0)}px)`},children:l.jsx("div",{className:m.cn("min-w-0",f),children:l.jsx(xNt,{status:a,errorMessage:c,activeToolText:u})})})]})}),!j&&l.jsxs("button",{type:"button",onClick:()=>O("smooth"),"aria-label":"Scroll to latest",className:m.cn("absolute right-4 z-10 inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-[11px] text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.08)] transition-colors hover:bg-muted/40",p),children:[l.jsx(ro,{className:"h-3 w-3"}),"Latest",k>0&&l.jsx("span",{className:"grid h-4 min-w-[16px] place-items-center rounded-full bg-foreground px-1 font-mono text-[9px] tabular-nums text-background",children:k>9?"9+":k})]})]})}function jNt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";const t=e;return(typeof t.userSql=="string"?t.userSql:"")||(typeof t.sourceSql=="string"?t.sourceSql:"")||(typeof t.sql=="string"?t.sql:"")}const kNt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function _Nt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=w.useState(!1),[a,c]=w.useState(m.isDevEnv),[u,d]=w.useState(!1),[f,h]=w.useState("auto"),[p,g]=w.useState(!1),[b,x]=w.useState(!1),[y,v]=w.useState(0),S=n??b,{isLocalDev:N,isConsoleMode:C}=Vm(),j=N||C||a,_=w.useRef(null);m.useDashboardStore(ne=>ne.dashboard.aiScopeTables),m.useDashboardStore(ne=>ne.isDashboardEditing);const k=m.useDashboardStore(ne=>ne.selectedSheetId),{setDataSource:I}=m.useEditorActions(),{setSelectedFrameId:T,setIsDashboardEditing:E}=m.useDashboardActions(),D=U$(),{clearAssistantMessageContexts:M}=m.useAIActions(),{clearQueue:A}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:O}=m.useFileActions(),$=m.useFileAttachments("dashboard"),V=m.useEditorStore(ne=>ne.card.dataSource),{assistantProfile:U}=Nge(),R=m.useDashboardStore(ne=>ne.handleOpenAssistantProfile),{selectedEntities:q,applyDashboardDefaultEntities:W}=XI("dashboard"),{sendMessage:F,isLoading:Z,messages:K,setMessages:Y,status:X,stop:z,errorMessage:B,clearError:H}=OSt({dynamicVisualMode:f}),L=w.useCallback(()=>{v(ne=>ne+1)},[]),G=w.useCallback(ne=>{r==null||r(ne),n===void 0&&x(ne)},[n,r]),J=w.useCallback(()=>{G(!S)},[S,G]);w.useEffect(()=>{if(!S)return;function ne(he){he.key==="Escape"&&G(!1)}return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[S,G]);const[oe,Q]=w.useState(""),ae=ne=>{Q(ne.target.value)};async function ie({sql:ne,cardTitle:he,connectionId:_e,cardType:Le,python:Ue,cardConfig:je,dataSource:Xe,customVisualPreferences:Ze,visualizationMode:at,dynamicCardPreferences:Be}){if(!k)return;const lt=at==="dynamic",Te=Zl.hasValidCardConfig(je),nt=_e||(Xe==null?void 0:Xe.connectionId)||"",Oe=Xe?{...Xe,connectionId:nt||Xe.connectionId,connectionType:Xe.connectionType||"",mode:Xe.mode||"database",selectedEntities:Xe.selectedEntities||[]}:nt?{connectionId:nt,connectionType:"",mode:"database",selectedEntities:[]}:eb,qe=!(Te&&(!lt||(Be==null?void 0:Be.provenance)==="card-config"||(Be==null?void 0:Be.provenance)==="query_spec")),Ae=qe?jNt(ne):"",Qe=qe?Ue:"",ct={id:m.v4(),title:he||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Le==="horizontalBar"?"y":"x"},...lt&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Le,sql:Ae,python:Qe,dataSource:Oe,config:je,connectionId:nt,visualizationMode:at,dynamicCardPreferences:Be,customCardPreferences:Ze?{url:Ze.url,componentName:Ze.componentName,pluginChartType:Ze.pluginChartType,settings:Ze.settings,type:"component"}:void 0},It={id:m.v4(),cards:[ct],activeCardId:ct.id};try{await D(k,It,"end"),E(!0),T(It.id)}catch(yt){console.error("Failed to add assistant visual to dashboard:",yt),it.error(yt instanceof Error?yt.message:"Failed to prepare semantic metadata for the new visual")}}const le=ne=>{ne.preventDefault();const he=oe.trim();if(!he&&$.length===0)return;const _e=[];he&&_e.push({type:"text",text:he}),$.forEach(Le=>{Le.data&&_e.push({type:"file",mediaType:Le.type,filename:Le.name,url:`data:${Le.type};base64,${Le.data}`})}),F({role:"user",parts:_e}),Q(""),P("dashboard"),L()};w.useEffect(()=>{var ne;e&&((ne=_.current)==null||ne.focus())},[e]),zge({assistantType:"dashboard",status:X,isLoading:Z,sendMessage:F});const{hasActiveTools:ue,activeToolText:fe}=Bge(K);function pe(ne){const he={role:"user",parts:[{type:"text",text:ne.title+" "+ne.subtitle}]};F(he),L()}function ge(ne){F({role:"user",parts:[{type:"text",text:ne}]}),L()}function de(ne){F({role:"user",parts:[{type:"text",text:ne}]}),L()}const ye=w.useCallback(async()=>{const ne=JSON.stringify(K??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ne),it.success("Conversation copied")}catch(he){console.error("Failed to copy conversation",he),it.error("Unable to copy conversation")}},[K]),ce=(oe==null?void 0:oe.length)===0&&(K==null?void 0:K.filter(ne=>ne.role==="user").length)===0;function re(){return l.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:l.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ee(){return l.jsxs(Ys,{children:[l.jsx(Zs,{asChild:!0,children:l.jsx(Yc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(ym,{className:"size-3.5"})})}),l.jsxs(Es,{align:"end",children:[l.jsx($a,{children:"Options"}),l.jsx(Sa,{}),l.jsx(Gu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(Gu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(Gu,{checked:u,onCheckedChange:d,children:"System Message"}),(N||C)&&l.jsxs(l.Fragment,{children:[l.jsx(Sa,{}),l.jsx($a,{children:"Dynamic Visuals"}),l.jsx(Gu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(Gu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(Gu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const se=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("relative flex h-full grow flex-col break-words bg-background",S&&"rounded-card border border-border/60 shadow-xl"),children:[l.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[re(),R&&l.jsxs("button",{type:"button",onClick:R,className:"inline-flex h-6 items-center gap-1 rounded-[4px] border border-border/60 bg-muted/40 px-1.5 text-[11px] text-muted-foreground transition-colors hover:border-border hover:text-foreground",title:"Edit assistant profile",children:[l.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),l.jsx("span",{className:"max-w-[180px] truncate",children:(U==null?void 0:U.name)||"Default profile"})]}),l.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[C&&ee(),j&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 px-1.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:ye,children:"Copy Conversation"}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:S?"Exit fullscreen":"Expand",onClick:J,children:S?l.jsx(Ot.Minimize2,{className:"h-3.5 w-3.5"}):l.jsx(Ot.Maximize2,{className:"h-3.5 w-3.5"})}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"New chat",onClick:()=>{const ne=K.filter(he=>he.role==="assistant").map(he=>he.id).filter(he=>!!he);Y([]),A("dashboard"),H(),M(ne)},children:l.jsx(lO,{className:"h-3.5 w-3.5"})}),l.jsx(Yc,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"Close",onClick:()=>{t(!1)},children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]})]}),l.jsx(cbe,{messages:K,showTools:a,showSystemMessage:u,onAddToDashboard:ie,onQuickReply:de,disableQuickReplies:Z,status:X,errorMessage:B,activeToolText:Z&&ue?fe:void 0,className:m.cn(S?"px-6 py-5":"px-3 py-3"),rowContentClassName:m.cn(S&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),l.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!U&&ce&&l.jsx(ope,{onClick:pe,placeholders:kNt}),ce&&U&&l.jsx(jge,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:ge}),l.jsx($ge,{assistantType:"dashboard"}),l.jsx(Pz,{ref:_,setInput:Q,stop:z,input:oe,handleInputChange:ae,handleSubmit:ne=>{le(ne)},isLoading:Z,status:X,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(Rz,{incomingSelectedEntities:q,open:p,onOpenChange:g,dataSource:V||eb,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ne=>W()})]});return S&&s?Dr.createPortal(l.jsx(Vb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background/95 px-4 pb-4 pt-[calc(var(--app-header-height,15px)+0.5rem)] backdrop-blur-sm",children:l.jsx("div",{className:"flex h-full w-full",children:se})}),s):se}function INt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=ice(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);w.useEffect(()=>{if(!c||u)return;async function d(p){if(TNt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),it.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=ENt(p);if(g!=null&&g.id){const b=rce(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),it.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function TNt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function ENt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function ube(e){const t=w.useCallback(o=>`semaphor-default-sheet-${o}`,[]),n=w.useCallback(()=>{if(!e)return null;try{const o=t(e);return localStorage.getItem(o)}catch(o){return console.error("Error reading default sheet preference:",o),null}},[e,t]),r=w.useCallback(o=>{if(!(!e||!o))try{const i=t(e);localStorage.setItem(i,o)}catch(i){console.error("Error saving default sheet preference:",i)}},[e,t]),s=w.useCallback(()=>{if(e)try{const o=t(e);localStorage.removeItem(o)}catch(o){console.error("Error clearing default sheet preference:",o)}},[e,t]);return{getDefaultSheetId:n,setDefaultSheetId:r,clearDefaultSheetId:s}}function DNt(e,t){switch(e.interactionMode){case"drillToDetail":MNt(e,t);break;case"drillThrough":ANt(e,t);break;case"drillToURL":RNt(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 MNt(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 ANt(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 RNt(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 PNt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(Jo,{children:[l.jsx(Ts,{children:i||"Insight Detail"}),l.jsx(Ks,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(dce,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Qde,{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 FNt(){const e=m.useInteractionStore(N=>N.interactionStates),t=m.useInteractionStore(N=>N.setInteractionState),n=m.useInteractionStore(N=>N.clearLastInteractionEvent),r=m.useInteractionStore(N=>N.replaceCardWithInsight),s=m.useInteractionStore(N=>N.setPendingDrillThrough),o=m.useInteractionStore(N=>N.pendingDrillThrough),i=m.useInteractionStore(N=>N.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=_m(),d=m.useDashboardStore(N=>N.dashboard),f=m.useDashboardStore(N=>N.filterValues),{data:h,isLoading:p}=Kde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=w.useState({open:!1,insightId:""}),x=Jde(g.insightId,{enabled:g.open&&!!g.insightId}),y=w.useRef(new Set),v=w.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:N,filters:C,contextMode:j})=>{b({open:!0,insightId:N,filters:C,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:j})},replaceCardContent:({cardId:N,insightId:C,filters:j,contextMode:_})=>{r(N,C,j,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:N,contextMode:C,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k})=>{const I={filters:N},T={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[I]},E={...m.createInitialInteractionState(),appliedClickFilters:[T],contextMode:C,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k};t(m.DRILL_CONTEXT_CARD_ID,E)}}),[a,r,f,c,d,s,t]);w.useEffect(()=>{Object.entries(e).forEach(([N,C])=>{if(C!=null&&C.lastInteractionEvent){const j=C.lastInteractionEvent,_=`${N}-${j.interactionMode}-${j.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{DNt(j,v)}catch(k){console.error("Error executing interaction event:",k)}finally{n(N),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,v]),w.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(N){console.error("[DrillThrough] Error during automatic navigation:",N),i()}},[o,h,p,u,c,i]);const S=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(PNt,{open:g.open,onOpenChange:S,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&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-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function ONt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=LNt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function LNt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function $Nt(e){return e?`Back to ${e}`:"Back"}function zNt(){var y,v,S,N,C;const e=m.useInteractionStore(j=>j.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(j=>j.actions.goBackFromDrill),n=m.useDashboardStore(j=>j.actions.clearDrillContext),{selectDashboard:r}=_m(),[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 j=k=>{o({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((N=(S=(v=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:v.filterGroups)==null?void 0:S[0])==null?void 0:N.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||!((C=e.appliedClickFilters)!=null&&C.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(j){console.error("[DrillBack] Error during back navigation:",j)}},g=()=>{n()},b=j=>{j.target.closest("button")||(a(!0),c.current={x:j.clientX-s.x,y:j.clientY-s.y})};ONt(f);const x=$Nt(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:b,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((j,_)=>{const k=j.field.label||j.field.name,I=String(j.value);return l.jsxs($s,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",I]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(Ce.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(Ov,{className:"mr-2 h-4 w-4"}),x]})})]})})}function BNt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function VNt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=Xb({id:`filter:${e.id}`,disabled:n||!t}),x={transform:Ki.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(j$,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const CK="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",HNt=[];function dbe({open:e,onOpenChange:t}){const[n,r]=w.useState(!1),[s,o]=w.useState(!1),[i,a]=w.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(Y=>{var X;return(X=Y.dashboard)==null?void 0:X.sheets}),u=m.useDashboardStore(Y=>Y.dashboard),d=m.useDashboardStore(Y=>Y.dashboardInputValues),f=m.useDashboardStore(Y=>Y.filterValues),h=m.useDashboardStore(Y=>Y.controlValues),p=m.useDashboardStore(Y=>Y.inlineFilterValuesMap),g=m.useDashboardStore(Y=>Y.cardControlValuesMap),b=m.useDashboardStore(Y=>Y.selectedSheetId),x=m.useDashboardStore(Y=>Y.selectedSheetId?Y.documentInputRuntimeBySheetId[Y.selectedSheetId]:void 0),y=m.useDashboardStore(Y=>Y.isDownloadingPdf),v=m.useDashboardStore(Y=>Y.reportContext),{authToken:S,tokenProps:N}=Tt(),C=c==null?void 0:c.find(Y=>Y.id===b),j=w.useMemo(()=>m.getDashboardExportSheets(c),[c]),_=m.isDocumentSheet(C),k=_&&C?C.document:void 0,I=w.useMemo(()=>_&&C?Jb(u,C.id):[],[C,_,u]),T=I.length>0,E=w.useMemo(()=>_&&C?Rme(u,C.id):!1,[C,_,u]),D=w.useMemo(()=>T?I.map(iS):(k==null?void 0:k.inputs)||HNt,[k,I,T]),M=v==null?void 0:v.calendar.tz,A=w.useMemo(()=>Rhe(D),[D]),P=w.useMemo(()=>Mhe(D,M),[D,M]),O=w.useMemo(()=>Ahe(D),[D]),$=x?x.filterValuesByInputId:P,V=x?x.controlValuesByInputId:O,U=w.useMemo(()=>_?E&&C&&k?oQ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:k.sections.map(Y=>Y.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:M}):Ohe(D,$,V,A,A):[],[k,D,C,_,u,g,h,f,p,d,V,$,A,M,E]),R=!!C,q=j.length>0,W=((c==null?void 0:c.length)||0)>1||_,F=i.sheetSelection==="current"&&(!R||_&&U.length>0)||i.sheetSelection==="all"&&!q;w.useEffect(()=>{e&&i.sheetSelection==="all"&&!q&&a(Y=>({...Y,sheetSelection:"current"}))},[q,e,i.sheetSelection]);const Z=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function K(){if(y){it.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){it.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!R){it.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!q){it.error("No dashboard sheets are available to export");return}o(!0);const Y=i.sheetSelection==="current"&&_,X=Y?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",z=it.loading(X);try{if(Y){if(!k||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){it.dismiss(z),it.error(`Set ${U.join(", ")} before exporting`);return}const H=new Date().toISOString(),L=E?iQ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:k.sections.map(G=>G.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:H,timezone:M}).snapshot:void 0;await M5(N.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:k.page.size,orientation:k.page.orientation,timezone:M,password:i.protectPdf?i.password:void 0,inputSnapshot:L,...L?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:$,controlValuesByInputId:V,generatedAt:H}}})}else{const H=Ete();await hQ(N.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,H)}it.dismiss(z);const B=Y?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";it.success(B,{duration:2e3}),Z()}catch(B){it.dismiss(z),it.error("Failed to download PDF",{description:i_(B,"Please try again or contact support."),descriptionClassName:o_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",B)}finally{o(!1)}}return l.jsx(Gs,{open:e,onOpenChange:Y=>{if(!Y){Z();return}t(!0)},children:l.jsxs(Is,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(Jo,{children:[l.jsx(Ts,{className:"text-[15px]",children:_?"Export document":"Export dashboard"}),l.jsx(Ks,{className:"text-[13px] leading-5",children:_?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[W&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:CK,children:"Export scope"}),l.jsxs(Ja,{value:i.sheetSelection,onValueChange:Y=>a({...i,sheetSelection:Y}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!R&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(Us,{value:"current",id:"scope-current",disabled:!R}),_?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!q&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(Us,{value:"all",id:"scope-all",disabled:!q}),"Dashboard sheets (",j.length," ",j.length===1?"sheet":"sheets",")"]})]}),_&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Tn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:Y=>{a({...i,protectPdf:Y,password:Y?i.password:""}),Y||r(!1)}}),l.jsx(Bv,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:CK,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:Y=>a({...i,password:Y.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:Y=>{Y.key==="Enter"&&i.password&&K()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(kk,{className:"h-3.5 w-3.5"}):l.jsx(Ot.Eye,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Qa,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:Z,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:K,disabled:s||y||F,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(gu,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function fbe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=w.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(gu,{className:m.cn("size-4",e)})}),l.jsx(dbe,{open:i,onOpenChange:a})]})}function NK(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function UNt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=Xb({id:`control:${e.id}`,disabled:!n}),d={transform:Ki.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Xhe,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function jK(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function kK(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function qNt(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return kK(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=kK(t,n).filter(a=>!o.has(a));return[...s,...i]}function WNt(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function GNt(e){return Wh(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>Wh(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function AM(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function KNt(e){return hbe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function hbe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=WNt(e.dashboard,t);return Bk(rb({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!GNt({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function YNt(e,t){return"toolbar"}function ZNt(){const e=ku("interactive"),t=m.useDashboardStore(B=>B.selectedSheetId),n=m.useDashboardStore(B=>B.dashboard.filters),r=m.useDashboardStore(B=>B.dashboard.filterLayout),s=m.useDashboardStore(B=>B.isDashboardEditing),o=m.useDashboardStore(B=>B.controlValues),i=m.useDashboardStore(B=>B.filterValues);m.useDashboardStore(B=>B.filteringCards);const a=m.useDashboardStore(B=>B.inlineFilterValuesMap),c=m.useDashboardStore(B=>B.dashboardInputValues),u=m.useInteractionStore(B=>B.clearAllClickFilters),d=m.useInteractionStore(B=>Object.entries(B.interactionStates).reduce((H,[L,G])=>{var J;return L===m.DRILL_CONTEXT_CARD_ID?H:H+(((J=G.appliedClickFilters)==null?void 0:J.length)??0)},0)),f=m.useDashboardStore(B=>B.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:v,setFilteringCards:S,upsertDashboardInput:N}=m.useDashboardActions(),C=tT(Xg(Yb,{activationConstraint:{distance:5}})),j=m.useDashboardStore(B=>B.dashboard),_=KNt({dashboard:j,selectedSheetId:t}).filter(B=>YNt(B.filter)==="toolbar"),k=hbe({dashboard:j,selectedSheetId:t}),I=_.map(B=>B.filter),T=new Map(_.map(B=>[`filter:${B.filter.id}`,B])),E=kXe(j),D=E.filter(B=>!B.hidden&&nv(B)==="toolbar"),M=E.filter(B=>!B.hidden&&nv(B)==="advanced"),A=qNt(r==null?void 0:r.toolbarItemOrder,I,D),P=new Map(I.map(B=>[`filter:${B.id}`,B])),O=new Map(D.map(B=>[`control:${B.id}`,B]));function $(B){const{active:H,over:L}=B;if(!L||H.id===L.id)return;const G=String(H.id),J=String(L.id),oe=A.findIndex(ge=>ge===G),Q=A.findIndex(ge=>ge===J);if(oe===-1||Q===-1)return;const ae=Zb(A,oe,Q);y({toolbarItemOrder:ae});const ie=new Set((n||[]).map(ge=>ge.id)),le=A.filter(ge=>ge.startsWith("filter:")).map(ge=>ge.replace("filter:","")).filter(ge=>ie.has(ge)),ue=ae.filter(ge=>ge.startsWith("filter:")).map(ge=>ge.replace("filter:","")).filter(ge=>ie.has(ge)),fe=A.filter(ge=>ge.startsWith("control:")).map(ge=>ge.replace("control:","")),pe=ae.filter(ge=>ge.startsWith("control:")).map(ge=>ge.replace("control:",""));h(NK(n||[],le,ue)),g(NK(j.controls||[],fe,pe))}const V=(r==null?void 0:r.toolbarWrap)??!1,U=(r==null?void 0:r.showDownloadButton)??!1,R=k.filter(AM),q=k.filter(B=>{if(AM(B))return!1;const H=m.getDashboardInputRuntimeSlot(c,B,{sheetId:t});return(H==null?void 0:H.status)==="set"||(H==null?void 0:H.status)==="cleared"}),W=new Set([...R,...q].map(B=>B.filter.id)),F=(i==null?void 0:i.filter(B=>!W.has(B.filterId)&&jK(B)).length)??0,Z=[...R,...q],K=Z.filter(B=>{const H=m.hydrateAuthoredDashboardInputSlot({dashboard:j,input:B,runtimeValues:c,target:{sheetId:t}});return(H==null?void 0:H.status)==="set"&&H.value.kind==="filter"&&jK(H.value.filterValue)}).length,Y=a?Object.values(a).reduce((B,H)=>B+((H==null?void 0:H.length)??0),0):0,X=F+K+Y+d,z=()=>{v([]),Z.forEach(B=>{p(B,{sheetId:t})}),S([]),u(),a&&Object.entries(a).forEach(([B,H])=>{H==null||H.forEach(L=>{f(B,L.filterId)})})};return!I.length&&!D.length&&!M.length&&!U&&X===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(eS,{sensors:C,collisionDetection:Xw,onDragEnd:$,children:l.jsxs("div",{className:m.cn("flex items-center",V?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(tS,{items:A,strategy:T4,children:l.jsx(IF,{className:"gap-3 pr-0",wrap:V,children:A.map(B=>{const H=P.get(B);if(H){const G=T.get(B),J=G&&AM(G);return l.jsx(VNt,{filter:H,isEditing:s,storageOptions:J?{storageTarget:"dashboardInput",dashboardInput:G,sheetId:t??void 0}:void 0,inputVariableName:J?G.variableName:void 0,onUpdateFilter:J?(oe,Q)=>{N({...G,variableName:(Q==null?void 0:Q.variableName)||G.variableName,filter:oe})}:void 0,onRemoveFilter:J?()=>{v((i||[]).filter(oe=>oe.filterId!==H.id)),b(G.id)}:void 0},B)}const L=O.get(B);return L?l.jsx(UNt,{control:L,value:o==null?void 0:o[L.id],isEditing:s,onChange:G=>x(L.id,G)},B):null})})}),M.length>0&&l.jsx(Sce,{title:"",controls:M,values:o,onChange:(B,H)=>x(B.id,H),immediatePlacement:"toolbar",advancedLabel:"More controls"}),X>0&&l.jsxs("button",{type:"button",onClick:z,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(Ce.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:X})]}),U&&l.jsx("div",{className:m.cn(X>0?"ml-1.5":"ml-auto"),children:l.jsx(fbe,{})})]})})})}function mbe(){var de,ye;const{showAssistant:e,tokenProps:t,renderMode:n}=Tt(),r=BNt((de=t.config)==null?void 0:de.showDashboardAssistant,e),{preferences:s}=Vm(),o=(ye=s==null?void 0:s.cardDisplay)==null?void 0:ye.mode,i=nf(o),a=jX({displayMode:o,renderMode:n}),c=w.useRef(null),u=w.useRef(null),[d,f]=w.useState(!1),{handleDragStart:h,isDraggingRef:p,getStyle:g,getPositionClasses:b}=_bt({initialPosition:"bottom-right"}),x=Th(ce=>ce.setFullscreen),y=Th(ce=>ce.setPanelOpen),v=Th(ce=>ce.setContainer),S=ure("dashboard"),N=dre(),C=fre("dashboard"),j=S.isOpen,_=N==="dashboard",k=m.useDashboardStore(ce=>ce.isVisualEditing),I=m.useDashboardStore(ce=>ce.themeStyle),T=Fu(),E=m.useDashboardStore(ce=>{var re;return(re=ce.dashboard)==null?void 0:re.sheets}),D=m.useDashboardStore(ce=>ce.showFilters),M=m.useDashboardStore(ce=>ce.isDashboardEditing),A=m.useDashboardStore(ce=>ce.selectedSheetId),P=E==null?void 0:E.find(ce=>ce.id===A),O=m.useDashboardStore(ce=>{var re,ee,se;return(se=(ee=(re=ce.dashboard)==null?void 0:re.sheets)==null?void 0:ee.find(ne=>ne.id===ce.selectedSheetId))==null?void 0:se.kind}),$=m.useDashboardStore(ce=>{var re,ee;return((ee=(re=ce.dashboard)==null?void 0:re.summary)==null?void 0:ee.position)||"top"}),V=O==="document",U=m.useDashboardStore(ce=>{var re;return(re=ce.dashboard)==null?void 0:re.id}),{getDefaultSheetId:R,setDefaultSheetId:q,clearDefaultSheetId:W}=ube(U),[F,Z]=w.useState(null),{setSelectedSheetId:K,setSheetTitle:Y,addSheet:X,setSheets:z}=m.useDashboardActions();INt(u);const{setActiveAssistantType:B}=m.useAIActions();w.useEffect(()=>{if(U){const ce=R();Z(ce)}},[U,R]),w.useEffect(()=>{j?B("dashboard"):N==="dashboard"&&x(null)},[j,B,N,x]),w.useEffect(()=>{var ce;j||(ce=c.current)==null||ce.resize(0)},[j]);function H(ce){var re,ee;ce?((re=c.current)==null||re.resize(40),y("dashboard",!0),x("dashboard"),B("dashboard")):(y("dashboard",!1),x(null),(ee=c.current)==null||ee.resize(0),B(null))}function L(ce="dashboard"){const re={id:m.v4(),title:ce==="document"?"New Document":"New Sheet",...ce==="document"?{kind:ce,document:m.createDefaultDocumentDefinition()}:{}};X(re),K(re.id)}function G(ce,re){if(!U)return;F===ce?(W(),Z(null),it.success("Default sheet cleared")):(q(ce),Z(ce),it.success(`"${re}" set as default sheet`))}function J(ce){var re;ce<1?(y("dashboard",!1),x(null),B(null),(re=c.current)==null||re.resize(0)):(j||y("dashboard",!0),B("dashboard"))}function oe(){return(I==null?void 0:I.canvasTheme)==="muted"||!(I!=null&&I.canvasTheme)?"hsl(var(--semaphor-muted))":(I==null?void 0:I.canvasTheme)==="clear"?"":I==null?void 0:I.canvasTheme}const Q=(ce,re)=>{ce.dataTransfer.setData("tabIndex",re.toString())},ae=ce=>{ce.preventDefault()},ie=(ce,re)=>{const ee=ce.dataTransfer.getData("tabIndex");if(ee===re.toString())return;const se=Array.from(E||[]),[ne]=se.splice(parseInt(ee),1);se.splice(re,0,ne),z(se)},le=r===!0&&!i&&!j&&!k&&!D;function ue(){if(E&&E.length>1||M)return l.jsx("div",{className:"relative flex w-full items-stretch border-b border-border",children:l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[E==null?void 0:E.map((ce,re)=>{const ee=A===ce.id,se=F===ce.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:ne=>Q(ne,re),onDragOver:ae,onDrop:ne=>ie(ne,re),onClick:()=>K(ce.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:ce.id,children:[ce.kind==="document"&&l.jsx(Qo,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(Tj,{enabled:M&&ee,text:ce.title,onSave:ne=>Y(ce.id,ne),children:ce.title},ce.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":se?"Clear default sheet":"Set as default sheet",title:se?"Clear default sheet":"Set as default sheet",onClick:ne=>{ne.stopPropagation(),G(ce.id,ce.title||"Sheet")},onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),ne.stopPropagation(),G(ce.id,ce.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ee||se?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(DY,{className:m.cn("h-3 w-3 transition-colors",se?"fill-current text-amber-500":"text-muted-foreground")})}),M&&ee&&E.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:ne=>{ne.stopPropagation(),f(!0)},onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),ne.stopPropagation(),f(!0))},children:l.jsx(Ce.X,{className:"h-3 w-3"})})]},ce.id)}),M&&l.jsxs(Ys,{children:[l.jsx(Zs,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(Ar,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(Es,{align:"start",className:"w-48",children:[l.jsxs(Nn,{onSelect:()=>L("dashboard"),children:[l.jsx(Hh,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(Nn,{onSelect:()=>L("document"),children:[l.jsx(Qo,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})})}function fe(){return l.jsx("div",{ref:u,style:{},className:"h-full min-h-0 grow",children:E==null?void 0:E.map(ce=>l.jsx(m.TabsContent,{style:{backgroundColor:oe(),...T.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:ce.id,children:l.jsx(cG,{sheet:ce})},ce.id))})}function pe(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",I==null?void 0:I.dashboardTabsContainer),onValueChange:ce=>{K(ce)},value:A||void 0,children:[ue(),$==="top"&&!V&&l.jsx(UP,{}),A&&!V&&l.jsx(ZNt,{}),V?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:fe()}):l.jsx(il,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:fe()}),$==="bottom"&&!V&&l.jsx(UP,{}),l.jsx(Ibt,{open:d,setOpen:f})]})}const ge=w.useCallback(ce=>{v("dashboard",ce)},[v]);return E?a&&A&&!V?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):a&&V&&P?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(cG,{sheet:P})}):l.jsxs(l.Fragment,{children:[l.jsx(FNt,{}),l.jsx(zNt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(spe,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",_&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(AF,{children:pe()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(kbt,{open:j,onTabClick:H,withHandle:!0,disabled:!j}),l.jsx(AF,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:J,defaultSize:j?40:0,ref:c,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(_Nt,{open:j,setOpen:H,isFullscreen:_,onFullscreenChange:ce=>x(ce?"dashboard":null),fullscreenContainer:C})})})]})]}),l.jsx("div",{ref:ge,className:m.cn("absolute inset-0",!_&&"pointer-events-none")}),le&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",b().horizontal,b().vertical),style:g(),children:l.jsx(m.Button,{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:()=>{p.current||H(!0)},onMouseDown:h,onTouchStart:h,title:"Open Assistant (drag to move)",children:l.jsx(Pxe,{className:"h-5 w-5"})})})]})]}):null}function XNt(e=[]){const t=w.useRef(null),n=w.useRef(null),r=w.useRef(null),[s,o]=w.useState(),i=w.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return w.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function QNt({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Vm(),r=nf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=XNt([t,o,r]);return w.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(bi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(N$,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(Ce.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function JNt(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":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(QNt,{filter:r}),l.jsx(jI,{filter:r})]},r.id))}):null}function ejt(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(JNt,{}),l.jsx(mbe,{})]})})}function pbe({children:e,preferences:t}){const{currentUser:n}=ti(),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(ace.Provider,{value:r,children:l.jsx(FI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}const gbe=w.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=w.useId(),f=w.useMemo(()=>tjt(d),[d]),{theme:h}=pO(),p=njt(h),g=w.useMemo(()=>s??pu.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=w.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=w.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(Vb,{...c,ref:u,className:i,style:a,children:o})})});gbe.displayName="AppearanceProvider";function tjt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function njt(e){const t=cN(e),[n,r]=w.useState(()=>rjt());return w.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function rjt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const bbe=w.createContext({openBrandStudioPreview:()=>{}}),sjt=bbe.Provider;function ojt(){return w.useContext(bbe)}function ijt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=cN(t),[o,i]=w.useState(()=>ajt(n)||s),a=w.useCallback(u=>{const d=cN(u);ljt(n,d),i(d)},[n]),c=w.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(PY.Provider,{...r,value:c,children:e})}function ajt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=cN(t,"system");return n===t?n:null}catch{return null}}function ljt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const cjt=w.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function $z({appearance:e,children:t}){var E,D;const{authToken:n,id:r,tokenProps:s}=Tt(),o=fS(),i=(E=o.data)==null?void 0:E.organizationAppearance,a=(D=s.config)==null?void 0:D.appearance,[c,u]=w.useState(!1),[d,f]=w.useState(null),[h,p]=w.useState(null),[g,b]=w.useState(null),[x,y]=w.useState(null),v=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,S=Gn({queryKey:Hde({resourceType:cs.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:M=>(M==null?void 0:M.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});w.useEffect(()=>{i!==void 0&&y({scopeKey:v,appearance:i})},[i,v]),w.useEffect(()=>{S.data!==void 0&&y({scopeKey:v,appearance:S.data})},[S.data,v]);const N=(x==null?void 0:x.scopeKey)===v?x.appearance:null,C=i!==void 0?i:S.data!==void 0?S.data:N,j=w.useMemo(()=>pu.resolveAppearance({organizationAppearance:C,tokenAppearance:a,reactAppearance:e}),[e,C,a]),_=w.useCallback(()=>{f(g??h??j),u(!0)},[g,h,j]),k=w.useCallback(()=>{u(!1)},[]);w.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const I=w.useMemo(()=>({openBrandStudioPreview:_}),[_]),T=g??h??e;return l.jsx(ijt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(sjt,{value:I,children:l.jsx(gbe,{organizationAppearance:C,tokenAppearance:a,reactAppearance:T,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(w.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(cjt,{appearance:d,onDraftChange:b,onSave:M=>{p(M),b(M),f(M)},onCancel:k})})})]})})})})}function ujt(e=2e3,t=500){const n=c0e(),[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 zz({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=ujt(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":""})}const djt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CYBi_mes.js"))),fjt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DEb9MeSM.js"))),hjt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-ezLyW7AK.js")));function mjt({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(a=>a.isVisualEditing),s=m.useDashboardStore(a=>a.showDashboardJSON),{appearance:o,preferences:i}=n;return l.jsx(Za,{FallbackComponent:RI,children:l.jsx(Gz,{dashboardProps:n,children:l.jsxs(GI,{children:[l.jsx(zz,{componentType:"surfboard",componentId:n.id}),l.jsxs($z,{appearance:o,children:[l.jsx(L0e,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(pbe,{preferences:i,children:[s&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(hjt,{})}),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(djt,{})}),l.jsx("div",{className:"flex grow overflow-hidden",children:l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(Kz,{...n,type:"dashboard",children:[r&&l.jsx(w.Suspense,{fallback:null,children:l.jsx(fjt,{})}),l.jsx(ejt,{})]})})})]})]})]})]})})})}const _K=[{value:"en-US",label:"English (United States)"},{value:"en-GB",label:"English (United Kingdom)"},{value:"de-DE",label:"German (Germany)"},{value:"fr-FR",label:"French (France)"},{value:"es-ES",label:"Spanish (Spain)"},{value:"it-IT",label:"Italian (Italy)"},{value:"nl-NL",label:"Dutch (Netherlands)"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"ja-JP",label:"Japanese (Japan)"},{value:"en-IN",label:"English (India)"},{value:"en-NZ",label:"English (New Zealand)"},{value:"mi-NZ",label:"Māori (New Zealand)"}],xbe=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","INR","BRL","KWD"]),pjt=iu.getSupportedCurrencyCodes(),gjt=pjt.filter(e=>!xbe.has(e));function IK(e){switch(e){case"viewer_tenant":return"tenant";case"viewer_organization":return"organization";case"session_initial":return"embedded";case"system_default":return"system";default:return"inherited"}}function bjt({value:e,inherited:t,inheritedSources:n,onChange:r,disabled:s}){const o=w.useId(),a=(e.locale===void 0?void 0:iu.canonicalizeSupportedLocale(e.locale))??t.locale,c=e.defaultCurrency??t.defaultCurrency,u=new Intl.NumberFormat(a,{style:"currency",currency:c}).format(1e3);return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{htmlFor:o,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Locale"}),l.jsxs(m.Select,{value:e.locale??"inherit",disabled:s,onValueChange:d=>r({...e,locale:d==="inherit"?void 0:d}),children:[l.jsx(m.SelectTrigger,{id:o,size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:"inherit",children:["Use ",IK(n.locale)," default —"," ",t.locale]}),e.locale&&!_K.some(d=>d.value===e.locale)&&l.jsx(m.SelectItem,{value:e.locale,children:e.locale}),_K.map(d=>l.jsxs(m.SelectItem,{value:d.value,children:[d.label," — ",d.value]},d.value))]})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default currency"}),l.jsxs(m.Select,{value:e.defaultCurrency??"inherit",disabled:s,onValueChange:d=>r({...e,defaultCurrency:d==="inherit"?void 0:d}),children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:"inherit",children:["Use ",IK(n.defaultCurrency)," default —"," ",t.defaultCurrency]}),[...xbe].map(d=>l.jsx(m.SelectItem,{value:d,children:d},d)),gjt.map(d=>l.jsx(m.SelectItem,{value:d,children:d},d))]})]})]}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2",children:[l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsx("p",{className:"mt-1 text-[14px] font-medium text-foreground",children:u}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Currency display only; values are not converted."})]})]})}function xjt(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=cs.DASHBOARD,userType:s,tenantId:o}=e,i=w.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:c,isError:u}=$I(i),d=sat(r,n);return{allUsers:a,isLoadingUsers:c,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function yjt({open:e,onOpenChange:t,title:n,subtitle:r,topContent:s,children:o}){return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{showCloseButton:!1,className:"z-[51] flex max-h-[80vh] w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:rounded-[6px]",children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(EY,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx(Ts,{className:"truncate text-[13px] font-medium text-foreground",title:n,children:n}),l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r})]}),l.jsx("button",{type:"button","aria-label":"Close",onClick:()=>t(!1),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]}),l.jsx("div",{className:"relative z-20 shrink-0 border-b border-border/60",children:s}),l.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:o}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-background px-4 py-2.5",children:l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>t(!1),children:"Close"})})]})})}function OT(e){return e==="org_broadcast"||e==="all_tenants_broadcast"||e==="tenant_broadcast"}function vjt(e){const t=e.role==="VIEWER"?"view":"edit";switch(e.entity.type){case"org_broadcast":return`Anyone in your organization can ${t}`;case"all_tenants_broadcast":return`Anyone across all tenants can ${t}`;case"tenant_broadcast":return`Anyone in ${e.entity.tenantName??"this workspace"} can ${t}`;default:return""}}function wjt({shares:e,viewerType:t}){const n=e.filter(o=>OT(o.entity.type)),r=n.length===0,s=t==="tenant"?"Restricted — only invited people and groups in your workspace have access":"Restricted — only the people, tenants, and groups below have access";return l.jsxs("div",{className:"flex items-start gap-2 border-b border-border/60 bg-muted/40 px-4 py-2",children:[r?l.jsx(Bv,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):l.jsx(vm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("div",{className:"min-w-0 flex-1 text-[12px] text-foreground/80",children:r?l.jsx("span",{children:s}):n.map((o,i)=>l.jsxs("span",{children:[i>0?" · ":"",vjt(o)]},o.id))})]})}const sN={VIEWER:"Viewer",EDITOR:"Editor",CONTRIBUTOR:"Contributor"},Sjt={VIEWER:"Can view and use",EDITOR:"Can edit, share, and delete",CONTRIBUTOR:"Can edit but not share or delete"},Cjt={org_user:"ORG",tenant_user:"TENANT USER",tenant:"TENANT",org_group:"ORG GROUP",tenant_group:"TENANT GROUP"};function Bz({type:e,viewerType:t}){if(t!=="organization")return null;const n=Cjt[e];return n?l.jsx("span",{className:"rounded-[4px] bg-muted px-1 py-0.5 text-[9px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n}):null}function kv({entity:e}){return OT(e.type)?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground",children:l.jsx(vm,{className:"h-3 w-3"})}):e.type==="tenant"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border bg-background text-muted-foreground",children:l.jsx(rY,{className:"h-3 w-3"})}):e.type==="org_group"||e.type==="tenant_group"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border/60 bg-muted text-muted-foreground",children:l.jsx(_k,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground",children:e.initial||"?"})}function jk({value:e,onChange:t,disabled:n,includeRemove:r,onRemove:s,displayLabelOverride:o,loading:i}){const a=n||i,c=l.jsxs("button",{type:"button",disabled:a,className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[12px] text-foreground hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-transparent",children:[o??sN[e],i?l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):l.jsx(Ce.ChevronDown,{className:m.cn("h-3 w-3 text-muted-foreground",n&&"invisible")})]});return a?c:l.jsxs(m.Popover,{modal:!0,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:c}),l.jsxs(m.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-56 rounded-[6px] border border-border/60 bg-popover p-1 shadow-md",children:[Object.keys(sN).map(u=>l.jsx(Njt,{label:sN[u],description:Sjt[u],selected:e===u,onSelect:()=>t(u)},u)),r&&s?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"my-1 h-px bg-border/60"}),l.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] text-destructive hover:bg-destructive/10",children:[l.jsx(va,{className:"h-3.5 w-3.5"}),"Remove access"]})]}):null]})]})}function Njt({label:e,description:t,selected:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:r,className:"flex w-full items-start justify-between gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] hover:bg-muted",children:[l.jsxs("div",{children:[l.jsx("div",{className:"font-medium text-foreground",children:e}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:t})]}),n?l.jsx(m.Check,{className:"mt-0.5 h-3.5 w-3.5 text-foreground"}):null]})}const jjt=5;function kjt(e){const{directory:t,groupConfig:n,excludeIds:r,placeholder:s,invites:o,defaultRole:i,onAdd:a,onRemoveInvite:c,onChangeInviteRole:u,onChangeDefaultRole:d,onSubmit:f,isSubmitting:h,viewerType:p}=e,[g,b]=w.useState(""),[x,y]=w.useState(!1),[v,S]=w.useState("all"),[N,C]=w.useState(new Set),[j,_]=w.useState(null),k=w.useRef(null),I=w.useRef(null),T=w.useRef(null),E=g.trim(),D=E.length>0,M=w.useMemo(()=>{const X=E.toLowerCase(),z=t.filter(B=>!r.has(B.id));return X?z.filter(B=>B.name.toLowerCase().includes(X)||B.sublabel.toLowerCase().includes(X)||(B.tenantName??"").toLowerCase().includes(X)):z},[E,r,t]),A=w.useMemo(()=>{if(v==="all")return M;const X=n.find(z=>z.key===v);return X?M.filter(z=>X.types.includes(z.type)):M},[M,v,n]),P=w.useMemo(()=>t.filter(X=>OT(X.type)&&!r.has(X.id)),[t,r]),O=w.useMemo(()=>{const X={all:M.length};for(const z of n)X[z.key]=M.filter(B=>z.types.includes(B.type)).length;return X},[M,n]),$=w.useMemo(()=>t.filter(z=>z.type==="tenant").map(z=>({tenant:z,userCount:t.filter(B=>B.type==="tenant_user"&&B.tenantName===z.name).length})),[t]),V=w.useMemo(()=>j?t.find(X=>X.id===j&&X.type==="tenant")??null:null,[t,j]),U=w.useMemo(()=>{if(!V)return[];const X=E.toLowerCase();return t.filter(z=>z.type!=="tenant_user"||z.tenantName!==V.name||r.has(z.id)?!1:X?z.name.toLowerCase().includes(X)||z.sublabel.toLowerCase().includes(X):!0)},[t,V,E,r]);function R(X){b(X),X.trim()!==E&&C(new Set)}function q(X){S(X),X!==v&&C(new Set)}function W(X){var z;a(X),R(""),!(j&&X.type==="tenant_user")&&(q("all"),C(new Set),_(null),(z=k.current)==null||z.focus())}function F(X){_(X),R(""),q("all"),C(new Set)}function Z(){var X;_(null),R(""),(X=k.current)==null||X.focus()}function K(X){var z;if(X.key==="Backspace"&&g.length===0){if(j){Z(),X.preventDefault();return}o.length>0&&c(o[o.length-1].entity.id)}else X.key==="Escape"&&((z=k.current)==null||z.blur())}function Y(X){C(z=>{const B=new Set(z);return B.has(X)?B.delete(X):B.add(X),B})}return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Popover,{open:x,onOpenChange:y,modal:!1,children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(m.Anchor2,{asChild:!0,children:l.jsx("div",{ref:I,className:"flex-1",children:l.jsx(_jt,{ref:k,placeholder:V?`Filter ${V.name} users…`:s,query:g,onQueryChange:X=>{R(X),y(!0)},onFocus:()=>y(!0),onKeyDown:K})})}),l.jsx(Ijt,{value:i,onChange:d}),l.jsx(m.Button,{type:"button",size:"xs",onClick:f,disabled:o.length===0||h,children:h?"Sharing…":"Share"})]}),l.jsx(m.Portal$2,{children:l.jsx(m.PortalScope,{children:l.jsxs(m.Content2,{ref:T,align:"start",sideOffset:4,onOpenAutoFocus:X=>X.preventDefault(),onCloseAutoFocus:X=>X.preventDefault(),onPointerDownOutside:X=>{var B;const z=X.target;z instanceof Node&&((B=I.current)!=null&&B.contains(z))&&X.preventDefault()},onInteractOutside:X=>{var B;const z=X.target;z instanceof Node&&((B=I.current)!=null&&B.contains(z))&&X.preventDefault()},onWheel:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),className:m.cn("pointer-events-auto z-[60] flex flex-col w-[var(--radix-popover-trigger-width)] min-w-[360px]","max-h-[min(360px,var(--radix-popover-content-available-height))]","overflow-hidden rounded-[6px] border border-border/60 bg-popover text-popover-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"),children:[V?l.jsx(Tjt,{tenant:V,userCount:U.length,onBack:Z}):n.length>1?l.jsx(Ejt,{groupConfig:n,groupCounts:O,activeFilter:v,onChangeFilter:q}):null,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-1",onWheel:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),children:l.jsx(Mjt,{drilledInTenant:V,drilledInTenantUsers:U,hasQuery:D,query:E,activeFilter:v,groupConfig:n,filteredMatches:A,broadcastItems:P,tenantsWithUserCounts:$,expandedGroups:N,directory:t,viewerType:p,onPick:W,onDrillInto:F,onToggleExpand:Y})})]})})})]}),o.length>0&&l.jsx(Rjt,{invites:o,viewerType:p,onChangeRole:u,onRemove:c})]})}const _jt=({ref:e,placeholder:t,query:n,onQueryChange:r,onFocus:s,onKeyDown:o})=>l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-input bg-background px-2 focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/10",onClick:()=>{var i;return(i=e.current)==null?void 0:i.focus()},children:[l.jsx(Ot.Search,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("input",{ref:e,type:"text",value:n,onChange:i=>r(i.target.value),onFocus:s,onKeyDown:o,placeholder:t,className:"h-full flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground"})]});function Ijt({value:e,onChange:t}){return l.jsx("div",{className:"flex h-7 shrink-0 items-center rounded-[5px] border border-input bg-background px-1",children:l.jsx(jk,{value:e,onChange:t})})}function Tjt({tenant:e,userCount:t,onBack:n}){return l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b border-border/60 px-2 py-1.5",children:[l.jsxs("button",{type:"button",onClick:n,"aria-label":"Back",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(xm,{className:"h-3 w-3"}),"Back"]}),l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx(rY,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e.name}),l.jsxs("span",{className:"text-[11px] text-muted-foreground/70",children:["· ",t," ",t===1?"user":"users"]})]})}function Ejt({groupConfig:e,groupCounts:t,activeFilter:n,onChangeFilter:r}){return l.jsx("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border/60 bg-popover px-2 py-1.5",children:e.map(s=>{const o=t[s.key]??0;if(o===0)return null;const i=n===s.key;return l.jsx(Djt,{label:s.pillLabel,count:o,active:i,onClick:()=>r(i?"all":s.key)},s.key)})})}function Djt({label:e,count:t,active:n,onClick:r}){return l.jsxs("button",{type:"button",onClick:r,className:m.cn("inline-flex h-6 shrink-0 items-center gap-1 rounded-[4px] px-2 text-[11px] transition-colors",n?"bg-foreground text-background":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e,typeof t=="number"?l.jsx("span",{className:m.cn("tabular-nums",n?"text-background/70":"text-muted-foreground/70"),children:t}):null]})}function Mjt(e){const{drilledInTenant:t,drilledInTenantUsers:n,hasQuery:r,query:s,activeFilter:o,groupConfig:i,filteredMatches:a,broadcastItems:c,tenantsWithUserCounts:u,expandedGroups:d,directory:f,viewerType:h,onPick:p,onDrillInto:g,onToggleExpand:b}=e;return t?l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",onClick:()=>p(t),className:"mb-2 flex w-full items-center gap-2 rounded-[5px] border border-dashed border-border/60 px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"truncate text-[13px] text-foreground",children:["Share ",l.jsx("strong",{className:"font-medium",children:t.name})," ","as a whole tenant instead"]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:"Grants every user in the workspace, present and future"})]}),l.jsx(Ot.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),n.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${s}" inside ${t.name}.`:`No users in ${t.name} to browse.`}):l.jsx(RM,{label:`Users in ${t.name}`,items:n,viewerType:h,onPick:p})]}):!r&&o==="tenant_users"&&u.length>0?l.jsxs("div",{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Browse by tenant"}),u.map(({tenant:x,userCount:y})=>l.jsxs("button",{type:"button",onClick:()=>g(x.id),className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:x}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] text-foreground",children:x.name}),l.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[y," ",y===1?"user":"users"]})]}),l.jsx(Ot.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},x.id)),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Click a tenant to filter to its users, or start typing to search across all tenants."})]}):!r&&o==="all"?l.jsxs(l.Fragment,{children:[c.length>0&&l.jsx(RM,{label:"General access",items:c,viewerType:h,onPick:p}),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Type to search, or pick a category above to browse."})]}):a.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${s}".`:"Nothing to browse in this category."}):l.jsx(l.Fragment,{children:i.map(x=>{if(o!=="all"&&o!==x.key)return null;const y=a.filter(C=>x.types.includes(C.type));if(y.length===0)return null;const v=d.has(x.key),S=o===x.key||v?y:y.slice(0,jjt),N=y.length-S.length;return x.key==="tenant_users"?l.jsx(Ajt,{label:x.label,items:y,visible:S,hiddenCount:N,directory:f,viewerType:h,onPick:p,onDrillInto:g,onToggleExpand:()=>b(x.key)},x.key):l.jsx(RM,{label:x.label,count:y.length,items:S,viewerType:h,onPick:p,showMoreCount:N,onShowMore:()=>b(x.key)},x.key)})})}function Ajt({label:e,items:t,visible:n,hiddenCount:r,directory:s,viewerType:o,onPick:i,onDrillInto:a,onToggleExpand:c}){const u=w.useMemo(()=>{const d=new Map;for(const f of n){const h=f.tenantName??"—";d.has(h)||d.set(h,[]),d.get(h).push(f)}return d},[n]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t.length>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t.length]}):null]}),Array.from(u.entries()).map(([d,f])=>{const h=s.find(p=>p.type==="tenant"&&p.name===d);return l.jsxs("div",{className:"mb-1",children:[l.jsxs("div",{className:"flex items-center justify-between px-2 py-0.5",children:[l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:d}),h?l.jsx("button",{type:"button",onClick:()=>a(h.id),className:"text-[10px] text-muted-foreground hover:text-foreground",children:"Browse all →"}):null]}),f.map(p=>l.jsx(ybe,{entity:p,viewerType:o,onPick:()=>i(p)},p.id))]},d)}),r>0?l.jsxs("button",{type:"button",onClick:c,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3"}),"Show ",r," more"]}):null]})}function RM({label:e,count:t,items:n,viewerType:r,onPick:s,showMoreCount:o,onShowMore:i}){return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),typeof t=="number"&&t>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t]}):null]}),n.map(a=>l.jsx(ybe,{entity:a,viewerType:r,onPick:()=>s(a)},a.id)),o&&o>0&&i?l.jsxs("button",{type:"button",onClick:i,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ot.ChevronRight,{className:"h-3 w-3"}),"Show ",o," more"]}):null]})}function ybe({entity:e,viewerType:t,onPick:n}){return l.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(kv,{entity:e}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.name}),l.jsx(Bz,{type:e.type,viewerType:t}),t==="organization"&&e.tenantName?l.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground/70",children:["· ",e.tenantName]}):null]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:e.sublabel})]})]})}function Rjt({invites:e,viewerType:t,onChangeRole:n,onRemove:r}){return l.jsx("div",{className:"space-y-0.5 rounded-[5px] bg-muted/40 px-1 py-1",children:e.map(s=>l.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[l.jsx(kv,{entity:s.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:s.entity.name}),l.jsx(Bz,{type:s.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&s.entity.tenantName?`${s.entity.sublabel} · ${s.entity.tenantName}`:s.entity.sublabel||(OT(s.entity.type)?`Will be granted as ${sN[s.role]}`:"")})]}),l.jsx(jk,{value:s.role,onChange:o=>n(s.entity.id,o)}),l.jsx("button",{type:"button",onClick:()=>r(s.entity.id),"aria-label":"Remove",className:"flex h-6 w-6 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Ce.X,{className:"h-3.5 w-3.5"})})]},s.entity.id))})}function Pjt({shares:e,sections:t,onChangeRole:n,onRemove:r,viewerType:s,pendingShareIds:o}){return l.jsx("div",{className:"space-y-3",children:t.map(i=>{const a=e.filter(c=>i.matches(c.entity));return a.length===0&&!i.emptyLabel?null:l.jsxs("section",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5 px-2 py-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:i.label}),l.jsxs("span",{className:"text-muted-foreground/70",children:["· ",a.length]})]}),a.length===0?l.jsx("p",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:i.emptyLabel}):a.map(c=>l.jsx(Fjt,{share:c,viewerType:s,loading:o.has(c.id),onChangeRole:u=>n(c,u),onRemove:()=>r(c)},c.id))]},i.label)})})}function Fjt({share:e,viewerType:t,loading:n,onChangeRole:r,onRemove:s}){return l.jsxs("div",{className:"group flex items-center gap-2 rounded-[5px] px-2 py-1.5 hover:bg-muted/40",children:[l.jsx(kv,{entity:e.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.entity.name}),e.isSelf?l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(you)"}):l.jsx(Bz,{type:e.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&e.entity.tenantName?`${e.entity.sublabel} · ${e.entity.tenantName}`:e.entity.sublabel})]}),e.isSelf?l.jsx(jk,{value:e.role,onChange:()=>{},disabled:!0,displayLabelOverride:"Owner"}):l.jsx(jk,{value:e.role,onChange:r,includeRemove:!0,onRemove:s,loading:n})]})}function Gm(e){if(!e)return"?";const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}function vbe(e){const t=e.type==="organization",n=e.name||e.email||"Unknown user";return{id:e.id,type:t?"org_user":"tenant_user",name:n,sublabel:e.email||"",initial:Gm(n),tenantId:e.tenantId,tenantName:e.tenantName}}function wbe(e){return{id:e.id,type:e.type==="ORG_GROUP"?"org_group":"tenant_group",name:e.name,sublabel:e.memberCount!==void 0?`${e.memberCount} member${e.memberCount===1?"":"s"}`:e.description||"",initial:Gm(e.name),tenantId:e.tenantId??void 0,tenantName:e.tenantName??void 0}}function Ojt(e){return{id:e.id,type:"tenant",name:e.name,sublabel:"Tenant workspace",initial:Gm(e.name),tenantId:e.id,tenantName:e.name}}const Sbe={id:"__broadcast:org",type:"org_broadcast",name:"Everyone in the organization",sublabel:"Any user in your organization can open this dashboard",initial:""},Cbe={id:"__broadcast:all-tenants",type:"all_tenants_broadcast",name:"Everyone across all tenants",sublabel:"Every tenant user in every tenant can open this dashboard",initial:""};function Nbe(e){return{id:"__broadcast:tenant",type:"tenant_broadcast",name:e.tenantName?`Everyone in ${e.tenantName}`:"Everyone in your workspace",sublabel:"Anyone who can sign in to your workspace can open this dashboard",tenantId:e.tenantId,tenantName:e.tenantName,initial:""}}function Ljt(e){return[Sbe,Cbe,...e.users.map(vbe),...e.tenants.map(Ojt),...e.groups.map(wbe)]}function $jt(e){var n,r;return[Nbe({tenantId:(n=e.currentUser)==null?void 0:n.tenantId,tenantName:(r=e.currentUser)==null?void 0:r.tenantName}),...e.users.filter(s=>s.type==="tenant").map(vbe),...e.groups.filter(s=>s.type==="TENANT_GROUP").map(wbe)]}function zjt({existingShares:e,userDirectory:t,groupDirectory:n,tenantDirectory:r,currentUser:s}){if(!(e!=null&&e.shares))return[];const o=new Map(t.map(f=>[f.id,f])),i=new Map(n.map(f=>[f.id,f])),a=new Map(r.map(f=>[f.id,f])),c=[];(e.shares.specificOrgUsers??[]).forEach(f=>c.push(Bjt(f,o,s))),(e.shares.specificTenantUsers??[]).forEach(f=>c.push(Vjt(f,o,s))),(e.shares.tenantWide??[]).forEach(f=>c.push(Hjt(f,a)));const u=[...e.shares.specificGroups??[],...e.shares.groups??[]],d=new Set;if(u.forEach(f=>{d.has(f.id)||(d.add(f.id),c.push(Ujt(f,i)))}),(s==null?void 0:s.type)==="organization"&&((e.shares.orgUsersOnly??[]).forEach(f=>c.push(qjt(f))),(e.shares.allTenantsOnly??[]).forEach(f=>c.push(Wjt(f)))),(s==null?void 0:s.type)==="tenant"&&s.tenantId){const f=(e.shares.tenantWide??[]).find(h=>h.tenantId===s.tenantId);if(f){const h=c.findIndex(p=>p.id===f.id&&p.entity.type==="tenant");h>=0&&c.splice(h,1),c.push(Gjt(f,s.tenantName))}}return(e.shares.allOrgGroups??[]).forEach(f=>c.push(Kjt(f))),(e.shares.allTenantGroups??[]).forEach(f=>c.push(Yjt(f))),c}function Bjt(e,t,n){var i,a,c;const r=t.get(e.orgUserId),s=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Org user",o=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.orgUserId,entity:{id:e.orgUserId,type:"org_user",name:s,sublabel:o,initial:Gm(s)}}}function Vjt(e,t,n){var i,a,c,u,d;const r=t.get(e.tenantUserId),s=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Tenant user",o=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.tenantUserId,entity:{id:e.tenantUserId,type:"tenant_user",name:s,sublabel:o,initial:Gm(s),tenantId:e.tenantId??((u=e.tenant)==null?void 0:u.id),tenantName:(d=e.tenant)==null?void 0:d.name}}}function Hjt(e,t){var s;const n=e.tenantId?t.get(e.tenantId):void 0,r=((s=e.tenant)==null?void 0:s.name)||(n==null?void 0:n.name)||"Tenant";return{id:e.id,role:e.role,entity:{id:e.tenantId??e.id,type:"tenant",name:r,sublabel:"All users in this tenant",initial:Gm(r),tenantId:e.tenantId,tenantName:r}}}function Ujt(e,t){var a,c,u;const n=t.get(e.groupId),r=((a=e.group)==null?void 0:a.name)||(n==null?void 0:n.name)||"Group",o=(((c=e.group)==null?void 0:c.type)||(n==null?void 0:n.type))==="ORG_GROUP",i=((u=e.group)==null?void 0:u.memberCount)??(n==null?void 0:n.memberCount);return{id:e.id,role:e.role,entity:{id:e.groupId,type:o?"org_group":"tenant_group",name:r,sublabel:i!==void 0?`${i} member${i===1?"":"s"}`:"",initial:Gm(r),tenantId:(n==null?void 0:n.tenantId)??void 0}}}function qjt(e){return{id:e.id,role:e.role,entity:{...Sbe}}}function Wjt(e){return{id:e.id,role:e.role,entity:{...Cbe}}}function Gjt(e,t){var r;const n=Nbe({tenantId:e.tenantId,tenantName:t??((r=e.tenant)==null?void 0:r.name)});return{id:e.id,role:e.role,entity:n}}function Kjt(e){return{id:e.id,role:e.role,entity:{id:`__all_org_groups:${e.id}`,type:"org_group",name:"All organization groups",sublabel:"Every org group",initial:"G"}}}function Yjt(e){return{id:e.id,role:e.role,entity:{id:`__all_tenant_groups:${e.id}`,type:"tenant_group",name:"All tenant groups",sublabel:"Every tenant group",initial:"G"}}}function Zjt(e,t){switch(e.type){case"org_user":return{scope:"specific_org_user",orgUserId:e.id,role:t};case"tenant_user":return{scope:"specific_tenant_user",tenantUserId:e.id,tenantId:e.tenantId,role:t};case"tenant":return{scope:"all_tenant_users",tenantId:e.id,role:t};case"org_group":case"tenant_group":return{scope:"group",groupId:e.id,role:t};case"org_broadcast":return{scope:"org_users_only",role:t};case"all_tenants_broadcast":return{scope:"all_tenants_only",role:t};case"tenant_broadcast":return{scope:"all_tenant_users",tenantId:e.tenantId,role:t}}}function Xjt(e){return e.invites.length===0?null:{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:e.invites.map(t=>Zjt(t.entity,t.role))}}}function Qjt(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[jbe(e.share,e.newRole,e.existingShares)]}}}function Jjt(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[jbe(e.share,e.share.role,e.existingShares)]}}}function jbe(e,t,n){if(e.entity.type==="org_broadcast")return{scope:"org_users_only",role:t};if(e.entity.type==="all_tenants_broadcast")return{scope:"all_tenants_only",role:t};if(e.entity.type==="tenant_broadcast")return{scope:"all_tenant_users",tenantId:e.entity.tenantId,role:t};if(e.entity.id.startsWith("__all_org_groups:"))return{scope:"all_org_groups",role:t};if(e.entity.id.startsWith("__all_tenant_groups:"))return{scope:"all_tenant_groups",role:t};switch(e.entity.type){case"org_user":{const r=((n==null?void 0:n.shares.specificOrgUsers)??[]).find(s=>s.orgUserId===e.entity.id);return{scope:"specific_org_user",orgUserId:(r==null?void 0:r.orgUserId)??e.entity.id,role:t}}case"tenant_user":{const r=((n==null?void 0:n.shares.specificTenantUsers)??[]).find(s=>s.tenantUserId===e.entity.id);return{scope:"specific_tenant_user",tenantUserId:(r==null?void 0:r.tenantUserId)??e.entity.id,tenantId:(r==null?void 0:r.tenantId)??e.entity.tenantId,role:t}}case"tenant":{const r=((n==null?void 0:n.shares.tenantWide)??[]).find(s=>s.tenantId===e.entity.id);return{scope:"all_tenant_users",tenantId:(r==null?void 0:r.tenantId)??e.entity.id,role:t}}case"org_group":case"tenant_group":{const s=[...(n==null?void 0:n.shares.specificGroups)??[],...(n==null?void 0:n.shares.groups)??[]].find(o=>o.groupId===e.entity.id);return{scope:"group",groupId:(s==null?void 0:s.groupId)??e.entity.id,role:t}}}}function TK(e){const{open:t,resource:n,resourceType:r,currentUser:s,config:o,onClose:i}=e,[a,c]=w.useState([]),[u,d]=w.useState("VIEWER"),[f,h]=w.useState(()=>new Set),[p,g]=w.useState(!1);function b(V){h(U=>{const R=new Set(U);return R.add(V),R})}function x(V){h(U=>{const R=new Set(U);return R.delete(V),R})}const y=$I({type:o.unifiedUsersType,limit:50}),v=Z$({type:o.groupsType,limit:50}),S=eat({enabled:o.fetchTenants}),N=w.useMemo(()=>{if(!o.fetchTenants)return[];const V=S.data;return(V==null?void 0:V.tenants)??[]},[o.fetchTenants,S.data]),{existingShares:C}=xjt({debouncedSearchQuery:"",resourceId:(n==null?void 0:n.id)||"",resourceType:r,userType:(s==null?void 0:s.type)??"tenant"}),j=qde(),_=Wde(),k=w.useMemo(()=>o.buildDirectory({users:y.users,groups:v.groups,tenants:N,currentUser:s}),[o,y.users,v.groups,N,s]),I=w.useMemo(()=>zjt({existingShares:C,userDirectory:y.users,groupDirectory:v.groups,tenantDirectory:N,currentUser:s}),[C,y.users,v.groups,N,s]),T=w.useMemo(()=>new Set([...a.map(V=>V.entity.id),...I.map(V=>V.entity.id)]),[a,I]);function E(V){c(U=>[...U,{entity:V,role:u}])}function D(V){c(U=>U.filter(R=>R.entity.id!==V))}function M(V,U){c(R=>R.map(q=>q.entity.id===V?{...q,role:U}:q))}function A(){const V=Xjt({resourceType:r,resourceId:n.id,invites:a});V&&(g(!0),j.mutate(V,{onSuccess:()=>c([]),onSettled:()=>g(!1)}))}function P(V,U){const R=Qjt({resourceType:r,resourceId:n.id,share:V,newRole:U,existingShares:C});b(V.id),j.mutate(R,{onSettled:()=>x(V.id)})}function O(V){const U=Jjt({resourceType:r,resourceId:n.id,share:V,existingShares:C});b(V.id),_.mutate(U,{onSettled:()=>x(V.id)})}const $=r==="visual"?"VISUAL":"DASHBOARD";return l.jsx(yjt,{open:t,onOpenChange:V=>{V||i()},title:`Share "${(n==null?void 0:n.title)??"resource"}"`,subtitle:$,topContent:l.jsxs(l.Fragment,{children:[l.jsx(wjt,{shares:I,viewerType:s==null?void 0:s.type}),l.jsx("div",{className:"px-4 py-3",children:l.jsx(kjt,{directory:k,groupConfig:o.groupConfig,excludeIds:T,placeholder:o.invitePlaceholder,invites:a,defaultRole:u,onChangeDefaultRole:d,onAdd:E,onRemoveInvite:D,onChangeInviteRole:M,onSubmit:A,isSubmitting:p,viewerType:s==null?void 0:s.type})})]}),children:l.jsx(Pjt,{shares:I,sections:o.sections,onChangeRole:P,onRemove:O,viewerType:s==null?void 0:s.type,pendingShareIds:f})})}const ekt={buildDirectory:({users:e,groups:t,tenants:n})=>Ljt({users:e,groups:t,tenants:n??[]}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["org_broadcast","all_tenants_broadcast"]},{key:"org_users",pillLabel:"People",label:"Org users",types:["org_user"]},{key:"tenants",pillLabel:"Tenants",label:"Tenants (whole workspace)",types:["tenant"]},{key:"tenant_users",pillLabel:"Tenant users",label:"Tenant users",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["org_group","tenant_group"]}],sections:[{label:"General access",matches:e=>e.type==="org_broadcast"||e.type==="all_tenants_broadcast"},{label:"People with access",matches:e=>e.type==="org_user"||e.type==="tenant_user",emptyLabel:"No individual people have been added."},{label:"Tenants with access",matches:e=>e.type==="tenant"},{label:"Groups with access",matches:e=>e.type==="org_group"||e.type==="tenant_group"}],fetchTenants:!0,invitePlaceholder:"Add people, tenants, groups, or broadcast access…",unifiedUsersType:"all",groupsType:"all"};function tkt(e){return{buildDirectory:({users:t,groups:n,currentUser:r})=>$jt({users:t,groups:n,currentUser:r}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["tenant_broadcast"]},{key:"people",pillLabel:"People",label:"People in your workspace",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["tenant_group"]}],sections:[{label:"General access",matches:t=>t.type==="tenant_broadcast"},{label:"People with access",matches:t=>t.type==="tenant_user",emptyLabel:"No teammates have been added yet."},{label:"Groups with access",matches:t=>t.type==="tenant_group"}],fetchTenants:!1,invitePlaceholder:"Add teammates, groups, or broadcast access…",unifiedUsersType:"tenant",groupsType:"TENANT_GROUP"}}function kbe({resource:e,resourceType:t,onClose:n}){const{currentUser:r}=ti();return(r==null?void 0:r.type)==="organization"?l.jsx(TK,{open:!0,resource:e,resourceType:t,currentUser:r,config:ekt,onClose:n}):l.jsx(TK,{open:!0,resource:e,resourceType:t,currentUser:r,config:tkt(),onClose:n})}function _be({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,c]=w.useState(n),[u,d]=w.useState(r??"");w.useEffect(()=>{e&&(c(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const p=a.trim();p&&o({title:p,description:u.trim()})};return l.jsx(Gs,{open:e,onOpenChange:h=>h?null:s(),children:l.jsx(Is,{className:"sm:max-w-md",children:l.jsxs("form",{onSubmit:f,className:"space-y-4",children:[l.jsxs(Jo,{children:[l.jsxs(Ts,{children:["Edit ",t]}),l.jsxs(Ks,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"resource-title",children:"Title"}),l.jsx(m.Input,{id:"resource-title",value:a,onChange:h=>c(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"resource-description",children:"Description"}),l.jsx(Hm,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),l.jsxs(Qa,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[l.jsx(m.Button,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),l.jsx(m.Button,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}const KF=new Set;function Ibe(e){return KF.add(e),()=>{KF.delete(e)}}function Vz(){KF.forEach(e=>{e()})}const nkt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},rkt={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}},skt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function okt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function ikt(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const EK=Symbol.for("r2wc.bound"),akt={parse:(e,t,n)=>{const r=ikt(t),s=n;if(typeof s<"u"&&r in s&&typeof s[r]<"u"){let o=s[r];return EK in s[r]||(o=o.bind(s),Object.defineProperty(o,EK,{value:!0})),o}else return}},lkt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},ckt={stringify:e=>e,parse:e=>e},PM={string:ckt,number:lkt,boolean:nkt,function:rkt,method:akt,json:skt},l1=Symbol.for("r2wc.render"),c1=Symbol.for("r2wc.connected"),Pf=Symbol.for("r2wc.context"),bl=Symbol.for("r2wc.props");function ukt(e,t,n){var d,f,h;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const r=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),s=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),o={},i={},a={},c={};for(const p of r){o[p]=Array.isArray(t.props)?"string":t.props[p];const g=okt(p);a[p]=g,c[g]=p}for(const p of s)i[p]=Array.isArray(t.events)?{}:t.events[p];class u extends HTMLElement{constructor(){super();ve(this,h,!0);ve(this,f);ve(this,d,{});ve(this,"container");t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[bl].container=this.container;for(const b of r){const x=a[b],y=this.getAttribute(x),v=o[b],S=v?PM[v]:null;S!=null&&S.parse&&(y||v==="method")&&(this[bl][b]=S.parse(y,x,this))}for(const b of s)this[bl][b]=x=>{const y=b.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(y,{detail:x,...i[b]}))}}static get observedAttributes(){return Object.keys(c)}connectedCallback(){this[c1]=!0,this[l1]()}disconnectedCallback(){this[c1]=!1,this[Pf]&&n.unmount(this[Pf]),delete this[Pf]}attributeChangedCallback(b,x,y){const v=c[b],S=o[v],N=S?PM[S]:null;v in o&&(N!=null&&N.parse)&&(y||S==="method")&&(this[bl][v]=N.parse(y,b,this),this[l1]())}[(h=c1,f=Pf,d=bl,l1)](){this[c1]&&(this[Pf]?n.update(this[Pf],this[bl]):this[Pf]=n.mount(this.container,e,this[bl]))}}for(const p of r){const g=a[p],b=o[p];Object.defineProperty(u.prototype,p,{enumerable:!0,configurable:!0,get(){return this[bl][p]},set(x){this[bl][p]=x;const y=b?PM[b]:null;if(y!=null&&y.stringify){const v=y.stringify(x,g,this);this.getAttribute(g)!==v&&(v==null?this.removeAttribute(g):this.setAttribute(g,v))}else p in o&&(y!=null&&y.parse)&&(x||b==="method")&&(this[bl][p]=y.parse(x,g,this)),this[l1]()}})}return u}function dkt(e,t,n){const r=hxe.createRoot(e),s=w.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function fkt({root:e,ReactComponent:t},n){const r=w.createElement(t,n);e.render(r)}function hkt({root:e}){e.unmount()}function mkt(e,t={}){return ukt(e,t,{mount:dkt,update:fkt,unmount:hkt})}const pkt={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},gkt=mkt(cxe,{props:pkt}),bkt=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(J4,{context:t})," "]})});var Tbe="Toggle",Ebe=te.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:s,...o}=e,[i,a]=m.useControllableState({prop:n,onChange:s,defaultProp:r??!1,caller:Tbe});return l.jsx(m.Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...o,ref:t,onClick:m.composeEventHandlers(e.onClick,()=>{e.disabled||a(!i)})})});Ebe.displayName=Tbe;var Dbe=Ebe;const xkt=m.cva("inline-flex items-center justify-center rounded-control text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Mbe=te.forwardRef(({className:e,variant:t,size:n,...r},s)=>l.jsx(Dbe,{ref:s,className:m.cn(xkt({variant:t,size:n,className:e})),...r}));Mbe.displayName=Dbe.displayName;function Hz(){var c,u;const e=m.useEditorStore(d=>d.card),t=m.useEditorStore(d=>d.frame),n=w.useMemo(()=>EI(t,e),[t,e]),{manifest:r}=mf(((c=n==null?void 0:n.customCardPreferences)==null?void 0:c.url)||""),s=w.useMemo(()=>{var d;return(d=r==null?void 0:r.visuals)==null?void 0:d.find(f=>{var h;return f.name===((h=n==null?void 0:n.customCardPreferences)==null?void 0:h.componentName)})},[r,(u=n==null?void 0:n.customCardPreferences)==null?void 0:u.componentName]),o=zb(n,s),i=w.useMemo(()=>TI({frame:t,configCard:n,isMultiInputVisual:o==="multiple"}),[t,n,o]),a=w.useMemo(()=>{const d=i.findIndex(f=>(f==null?void 0:f.id)===e.id);return d<0?-1:Yg(e,d)},[i,e]);return w.useMemo(()=>!n||o!=="multiple"||a<0?e.type:Lh(e,a,s==null?void 0:s.slots)??e.type,[n,o,a,e,s==null?void 0:s.slots])}function Abe({storeValue:e,defaultValue:t="",onStoreUpdate:n,delay:r=300}){const[s,o]=w.useState(e??t),i=w.useRef(null),a=w.useRef(s),c=w.useRef(e),u=w.useRef(!1),d=w.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null),u.current&&a.current!==(c.current??t)&&(n(a.current),c.current=a.current)},[t,n]);w.useEffect(()=>{if(e!==c.current){i.current&&(clearTimeout(i.current),i.current=null);const h=e??t;o(h),a.current=h,c.current=e,u.current=!1}},[e,t]),w.useEffect(()=>{if(u.current)return i.current=setTimeout(()=>{d()},r),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[r,d,s]),w.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=w.useCallback(h=>{const p=h??t;u.current=!0,a.current=p,o(p)},[t]);return{value:s,onChange:f,flush:d}}const ykt=300;function vkt({onExpand:e},t){const n=m.useEditorStore(S=>S.card.sql),r=m.useEditorStore(S=>S.sqlGen),s=m.useEditorStore(S=>S.card),o=Hz(),{setCardSql:i,setSqlGen:a,setRunSql:c}=m.useEditorActions(),u=w.useMemo(()=>o!==s.type?{...s,type:o}:s,[s,o]),{queryKey:d}=ob(u),f=Kr(),h=w.useRef(d);h.current=d;const p=w.useRef(r);p.current=r;const g=w.useCallback(S=>{i(S)},[i]),{value:b,onChange:x,flush:y}=Abe({storeValue:n,defaultValue:"",onStoreUpdate:g,delay:ykt});w.useEffect(()=>Ibe(y),[y]);function v(S){x(S),m.isObjectEmpty(p.current)||a({})}return l.jsxs("div",{className:"relative h-full w-full",children:[l.jsx(m.CodeEditor,{ref:t,value:b??"",onValueChange:v,language:"sql-jinja",embedded:!0,hideLineNumbers:!0,wrapLines:!0,placeholder:"Write your SQL here",onKeyDown:S=>{S.key==="Enter"&&S.shiftKey&&(S.preventDefault(),Vz(),setTimeout(()=>{f.removeQueries({queryKey:h.current,exact:!0}),c(!0)},0))}}),e?l.jsx(m.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2.5 top-2 z-20 h-7 w-7 bg-background/80 p-0 opacity-60 backdrop-blur-sm transition-opacity hover:bg-accent hover:opacity-100 focus-visible:opacity-100",onClick:e,"aria-label":"Expand SQL editor",title:"Expand SQL editor",children:l.jsx(Ot.Maximize2,{className:"h-3.5 w-3.5"})}):null]})}const wkt=w.forwardRef(vkt),Skt=300;function Ckt(e,t){const n=m.useEditorStore(g=>g.card.python),r=m.useEditorStore(g=>g.card),s=Hz(),{setCardPython:o,setRunSql:i}=m.useEditorActions(),a=w.useMemo(()=>s!==r.type?{...r,type:s}:r,[r,s]),{queryKey:c}=ob(a),u=Kr(),d=w.useRef(c);d.current=c;const{value:f,onChange:h,flush:p}=Abe({storeValue:n,defaultValue:mO,onStoreUpdate:o,delay:Skt});return w.useEffect(()=>Ibe(p),[p]),l.jsx(m.CodeEditor,{ref:t,value:f??"",onValueChange:h,language:"python",embedded:!0,hideLineNumbers:!0,wrapLines:!0,className:"[&_.code-editor-pre]:!pt-2 [&_.code-editor-textarea]:!pt-2",onKeyDown:g=>{g.key==="Enter"&&g.shiftKey&&(g.preventDefault(),Vz(),setTimeout(()=>{u.removeQueries({queryKey:d.current,exact:!0}),i(!0)},0))}})}const Nkt=w.forwardRef(Ckt),Rbe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),jkt=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),kkt=Array.from(Rbe).join(", "),_kt=3,Ikt="Self-heal",Tkt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function Ekt({card:e}){var U,R,q,W,F;const[t,n]=w.useState({}),{authToken:r}=Tt(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=w.useMemo(()=>Pw(o),[o]),a=m.useEditorStore(Z=>Z.frame),c=m.useEditorStore(Z=>Z.inlineFilterValuesMap[e.id]),u=m.useEditorStore(Z=>Z.actions.setCardInlineFilterValue),d=m.useEditorStore(Z=>Z.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=mf(((U=f.customCardPreferences)==null?void 0:U.url)||""),g=(R=p==null?void 0:p.visuals)==null?void 0:R.find(Z=>{var K;return Z.name===((K=f.customCardPreferences)==null?void 0:K.componentName)}),b=zb(f,g)??"single",x=w.useMemo(()=>TI({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=w.useMemo(()=>{const Z=x.findIndex(K=>(K==null?void 0:K.id)===e.id);return Z<0?-1:Yg(e,Z)},[x,e]),v=w.useMemo(()=>b!=="multiple"||y<0?e.type:Lh(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),S=w.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:v!==e.type?{...e,type:v}:e,[e,v,b]),{data:N}=ob(S),C=m.useInteractionStore(Z=>Z.interactionStates),j=m.useDashboardStore(Z=>{var K;return(K=Z.dashboard)==null?void 0:K.id}),_=m.useDashboardStore(Z=>Z.dashboard.filters),k=m.useDashboardStore(Z=>Z.filterValues),I=m.useDashboardStore(Z=>Z.selectedSheetId),T=w.useMemo(()=>k$({card:e,sheetId:I||"",inlineFilterValues:c,setInlineFilterValue:Z=>u(e.id,Z),removeInlineFilterValue:Z=>d(e.id,Z)}),[e,I,c,u,d]),{cardFilters:E,cardFilterValues:D}=w.useMemo(()=>Wv({card:e,interactionStates:C,currentDashboardId:j,filters:_,filterValues:k,selectedSheetId:I}),[e,C,j,_,k,I]),M=w.useCallback((Z,K)=>{const Y=T$(K);n(X=>({...X,[Z]:Y}))},[]),A=(q=f.customCardPreferences)==null?void 0:q.componentName,P=A?h(A):null,O=_j((W=f.customCardPreferences)==null?void 0:W.settings,f),$=w.useMemo(()=>I$(x),[x]),V=w.useMemo(()=>$.map((Z,K)=>Lh(Z,K,g==null?void 0:g.slots)),[$,g==null?void 0:g.slots]);return A?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(w.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[P&&b==="single"&&l.jsx(P,{editing:!0,params:s,theme:i,settings:O,cardMetadata:Ole({card:e,dataMetadata:N==null?void 0:N.metadata}),onDataChange:M,data:(N==null?void 0:N.records)||[],filters:E,filterValues:[...D||[],...c||[]],inlineFilters:T}),P&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((Z,K)=>{if(!Z)return null;const Y=Yg(Z,K),X=Lh(Z,Y,g==null?void 0:g.slots);return l.jsx(Z3,{onDataChange:M,card:Z,effectiveCardType:X},`${Z.id}-${Y}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(P,{editing:!0,onDataChange:M,...E$({configCard:f,slotOrderedCards:$,slotTypes:V,multiInputData:t,params:s,theme:i,chartSettings:O,filters:E,filterValues:[...D||[],...c||[]],inlineFilters:T})})})]})]},(F=f.customCardPreferences)==null?void 0:F.componentName)}):null}const Dkt=w.memo(Ekt,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),Mkt=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Pbe=["PageUp","PageDown"],Fbe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Obe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},rx="Slider",[YF,Akt,Rkt]=m.createCollection(rx),[Uz]=m.createContextScope(rx,[Rkt]),[Pkt,uS]=Uz(rx),qz=te.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=te.useRef(new Set),y=te.useRef(0),v=te.useRef(!1),N=i==="horizontal"?Fkt:Okt,[C,j]=te.useState(null),_=m.useComposedRefs(t,j),[k=[],I]=m.useControllableState({prop:d,defaultProp:u,onChange:O=>{var V;(V=[...x.current][y.current])==null||V.focus({preventScroll:!0,focusVisible:v.current}),v.current=!1,f(O)}}),T=te.useRef(k),E=te.useRef(k);te.useEffect(()=>{const O=g?C==null?void 0:C.ownerDocument.getElementById(g):C==null?void 0:C.closest("form");if(O instanceof HTMLFormElement){const $=()=>I(E.current);return O.addEventListener("reset",$),()=>O.removeEventListener("reset",$)}},[C,g,I]);function D(O){const $=Bkt(k,O);P(O,$)}function M(O){P(O,y.current)}function A(){const O=T.current[y.current];k[y.current]!==O&&h(k)}function P(O,$,{commit:V}={commit:!1}){const U=Jbe(o),R=iN(Math.round((O-r)/o)*o+r,U),q=m.clamp(R,[r,s]);I((W=[])=>{const F=$kt(W,q,$);if(Ukt(F,c*o)){y.current=F.indexOf(q);const Z=String(F)!==String(W);return Z&&V&&h(F),Z?F:W}else return W})}return l.jsx(Pkt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:k,orientation:i,form:g,children:l.jsx(YF.Provider,{scope:e.__scopeSlider,children:l.jsx(YF.Slot,{scope:e.__scopeSlider,children:l.jsx(N,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:_,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(T.current=k,v.current=!1)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:D,onSlideMove:a?void 0:M,onSlideEnd:a?void 0:A,onHomeKeyDown:()=>{a||(v.current=!0,P(r,0,{commit:!0}))},onEndKeyDown:()=>{a||(v.current=!0,P(s,k.length-1,{commit:!0}))},onStepKeyDown:({event:O,direction:$})=>{if(!a){v.current=!0;const R=Pbe.includes(O.key)||O.shiftKey&&Fbe.includes(O.key)?10:1,q=y.current,W=k[q],F=qkt(W,{min:r,step:o,direction:$,multiplier:R});P(F,q,{commit:!0})}}})})})})});qz.displayName=rx;var[Lbe,$be]=Uz(rx,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Fkt=te.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=te.useState(null),p=m.useComposedRefs(t,h),g=te.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function v(S){const N=g.current||f.getBoundingClientRect(),C=[0,N.width],_=Wz(C,y?[n,r]:[r,n]);return g.current=N,_(S-N.left)}return l.jsx(Lbe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(zbe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const N=v(S.clientX);i==null||i(N)},onSlideMove:S=>{const N=v(S.clientX);a==null||a(N)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:S=>{const C=Obe[y?"from-left":"from-right"].includes(S.key);u==null||u({event:S,direction:C?-1:1})}})})}),Okt=te.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=te.useRef(null),f=m.useComposedRefs(t,d),h=te.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],S=Wz(y,p?[r,n]:[n,r]);return h.current=x,S(b-x.top)}return l.jsx(Lbe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(zbe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Obe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),zbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=uS(rx,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Pbe.concat(Fbe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus({preventScroll:!0,focusVisible:!1}):r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),Bbe="SliderTrack",Vbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(Bbe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});Vbe.displayName=Bbe;var ZF="SliderRange",Hbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(ZF,n),o=$be(ZF,n),i=te.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>Qbe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});Hbe.displayName=ZF;var Ube="SliderThumb",[Lkt,qbe]=Uz(Ube),Wbe="SliderThumbProvider";function Gbe(e){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:s}=e,o=uS(Wbe,t),i=Akt(t),[a,c]=te.useState(null),u=te.useMemo(()=>a?i().findIndex(x=>x.ref.current===a):-1,[i,a]),d=m.useSize(a),f=a?!!o.form||!!a.closest("form"):!0,h=o.values[u],p=n??(o.name?o.name+(o.values.length>1?"[]":""):void 0),g=h===void 0?0:Qbe(h,o.min,o.max);te.useEffect(()=>{if(a)return o.thumbs.add(a),()=>{o.thumbs.delete(a)}},[a,o.thumbs]);const b={value:h,name:p,form:o.form,isFormControl:f,index:u,thumb:a,onThumbChange:c,percent:g,size:d};return l.jsx(Lkt,{scope:t,...b,children:Wkt(s)?s(b):r})}Gbe.displayName=Wbe;var oN="SliderThumbTrigger",Kbe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=uS(oN,n),o=$be(oN,n),{index:i,value:a,percent:c,size:u,onThumbChange:d}=qbe(oN,n),f=m.useComposedRefs(t,d),h=zkt(i,s.values.length),p=u==null?void 0:u[o.size],g=p?Vkt(p,c,o.direction):0;return l.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${c}% + ${g}px)`},children:l.jsx(YF.ItemSlot,{scope:n,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||h,"aria-valuemin":s.min,"aria-valuenow":a,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...r,ref:f,style:a===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{s.valueIndexToChangeRef.current=i})})})})});Kbe.displayName=oN;var Ybe=te.forwardRef((e,t)=>{const{__scopeSlider:n,name:r,...s}=e;return l.jsx(Gbe,{__scopeSlider:n,name:r,internal_do_not_use_render:({index:o,isFormControl:i})=>l.jsxs(l.Fragment,{children:[l.jsx(Kbe,{...s,ref:t,__scopeSlider:n}),i?l.jsx(Xbe,{__scopeSlider:n},o):null]})})});Ybe.displayName=Ube;var Zbe="SliderBubbleInput",Xbe=te.forwardRef(({__scopeSlider:e,...t},n)=>{const{value:r,name:s,form:o}=qbe(Zbe,e),i=te.useRef(null),a=m.useComposedRefs(i,n),c=m.usePrevious(r);return te.useEffect(()=>{const u=i.current;if(!u)return;const d=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(d,"value").set;if(c!==r&&h){const p=new Event("input",{bubbles:!0});h.call(u,r),u.dispatchEvent(p)}},[c,r]),l.jsx(m.Primitive.input,{style:{display:"none"},name:s,form:o,...t,ref:a,defaultValue:r})});Xbe.displayName=Zbe;function $kt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function Qbe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function zkt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Bkt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function Vkt(e,t,n){const r=e/2,o=Wz([0,50],[0,r]);return(r-o(t)*n)*n}function Hkt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Ukt(e,t){if(t>0){const n=Hkt(e);return Math.min(...n)>=t}return!0}function Wz(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Jbe(e){if(!Number.isFinite(e))return 0;const t=e.toString();if(t.includes("e")){const[r,s]=t.split("e"),o=r.split(".")[1]||"",i=Number(s);return Math.max(0,o.length-i)}const n=t.split(".")[1];return n?n.length:0}function iN(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function qkt(e,{min:t,step:n,direction:r,multiplier:s}){const o=Jbe(n),i=(e-t)/n,a=Math.round(i),c=iN(a*n+t,o)===iN(e,o);let u;return c?u=a+s*r:r>0?u=Math.ceil(i):u=Math.floor(i),iN(u*n+t,o)}function Wkt(e){return typeof e=="function"}const exe=te.forwardRef(({className:e,...t},n)=>l.jsxs(qz,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(Vbe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(Hbe,{className:"absolute h-full bg-primary"})}),l.jsx(Ybe,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));exe.displayName=qz.displayName;function aN(e,t){return`${e.replace(/\/$/,"")}/dashboard-authoring${t}`}function Gkt(e=!0){const{authToken:t,tokenProps:n}=Tt();return Gn({queryKey:["dashboard-authoring-sources",n.apiServiceUrl,n.project_id,n.tenantId,n.endUserId,n.orgUserId,t==null?void 0:t.accessToken],enabled:e&&!!(t!=null&&t.accessToken)&&!!n.apiServiceUrl,queryFn:async()=>(await m.getRequest(aN(n.apiServiceUrl,"/sources"),(t==null?void 0:t.accessToken)||"")).sources||[]})}function Kkt(){const{authToken:e,tokenProps:t}=Tt(),n=(e==null?void 0:e.accessToken)||"",r=t.apiServiceUrl,s=Ao({mutationFn:async a=>(await m.postRequestRegular(aN(r,"/plan"),n,a)).plan}),o=Ao({mutationFn:async a=>{const c="domainId"in a?{mode:"suggestions",domainId:a.domainId,datasetNames:a.datasetNames,instruction:a.instruction}:{mode:"suggestions",dataset:a.dataset,instruction:a.instruction};return(await m.postRequestRegular(aN(r,"/plan"),n,c)).suggestions||[]}}),i=Ao({mutationFn:async a=>{const c="plan"in a?{plan:a.plan,sharing:a.sharing}:{plan:a};return m.postRequestRegular(aN(r,"/create"),n,{...c})}});return{planDashboard:s,suggestDashboards:o,createDashboardFromPlan:i}}const FM="__describe_own__",qx=6,Ykt=350;function OM(e){return e.kind==="semantic"?e.label||e.datasetName:e.label||[e.databaseName,e.schemaName,e.tableName].filter(Boolean).join(".")||e.tableName}function DK(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"){const t=e;return typeof t.label=="string"&&t.label||typeof t.name=="string"&&t.name||typeof t.qualifiedFieldName=="string"&&t.qualifiedFieldName||void 0}}}function MK(e){return e.kind==="semantic"?{kind:"semantic",domainId:e.domainId,datasetName:e.datasetName,datasetId:e.datasetId,label:e.label,connectionId:e.connectionId}:{kind:"physical",connectionId:e.connectionId,databaseName:e.databaseName,schemaName:e.schemaName,tableName:e.tableName,label:e.label}}function Zkt(e){const t=new Map;for(const n of e){if(n.kind!=="semantic")continue;const r=n.domainId;t.has(r)||t.set(r,{id:r,label:n.domainLabel||n.domainName||"Semantic domain",items:[]}),t.get(r).items.push(n)}return Array.from(t.values())}function u1(e){return Array.from(new Set(Array.from(e).map(t=>t.trim()).filter(Boolean)))}function Xkt(e){switch(e){case"kpi":return"KPI";case"line":return"Trend";case"bar":case"stackedBar":return"Breakdown";case"table":return"Table";case"text":return"Text";default:return e?e.replace(/([A-Z])/g," $1"):"Card"}}function Qkt(e){return(e==null?void 0:e.kind)==="semantic"?e.datasetName:void 0}function txe(e){var s,o,i,a,c,u,d;const t=e.analyticsIntent,n=new Set,r=f=>{const h=Qkt(f);h&&n.add(h)};return t&&(r(t.source),t.kind==="metric"&&((s=t.measures)==null||s.forEach(f=>r(f.source)),r((o=t.primaryMeasure)==null?void 0:o.source),(i=t.dimensions)==null||i.forEach(f=>r(f.source)),r((a=t.dateField)==null?void 0:a.source),(c=t.filters)==null||c.forEach(f=>r(f.field.source))),t.kind==="records"&&((u=t.fields)==null||u.forEach(f=>r(f.source)),r((d=t.dateField)==null?void 0:d.source))),n}function Jkt(e){var o;const t=e.sheets.flatMap(i=>i.cards),n=t.filter(i=>i.type!=="text"),r=n.filter(i=>txe(i).size>1),s=((o=e.filterInputs)==null?void 0:o.length)||0;return{cards:t,dataCards:n,joinedCards:r,filterCount:s,datasetCount:e.datasets.length}}function nxe({open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,sources:o,sourcesLoading:i=!1,suggestDashboards:a,planDashboard:c,createDashboardFromPlan:u,settingsSlot:d,blankDescription:f="",description:h="Start blank, or pick a dataset to see starter ideas tailored to your data.",canCreate:p=!0,initialDomainId:g}){const[b,x]=w.useState(()=>g?"dataset":"blank"),[y,v]=w.useState(null),[S,N]=w.useState([]),[C,j]=w.useState(!1),[_,k]=w.useState(null),[I,T]=w.useState(""),[E,D]=w.useState(""),[M,A]=w.useState(""),[P,O]=w.useState(""),[$,V]=w.useState(""),[U,R]=w.useState("idle"),[q,W]=w.useState("choose"),[F,Z]=w.useState(null),K=w.useRef(!1),Y=w.useRef(0),X=w.useRef(null),z=w.useRef(!1),[B,H]=w.useState(!1),L=()=>{Y.current+=1,W("choose"),Z(null)},G=w.useMemo(()=>o.filter(De=>De.kind==="semantic"),[o]),J=G.length>0,oe=b,Q=x,ae=oe==="blank",ie=oe==="dataset",le=i?"Checking datasets...":J?void 0:"No datasets found",ue=w.useMemo(()=>{const De=new Set;for(const mt of G)mt.kind==="semantic"&&De.add(mt.domainId);return De.size===1},[G]),fe=w.useMemo(()=>Zkt(G),[G]);w.useEffect(()=>{if(!e){X.current=null,z.current=!1;return}if(!g||z.current||X.current===g)return;if((y==null?void 0:y.kind)==="semantic"&&y.domainId===g){X.current=g;return}const De=G.filter(Ct=>Ct.kind==="semantic"&&Ct.domainId===g),mt=De[0];mt&&(X.current=g,Q("dataset"),v(mt),N(De.map(Ct=>Ct.datasetName)),j(De.length>1),k(null),Y.current+=1,W("choose"),Z(null),V(""))},[g,e,y,G,Q]),w.useEffect(()=>{!y&&ue&&G.length>0&&(v(G[0]),N([G[0].datasetName]))},[y,ue,G]);const pe=w.useMemo(()=>!y||y.kind!=="semantic"?[]:G.filter(De=>De.kind==="semantic"&&De.domainId===y.domainId),[y,G]);w.useEffect(()=>{if(!y||y.kind!=="semantic"){S.length>0&&N([]),C&&j(!1);return}const De=new Set(pe.map(Ct=>Ct.datasetName));let mt=u1(S).filter(Ct=>De.has(Ct));C||(mt=mt.slice(0,qx)),mt.length===0&&mt.push(y.datasetName),mt.join("|")!==S.join("|")&&N(mt),pe.length<=1&&C&&j(!1)},[S,pe,y,C]);const ge=w.useMemo(()=>new Set(S),[S]),de=w.useMemo(()=>!y||y.kind!=="semantic"?[]:pe.filter(De=>ge.has(De.datasetName)),[ge,pe,y]),ye=C?pe.length:de.length,ce=ie&&!!y&&ye>0,re=w.useMemo(()=>C?new Set(pe.map(De=>De.datasetName)):ge,[C,pe,ge]),ee=w.useMemo(()=>new Set(pe.map(De=>De.datasetName)),[pe]),se=!C&&S.length<qx,ne=ce&&!C&&de.length>1?de.map(De=>De.datasetName):void 0,he=w.useMemo(()=>!y||!ce?"":y.kind==="semantic"?C?`${y.domainId}:whole`:`${y.domainId}:${de.map(De=>De.datasetName).join(",")}`:[y.connectionId,y.databaseName,y.schemaName,y.tableName].filter(Boolean).join(":"),[ce,de,y,C]),[_e,Le]=w.useState(he);w.useEffect(()=>{const De=window.setTimeout(()=>{Le(he)},Ykt);return()=>window.clearTimeout(De)},[he]);const Ue=he===_e;w.useEffect(()=>{e||(Q("blank"),v(null),N([]),j(!1),k(null),T(""),D(""),A(""),O(""),V(""),R("idle"),L())},[e,Q]);const je=w.useMemo(()=>{if(!y||!ce||!Ue)return null;if(y.kind==="semantic"&&(C||de.length>1))return["dashboard-suggestions","semantic-domain",y.domainId,C?"whole":de.map(De=>De.datasetName).join(","),E];if(y.kind==="semantic"){const De=de[0]||y;return["dashboard-suggestions","semantic",De.domainId,De.datasetName,E]}return["dashboard-suggestions","physical",y.connectionId,y.databaseName,y.schemaName,y.tableName,E]},[E,ce,de,y,Ue,C]),Xe=w.useMemo(()=>!y||!ce||!Ue?null:y.kind==="semantic"&&(C||de.length>1)?{domainId:y.domainId,datasetNames:ne,instruction:E||void 0}:{dataset:MK(de[0]||y),instruction:E||void 0},[E,ce,ne,de,y,Ue,C]),Ze=Gn({queryKey:je??["dashboard-suggestions","idle"],queryFn:()=>a(Xe),enabled:!!Xe&&e,staleTime:5*60*1e3,gcTime:10*60*1e3}),at=Ze.data??null,Be=(je==null?void 0:je.join("|"))??"";w.useEffect(()=>{k(null),L()},[Be]);const lt=()=>{!y||!ce||(k(null),L(),Ze.refetch())},Te=w.useMemo(()=>(at==null?void 0:at.find(De=>De.id===_))||null,[at,_]),nt=(y==null?void 0:y.kind)==="semantic"&&fe.find(De=>De.id===y.domainId)||null,Oe=(nt==null?void 0:nt.label)||"this domain",He=y?C?`All ${pe.length} datasets in ${Oe}`:`${ye} of ${pe.length} datasets in ${Oe}`:le||"Pick data to see recommendations",qe=De=>{if(De.kind!=="semantic")return;z.current=!0;const mt=(y==null?void 0:y.kind)==="semantic"&&y.domainId===De.domainId;v(De),j(!1),N(Ct=>mt&&Ct.length>0&&!C?Ct.slice(0,qx):[De.datasetName]),k(null),L(),V("")},Ae=De=>{if(De.kind!=="semantic")return;z.current=!0;const mt=(y==null?void 0:y.kind)==="semantic"&&y.domainId===De.domainId;v(De),j(!1),N(Ct=>{const Kt=mt&&!C?Ct:[],Bt=new Set(Kt);if(Bt.has(De.datasetName))Bt.delete(De.datasetName);else{if(Bt.size>=qx)return u1(Bt);Bt.add(De.datasetName)}return Bt.size===0&&Bt.add(De.datasetName),u1(Bt)}),k(null),L(),V("")},Qe=De=>{const mt=De.items[0];mt&&(z.current=!0,v(mt),N(De.items.map(Ct=>Ct.datasetName)),j(!0),k(null),L(),V(""))},ct=De=>{const mt=pe.find(Ct=>Ct.datasetName===De);mt&&(re.has(De)||Ae(mt))},It=I.trim(),yt=ce&&It!==E,kt=()=>{yt&&(D(It),k(null),L(),V(""))},Mt=De=>{De.key!=="Enter"||De.shiftKey||De.nativeEvent.isComposing||(De.preventDefault(),kt())},vt=_===FM,St=_!==null&&!vt,ke=M.trim().length>0,Ee=St||vt&&ke,Pe=P.trim().length>0,Fe=ie&&ce&&!C&&de.length===1,Ge=ie&&ce&&!Ee&&!Fe,Pt=ae||ie&&!Ee&&Fe,_t=q==="review"&&!!F,Ft=ae?Pe:ie&&ce&&(Ee||Pe&&Fe),Vt=B||c.isPending||u.isPending||s,Ht=Ee&&Vt?U==="validating"?"Validating cards against your data.":"This usually takes about 30 seconds.":null,Qn=()=>{var Kt;if(!y)return null;const De=(Te==null?void 0:Te.prompt)||M.trim()||"Create a starter dashboard.",mt=u1(((Kt=Te==null?void 0:Te.datasets)==null?void 0:Kt.map(Bt=>Bt.name))||[]),Ct=y.kind==="semantic"?mt.length>1?mt:ne:void 0;return y.kind==="semantic"&&(C||de.length>1)?{prompt:De,domainId:y.domainId,datasetNames:Ct}:{prompt:De,dataset:MK(de[0]||y)}},st=async()=>{if(K.current||Vt)return;K.current=!0,H(!0),V("");let De=null;try{if(ae){await n({title:P.trim()||"Untitled dashboard",description:f});return}if(!y)return;if(!Ee){if(!Fe)return;await n({title:P.trim()||"Untitled dashboard",description:f,dataset:de[0]||y});return}if(!F){const Kt=Qn();if(!Kt)return;const Bt=Y.current+1;Y.current=Bt,De=Bt,R("planning");const Xt=await c.mutateAsync(Kt);if(Y.current!==Bt)return;Z(Xt),W("review");return}const mt=P.trim()?{...F,title:P.trim()}:F;R("validating");const Ct=await u.mutateAsync(mt);r(Ct)}catch(mt){if(De!==null&&Y.current!==De)return;V(m.getRequestErrorMessage(mt,"The dashboard could not be created from this recommendation."))}finally{K.current=!1,H(!1),R("idle")}};return l.jsx(Gs,{open:e,onOpenChange:t,children:l.jsxs(Is,{className:`flex max-w-[94vw] flex-col gap-0 overflow-hidden p-0 transition-[width,height] duration-300 ease-out motion-reduce:transition-none ${ie?"h-[720px] max-h-[88vh] w-[1120px]":"h-[440px] w-[520px]"}`,children:[l.jsx("div",{className:"shrink-0 border-b border-border px-5 pt-4 pb-3.5",children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx(Ts,{className:"text-[15px] font-semibold tracking-tight",children:"New dashboard"}),l.jsx(Ks,{className:"mt-1 text-[12px] leading-[1.5] text-muted-foreground",children:ie?le||"Pick data on the left, then choose a starter idea.":h})]}),ie&&l.jsx("button",{type:"button",onClick:()=>{z.current=!0,Q("blank"),k(null),A(""),L(),V("")},className:"mr-6 mt-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground",children:"Start blank instead"})]})}),ae?l.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[l.jsx(AK,{kind:"blank",selected:!0,onClick:()=>{z.current=!0,Q("blank"),k(null),A(""),V("")}}),l.jsx(AK,{kind:"dataset",selected:!1,hint:le,onClick:()=>{Q("dataset"),V("")}})]}),l.jsxs("div",{className:"mt-4",children:[l.jsx(RK,{children:"Title"}),l.jsx("input",{type:"text",value:P,onChange:De=>O(De.target.value),placeholder:"Name your dashboard",className:"mt-1 block h-7 w-full rounded-[5px] border border-border bg-background px-2 text-[12px] text-foreground focus:border-foreground/40 focus:outline-none"})]}),d?l.jsx("div",{className:"mt-4",children:d}):null]}):l.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[320px_1fr] overflow-hidden",children:[l.jsx(r_t,{groups:fe,loading:i,selectedSource:y,selectedDatasetNames:ge,useWholeDomain:C,selectionLimit:qx,onPickSource:qe,onToggleDataset:Ae,onUseWholeDomain:Qe,summary:ce?He:null}),l.jsxs("div",{className:"flex min-w-0 flex-col overflow-hidden",children:[q==="choose"&&l.jsx("div",{className:"shrink-0 border-b border-border px-4 py-3",children:l.jsxs("div",{className:"flex items-end gap-2 rounded-[6px] border border-border bg-background px-3 py-2 focus-within:border-foreground/40",children:[l.jsx("textarea",{rows:2,value:I,onChange:De=>T(De.target.value),onKeyDown:Mt,placeholder:"Add context to steer every idea. e.g. focus on last quarter, use USD, exclude internal accounts.",className:"block flex-1 resize-none bg-transparent text-[12px] leading-[1.55] text-foreground placeholder:text-muted-foreground focus:outline-none"}),l.jsx(m.Button,{type:"button",size:"xs",variant:It?"default":"secondary",disabled:!yt,onClick:kt,children:"Update ideas"})]})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-4 border-b border-border px-4 py-2",children:[l.jsx(t_t,{step:_t?"review":"choose"}),!_t&&l.jsxs("button",{type:"button",onClick:lt,disabled:!ce||at===null,className:"ml-auto inline-flex h-6 items-center gap-1 rounded-[3px] px-1.5 text-[10.5px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50",children:[l.jsx(Xl,{className:"h-2.5 w-2.5"}),"Suggest more"]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[_t?l.jsx(n_t,{plan:F,titleOverride:P.trim()}):ce?l.jsx("div",{children:at===null?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Fetching recommendations…"]}),l.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Array.from({length:4}).map((De,mt)=>l.jsx(a_t,{},mt))})]}):l.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[at.slice(0,4).map(De=>l.jsx(s_t,{suggestion:De,selected:_===De.id,selectedDatasetNames:re,domainDatasetNames:ee,canAddDataset:se,onAddDataset:ct,onClick:()=>{k(mt=>mt===De.id?null:De.id),A(""),L(),V("")}},De.id)),l.jsx(i_t,{selected:vt,onClick:()=>{k(De=>De===FM?null:FM),L(),V("")}})]})}):l.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-1 text-center",children:[l.jsx(fo,{className:"h-5 w-5 text-muted-foreground"}),l.jsx("div",{className:"mt-2 text-[12.5px] font-medium text-foreground",children:i?"Loading datasets…":"Pick data to see recommendations"}),l.jsx("div",{className:"max-w-[320px] text-[11.5px] leading-relaxed text-muted-foreground",children:"Pick one or more datasets on the left, or All datasets in a domain."})]}),vt&&l.jsx("div",{className:"mt-3 rounded-[5px] border border-border bg-background focus-within:border-foreground/40",children:l.jsx("textarea",{rows:3,autoFocus:!0,value:M,onChange:De=>{A(De.target.value),L(),V("")},placeholder:"e.g. Executive view with revenue KPIs, weekly trend, and a top-customers table.",className:"block w-full resize-none bg-transparent px-2.5 py-2 text-[12px] leading-[1.55] text-foreground placeholder:text-muted-foreground focus:outline-none"})}),ce&&(Ee||Fe)&&l.jsxs("div",{className:"mt-4",children:[l.jsx(RK,{children:Pt?"Title":"Title (optional)"}),l.jsx("input",{type:"text",value:P,onChange:De=>O(De.target.value),placeholder:Pt?"Name your dashboard":(Te==null?void 0:Te.title)||"We will suggest one",className:"mt-1 block h-7 w-full rounded-[5px] border border-border bg-background px-2 text-[12px] text-foreground focus:border-foreground/40 focus:outline-none"})]}),Ge&&l.jsx("div",{className:"mt-4 rounded-[5px] border border-border bg-muted/30 px-3 py-2 text-[11.5px] leading-relaxed text-muted-foreground",children:"Choose a recommendation or describe what you want to create from this data scope."}),$&&l.jsx("div",{className:"mt-4 rounded-[5px] border border-destructive/30 bg-destructive/5 px-3 py-2 text-[11.5px] leading-relaxed text-destructive",children:$}),d?l.jsx("div",{className:"mt-4",children:d}):null]})]})]}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-3 border-t border-border bg-muted/30 px-5 py-2.5",children:l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Ht?l.jsx("span",{className:"truncate text-right text-[11px] text-muted-foreground",children:Ht}):null,l.jsx(m.Button,{type:"button",variant:"ghost",size:"xs",onClick:()=>t(!1),disabled:Vt,children:"Cancel"}),_t?l.jsx(m.Button,{type:"button",variant:"secondary",size:"xs",onClick:()=>{L(),V("")},disabled:Vt,children:"Back to ideas"}):null,l.jsx(m.Button,{type:"button",size:"xs",disabled:!Ft||!p||Vt,onClick:st,children:Vt?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),Ee?U==="planning"?"Planning Insights…":U==="validating"?"Validating cards…":"Building dashboard…":"Creating…"]}):l.jsxs(l.Fragment,{children:[Ee&&!_t?"Review plan":"Create dashboard",l.jsx(Lv,{className:"h-3 w-3"})]})})]})})]})})}function e_t({open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,initialDomainId:o}){const i=Gkt(e),{suggestDashboards:a,planDashboard:c,createDashboardFromPlan:u}=Kkt();return l.jsx(nxe,{open:e,onOpenChange:t,onCreateBlank:n,onAiCreateSuccess:r,isCreatingBlank:s,sources:i.data||[],sourcesLoading:i.isLoading,suggestDashboards:a.mutateAsync,planDashboard:c,createDashboardFromPlan:u,initialDomainId:o})}function t_t({step:e}){const t=[{id:"choose",label:"Choose idea"},{id:"review",label:"Review plan"}],n=t.findIndex(r=>r.id===e);return l.jsx("div",{className:"flex items-center gap-2",children:t.map((r,s)=>{const o=r.id===e,i=s<n;return l.jsxs("div",{className:"flex items-center gap-2",children:[s>0&&l.jsx("span",{className:"h-px w-4 bg-border","aria-hidden":"true"}),l.jsxs("span",{className:`inline-flex h-5 items-center gap-1 rounded-full px-2 text-[10px] font-medium ${o?"bg-foreground text-background":i?"bg-muted text-foreground":"bg-transparent text-muted-foreground"}`,children:[i?l.jsx(m.Check,{className:"h-2.5 w-2.5"}):l.jsx("span",{children:s+1}),r.label]})]},r.id)})})}function n_t({plan:e,titleOverride:t}){const n=Jkt(e),r=e.datasets.map(o=>o.kind==="semantic"?o.label||o.datasetName:o.kind==="physical"?o.label||[o.databaseName,o.schemaName,o.tableName].filter(Boolean).join(".")||o.tableName:o.label||"Dataset"),s=[...(e.warnings||[]).map(o=>o.message),...e.unresolvedRequests||[]].filter(Boolean);return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:t||e.title||"Dashboard plan"}),e.description&&l.jsx("div",{className:"mt-1 max-w-[680px] text-[11.5px] leading-relaxed text-muted-foreground",children:e.description})]}),l.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[l.jsx(d1,{label:"Cards",value:n.dataCards.length}),l.jsx(d1,{label:"Datasets",value:n.datasetCount}),l.jsx(d1,{label:"Filters",value:n.filterCount}),l.jsx(d1,{label:"Joined cards",value:n.joinedCards.length})]}),l.jsxs("div",{children:[l.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Cards to create"}),l.jsx("div",{className:"divide-y divide-border rounded-[6px] border border-border",children:n.cards.slice(0,mxe.DASHBOARD_AUTHORING_MAX_GENERATED_CARDS).map(o=>{const i=Array.from(txe(o));return l.jsxs("div",{className:"grid grid-cols-[88px_1fr_auto] items-center gap-2 px-2.5 py-2",children:[l.jsx("span",{className:"rounded-[3px] bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:Xkt(o.type)}),l.jsx("span",{className:"min-w-0 truncate text-[12px] text-foreground",children:o.title}),i.length>0&&l.jsx("span",{className:"max-w-[220px] truncate text-[10.5px] text-muted-foreground",children:i.join(" + ")})]},o.id)})})]}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsx(LM,{title:"Datasets",empty:"No datasets selected",items:r}),l.jsx(LM,{title:"Filters",empty:"No dashboard filters planned",items:(e.filterInputs||[]).map(o=>o.label)})]}),n.joinedCards.length>0&&l.jsx(LM,{title:"Relationship-based cards",empty:"No relationship-based cards planned",items:n.joinedCards.map(o=>o.title)}),s.length>0&&l.jsx("div",{className:"rounded-[6px] border border-amber-300/60 bg-amber-50/60 px-3 py-2 text-[11.5px] leading-relaxed text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300",children:s.slice(0,3).map(o=>l.jsx("div",{children:o},o))})]})}function d1({label:e,value:t}){return l.jsxs("div",{className:"rounded-[6px] border border-border bg-muted/20 px-2.5 py-2",children:[l.jsx("div",{className:"text-[15px] font-semibold tabular-nums text-foreground",children:t}),l.jsx("div",{className:"mt-0.5 truncate text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:e})]})}function LM({title:e,empty:t,items:n}){return l.jsxs("div",{children:[l.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),l.jsx("div",{className:"min-h-10 rounded-[6px] border border-border px-2.5 py-2 text-[11.5px] leading-relaxed",children:n.length>0?l.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.slice(0,8).map(r=>l.jsx("span",{className:"max-w-full truncate rounded-[3px] bg-muted px-1.5 py-0.5 text-muted-foreground",children:r},r))}):l.jsx("span",{className:"text-muted-foreground",children:t})})]})}function r_t({groups:e,loading:t,selectedSource:n,selectedDatasetNames:r,useWholeDomain:s,selectionLimit:o,onPickSource:i,onToggleDataset:a,onUseWholeDomain:c,summary:u}){const[d,f]=w.useState(""),[h,p]=w.useState({}),g=d.trim().toLowerCase(),b=(n==null?void 0:n.kind)==="semantic"?n.domainId:null,x=!s&&r.size>=o,y=N=>!g||(N||"").toLowerCase().includes(g),v=e.filter(N=>y(N.label)||N.items.some(C=>y(OM(C)))),S=N=>h[N.id]!==void 0?h[N.id]:g||e.length===1?!0:N.id===b;return l.jsxs("div",{className:"flex min-w-0 flex-col overflow-hidden border-r border-border",children:[l.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2.5",children:[l.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 focus-within:border-foreground/40",children:[l.jsx(Ot.Search,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("input",{value:d,onChange:N=>f(N.target.value),placeholder:"Search datasets…",className:"h-7 flex-1 bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),d&&l.jsx("button",{type:"button",onClick:()=>f(""),className:"flex h-4 w-4 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-accent hover:text-foreground",children:l.jsx(Ce.X,{className:"h-2.5 w-2.5"})})]}),l.jsxs("div",{className:"mt-2.5 flex items-center justify-between gap-2",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Dashboard scope"}),x&&l.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Max ",o," · clear one to swap"]})]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto px-2 py-2",children:[t&&l.jsxs("div",{className:"flex items-center gap-2 px-1 py-2 text-[11px] text-muted-foreground",children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Loading datasets…"]}),!t&&v.length===0&&l.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[l.jsx("div",{className:"text-[12px] text-foreground",children:"No datasets found"}),l.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:"Try a different search or connect a semantic domain."})]}),v.map(N=>{const C=S(N),j=b===N.id&&s,_=j?N.items.length:N.items.filter(T=>b===N.id&&r.has(T.datasetName)).length,k=y(N.label),I=g&&!k?N.items.filter(T=>y(OM(T))):N.items;return l.jsxs("div",{className:"mb-0.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5 rounded-[4px] px-1.5 py-1.5 hover:bg-accent/60",children:[l.jsxs("button",{type:"button",onClick:()=>p(T=>({...T,[N.id]:!C})),className:"flex min-w-0 flex-1 items-center gap-1.5 text-left",children:[C?l.jsx(Ce.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):l.jsx(Ot.ChevronRight,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx(fo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:N.label}),l.jsx("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:_>0?`${_}/${N.items.length}`:N.items.length})]}),j?l.jsxs("button",{type:"button",onClick:()=>i(N.items[0]),className:"inline-flex h-5 items-center gap-1 rounded-[3px] bg-foreground px-1.5 text-[10px] font-medium text-background",title:"All datasets in this domain are selected. Click to go back to picking datasets.",children:[l.jsx(zv,{className:"h-2.5 w-2.5"}),"All datasets"]}):l.jsx("button",{type:"button",onClick:()=>c(N),className:"inline-flex h-5 items-center rounded-[3px] border border-border px-1.5 text-[10px] font-medium text-muted-foreground hover:border-foreground/40 hover:text-foreground",title:"Use every dataset in this domain",children:"All datasets"})]}),C&&l.jsx("div",{className:"ml-3.5 border-l border-border pl-1.5",children:I.map(T=>{const E=j||b===N.id&&r.has(T.datasetName),D=b===N.id&&!s&&!E&&r.size>=o;return l.jsxs("button",{type:"button",onClick:()=>a(T),disabled:D,"aria-pressed":E,className:`flex w-full items-center gap-2 rounded-[4px] px-1.5 py-1.5 text-left ${E?"bg-accent":"hover:bg-accent/60"} ${D?"cursor-not-allowed opacity-45 hover:bg-transparent":""}`,children:[l.jsx("span",{className:`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-[4px] border ${E?"border-foreground bg-foreground text-background":"border-border"}`,children:E&&l.jsx(m.Check,{className:"h-2.5 w-2.5"})}),l.jsx(m.Table2,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"flex-1 truncate text-[12px] text-foreground/90",children:OM(T)}),DK(T.primaryDateField)&&l.jsx("span",{className:"truncate text-[10px] text-muted-foreground",children:DK(T.primaryDateField)})]},`${N.id}:${T.datasetName}`)})})]},N.id)})]}),l.jsx("div",{className:"shrink-0 border-t border-border px-3 py-2.5 text-[11px] leading-relaxed",children:u?l.jsxs("span",{className:"flex items-center gap-1.5 text-muted-foreground",children:[l.jsx(Exe,{className:"h-3 w-3 shrink-0"}),l.jsx("span",{className:"font-medium text-foreground",children:u})]}):l.jsx("span",{className:"text-muted-foreground",children:"Pick data to see recommendations."})})]})}function s_t({suggestion:e,selected:t,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o,onClick:i}){var a;return l.jsxs("div",{className:`group relative flex flex-col overflow-hidden rounded-[5px] border bg-background transition-colors ${t?"border-foreground":"border-border hover:border-foreground/30"}`,children:[l.jsxs("button",{type:"button",onClick:i,className:"block w-full px-2.5 pt-2.5 pb-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground/40",children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"truncate text-[12.5px] font-medium text-foreground",title:e.title,children:e.title}),l.jsx("div",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",title:e.description,children:e.description})]}),t&&l.jsx("div",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full bg-foreground",children:l.jsx(m.Check,{className:"h-2.5 w-2.5 text-background"})})]}),l.jsx("div",{className:"mt-2 flex gap-1",children:e.preview.slice(0,5).map((c,u)=>l.jsx(l_t,{kind:c},u))})]}),l.jsx("div",{className:"flex flex-wrap items-center gap-1.5 px-2.5 pb-2.5 pt-1.5 text-[10px] text-muted-foreground",children:(a=e.datasets)!=null&&a.length?l.jsx(o_t,{datasets:e.datasets,relationshipHints:e.relationshipHints,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o}):l.jsxs(l.Fragment,{children:[l.jsxs("span",{children:[e.cardCount," cards"]}),e.filterCount>0&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-border",children:"·"}),l.jsxs("span",{children:[e.filterCount," filter",e.filterCount>1?"s":""]})]})]})})]})}function o_t({datasets:e,relationshipHints:t,selectedDatasetNames:n,domainDatasetNames:r,canAddDataset:s,onAddDataset:o}){const i=t!=null&&t.length?t.join(`
1321
1321
  `):e.map(a=>a.label||a.name).join(", ");return l.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-1",title:i,children:e.map(a=>{const c=n.has(a.name),u=!c&&s&&r.has(a.name),d=a.label||a.name;return u?l.jsxs("button",{type:"button",title:`Add ${d} to your selection`,"aria-label":`Add ${d} to your selection`,onClick:()=>o(a.name),className:"inline-flex max-w-[112px] cursor-pointer items-center gap-0.5 rounded-[3px] border border-amber-400/60 bg-amber-50 px-1.5 py-0.5 text-[9.5px] font-medium text-amber-700 hover:border-amber-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-500 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-400",children:[l.jsx(Ar,{className:"h-2.5 w-2.5 shrink-0"}),l.jsx("span",{className:"truncate",children:d})]},a.name):l.jsx("span",{className:`max-w-[96px] truncate rounded-[3px] border px-1.5 py-0.5 text-[9.5px] ${c?"border-border bg-muted/40 text-muted-foreground":"border-amber-400/50 bg-amber-50/60 text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/5 dark:text-amber-400/90"}`,title:c?void 0:`${d} is not in your selection`,children:d},a.name)})})}function AK({kind:e,selected:t,onClick:n,disabled:r=!1,hint:s}){const o=e==="blank"?Ixe:fo,i=e==="blank"?"Blank dashboard":"From a dataset",a=e==="blank"?"Empty canvas. Build it yourself.":"Pick a dataset and we'll suggest starter ideas.";return l.jsxs("button",{type:"button",onClick:n,disabled:r,className:`group relative flex h-full flex-col gap-2 rounded-[5px] border bg-background px-3 py-2.5 text-left transition-colors ${t?"border-foreground":"border-border enabled:hover:border-foreground/30"} disabled:cursor-not-allowed disabled:opacity-60`,title:r&&s?s:void 0,children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-[4px] border border-border bg-muted/40 text-muted-foreground",children:l.jsx(o,{className:"h-3.5 w-3.5"})}),t&&l.jsx("div",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full bg-foreground",children:l.jsx(m.Check,{className:"h-2.5 w-2.5 text-background"})})]}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"truncate text-[12.5px] font-medium text-foreground",children:i}),l.jsx("div",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:s||a})]})]})}function i_t({selected:e,onClick:t}){return l.jsxs("button",{type:"button",onClick:t,className:`group relative flex flex-col overflow-hidden rounded-[5px] border border-dashed bg-background p-2.5 text-left transition-colors ${e?"border-foreground":"border-border hover:border-foreground/40"}`,children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"truncate text-[12.5px] font-medium text-foreground",children:"Describe what you want"}),l.jsx("div",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:"Tell us the key metrics, breakdowns, and views you want to see."})]}),e&&l.jsx("div",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full bg-foreground",children:l.jsx(m.Check,{className:"h-2.5 w-2.5 text-background"})})]}),l.jsx("div",{className:"mt-2 flex h-[28px] items-center justify-start rounded-[3px] border border-dashed border-border px-2 text-[10px] text-muted-foreground",children:"Metrics, breakdowns, KPIs…"}),l.jsx("div",{className:"mt-1.5 text-[10px] text-muted-foreground",children:"Tailored to what you describe"})]})}function a_t(){return l.jsxs("div",{className:"rounded-[5px] border border-border p-2.5",children:[l.jsx("div",{className:"h-3 w-32 rounded-[3px] bg-muted/60"}),l.jsx("div",{className:"mt-1 h-2 w-44 rounded-[3px] bg-muted/60"}),l.jsx("div",{className:"mt-2 flex gap-1",children:Array.from({length:4}).map((e,t)=>l.jsx("div",{className:"h-8 w-10 rounded-[3px] bg-muted/60"},t))})]})}function l_t({kind:e}){return l.jsx("div",{className:"flex h-8 w-10 items-center justify-center rounded-[3px] border border-border bg-muted/30",children:l.jsx(c_t,{kind:e})})}function c_t({kind:e}){return e==="kpi"?l.jsx("div",{className:"text-[8px] font-semibold tabular-nums text-foreground/80",children:"1.2M"}):e==="line"?l.jsx("svg",{viewBox:"0 0 40 16",className:"h-3 w-8 text-muted-foreground",children:l.jsx("polyline",{fill:"none",stroke:"currentColor",strokeWidth:"1",points:"0,12 8,10 16,7 24,9 32,4 40,5"})}):e==="bar"?l.jsx("svg",{viewBox:"0 0 40 16",className:"h-3 w-8 text-muted-foreground",children:[6,10,7,12,9].map((t,n)=>l.jsx("rect",{x:n*8+1,y:15-t,width:"5",height:t,fill:"currentColor"},n))}):e==="donut"?l.jsxs("svg",{viewBox:"0 0 16 16",className:"h-3.5 w-3.5",children:[l.jsx("circle",{cx:"8",cy:"8",r:"6",fill:"none",strokeWidth:"2.5",className:"stroke-border"}),l.jsx("circle",{cx:"8",cy:"8",r:"6",fill:"none",strokeWidth:"2.5",strokeDasharray:"22 60",transform:"rotate(-90 8 8)",className:"stroke-muted-foreground"})]}):e==="table"?l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"h-[2px] w-7 rounded-full bg-muted-foreground/60"}),l.jsx("div",{className:"h-[2px] w-7 rounded-full bg-muted-foreground/60"}),l.jsx("div",{className:"h-[2px] w-7 rounded-full bg-muted-foreground/60"}),l.jsx("div",{className:"h-[2px] w-7 rounded-full bg-muted-foreground/60"})]}):null}function RK({children:e}){return l.jsx("label",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})}function u_t(){const e=w.useContext(wO);if(e&&e.isSemaphorClient)return e}function rxe({children:e}){const{setIsSessionExpired:t}=m.useDashboardActions(),n=u_t(),[r]=w.useState(()=>{const s=new r0e({queryCache:new KY({onError:o=>{o instanceof Error?(console.error(`Something went wrong: ${o.message}`),o.message==="invalid token"&&t(!0)):console.error("Something went wrong:",o)}}),defaultOptions:{queries:{gcTime:36e5,staleTime:3e5,refetchOnWindowFocus:!1,retry:!1}}});return s.isSemaphorClient=!0,s});return n?l.jsx(l.Fragment,{children:e}):l.jsx(s0e,{client:r,children:e})}const d_t={id:"",authToken:void 0,tokenProps:{}},dS=w.createContext(d_t),Gz=({children:e,dashboardProps:t})=>{const n=w.useMemo(()=>{let r={};const s=t.authToken;return s&&(r=Ce.jwtDecode(s.accessToken)),{...t,tokenProps:r}},[t]);return l.jsx(rxe,{children:l.jsx(dS.Provider,{value:n,children:e})})};function Tt(){const e=w.useContext(dS);if(e===void 0)throw new Error("useApplicationContext must be used within a ApplicationContextProvider");return e}function fS(){const{authToken:e,version:t,tokenProps:n,id:r}=Tt(),s=Ro(g=>g.selectedDashboard),o=Ro(g=>g.showHub),i=m.useDashboardStore(g=>g.selectedLensId),a=f_t({showHub:o,selectedDashboardId:s==null?void 0:s.id,dashboardId:r,tokenDashboardId:n==null?void 0:n.dashboard_id});function c(){return!(!(e!=null&&e.accessToken)||!a)}const{data:u,isLoading:d,isFetching:f,isError:h,refetch:p}=Gn({queryKey:["dashboard",i,e==null?void 0:e.accessToken,a],queryFn:()=>m.getDashboard(n.apiServiceUrl,e==null?void 0:e.accessToken,{lensId:i,version:t,dashboardId:a}),enabled:c()});return{data:u,isLoading:d,isFetching:f,isError:h,refetch:p,dashboardIdToFetch:a}}function f_t({showHub:e,selectedDashboardId:t,dashboardId:n,tokenDashboardId:r}){return e?null:t||n||r||null}function h_t(){const{authToken:e}=Tt(),t=m.useDashboardStore(r=>r.authToken),{setAuthToken:n}=m.useDashboardActions();return w.useLayoutEffect(()=>{const r=e==null?void 0:e.accessToken,s=t==null?void 0:t.accessToken;e&&r!==s&&n(e)},[e,t,n]),e}function $M(e,t){return e&&t.has(e)?e:null}function m_t({selectedSheetId:e,preservedSelectedSheetId:t,defaultSheetId:n,sheets:r}){var o;const s=new Set((r||[]).map(i=>i.id).filter(i=>typeof i=="string"));return $M(e,s)||$M(t,s)||$M(n,s)||((o=r==null?void 0:r[0])==null?void 0:o.id)||null}function p_t(e){var i,a;const t=[...e.inputs||[]],n=new Set(t.map(c=>c.id)),r=new Set((e.sheets||[]).filter(c=>c.kind==="document").map(c=>c.id));let s=!1;for(const c of e.sheets||[])if(!(c.kind!=="document"||!((a=(i=c.document)==null?void 0:i.inputs)!=null&&a.length)))for(const u of c.document.inputs)n.has(u.id)||(t.push(g_t(u,c.id)),n.add(u.id),s=!0);const o=t.map(c=>{if(c.kind==="filter"&&PK(c,r)&&c.filter.variableName!==c.variableName)return s=!0,{...c,filter:{...c.filter,variableName:c.variableName}};if(c.kind!=="control"||!PK(c,r))return c;const u=Ed(c.control.id||c.variableName,t.filter(d=>d.id!==c.id));return c.variableName===u&&c.control.id===u?c:(s=!0,{...c,variableName:u,control:{...c.control,id:u}})});return s?{...e,inputs:o}:e}function g_t(e,t){const n={id:e.id,label:e.label,variableName:e.variableName,description:e.description,requiredAtExecution:e.requiredAtExecution,scope:{kind:"sheets",sheetIds:[t]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},exports:e.exports,compatibility:{source:"documentInput",sheetId:t,inputId:e.id}};return e.kind==="filter"?{...n,kind:"filter",filter:e.filter}:{...n,kind:"control",control:e.control}}function PK(e,t){var n;switch(e.scope.kind){case"allSheets":return!((n=e.scope.sheetKinds)!=null&&n.length)||e.scope.sheetKinds.includes("document");case"sheets":return e.scope.sheetIds.some(r=>t.has(r));case"documentSections":return t.has(e.scope.sheetId);default:return!1}}function b_t(e){return e==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function x_t(e,t){const n=b_t(e);return n==="dark"?Ql({...t==null?void 0:t.default},{...t==null?void 0:t.dark}):t==null?void 0:t.default}function FK(e,t,n){return _ye(x_t(e,t),n)}function y_t(e){return uo.stableSerialize({hasExplicitDefaultControlValues:e!==void 0,values:e??null})}function v_t(e,t){const{controlContractOverrides:n,cardId:r}=t;if(!n||(n.controlDefinitions!==void 0&&(e.controls=n.controlDefinitions),typeof r!="string"||r.trim().length===0))return e;const s=m.findCardById(e,r);return s&&(n.cardControlDefinitions!==void 0&&(s.controls=n.cardControlDefinitions),n.controlBindings!==void 0&&(s.controlBindings=n.controlBindings)),e}function w_t(e,t){const n=w.useRef({key:t,value:e});return n.current.key!==t&&(n.current={key:t,value:e}),n.current.value}function S_t({customStyle:e,currentTheme:t,onSave:n,onEvent:r,defaultFilterValues:s,defaultControlValues:o,controlContractOverrides:i,dashboardInputExecutionSnapshot:a,type:c,cardId:u,selectedSheetId:d,onFilterValuesChange:f}){var pe,ge;const{authToken:h,tokenProps:p}=Tt(),g=h==null?void 0:h.accessToken,b=h==null?void 0:h.refreshToken,x=w.useMemo(()=>jte(),[]);h_t();const y=m.useDashboardStore(de=>de.selectedLensId),v=m.useDashboardStore(de=>de.relaodToken),{data:S,isLoading:N,isFetching:C,isError:j,refetch:_,dashboardIdToFetch:k}=fS(),I=(pe=S==null?void 0:S.dashboard)==null?void 0:pe.id,{getDefaultSheetId:T,clearDefaultSheetId:E}=ube(I),[D,M]=w.useState(s||[]),A=w.useRef(null),P=w.useRef(null),O=y_t(o),$=PA(i),V=PA(i,{includePresentation:!0}),U=w.useRef(o);U.current=o;const R=w.useRef(O);R.current=O;const q=w_t(i,V),W=w.useRef(null),F=w.useRef(!1),Z=w.useRef({dashboardId:null,defaultControlValuesKey:O,controlContractOverridesKey:$}),{setTheme:K}=pO(),{compiledAppearance:Y}=m.useAppearance(),X=m.useDashboardStore(de=>de.dashboard.globalStyle),z=w.useMemo(()=>S!=null&&S.dashboard?p_t(v_t(hi(S.dashboard),{controlContractOverrides:q,cardId:u})):void 0,[S==null?void 0:S.dashboard,q,c,u]),{setDashboardWithFilterValues:B,hydrateRuntimeControlValues:H,setStyle:L,setOnSaveFunction:G,setLenses:J,setSelectedLensId:oe,setInlineFilterValuesMap:Q}=m.useDashboardActions();m.useDashboardStore(de=>de.actions.setCustomCards);const ae=m.useDashboardStore(de=>de.filterValues),ie=m.useDashboardStore(de=>de.actions.setThemeStyle),le=m.useDashboardStore(de=>de.actions.setDashboardTheme),ue=m.useDashboardStore(de=>de.actions.setOnEvent);w.useEffect(()=>{const de=P.current;de&&de!==k&&m.storeEvents.emit("dashboard:unload"),P.current=k},[k]),w.useEffect(()=>{v&&_()},[_,v]),w.useEffect(()=>{var ce;const de=((ce=S==null?void 0:S.dashboard)==null?void 0:ce.id)||null,ye=A.current;de&&de!==ye&&m.storeEvents.emit("dashboard:load"),A.current=de},[(ge=S==null?void 0:S.dashboard)==null?void 0:ge.id]),w.useEffect(()=>{le(Y.mode)},[Y.mode,le]),w.useEffect(()=>{t&&K(t)},[t,K]);const fe=w.useCallback(()=>{const de=hi(m.DEFAULT_STYLE),ye=Ql(de,X);if(e){const ce=Ql(ye,e),re=FK(Y.mode,ce,Y);ie(re),L(ce)}else{const ce=FK(Y.mode,ye,Y);ie(ce),L(m.DEFAULT_STYLE)}},[Y,e,X,ie,L]);return w.useEffect(()=>{S&&S.dashboard&&fe()},[Y.mode,e,X,fe,S]),w.useEffect(()=>{var Qe,ct,It,yt,kt,Mt;function de(vt,St){const ke=vt.filters||[],Ee=[];for(const Pe of St){const Fe=ke.find(Ge=>Ge.id===Pe.filterId);Fe&&Ee.push({filterId:Pe.filterId,name:Fe.column,operation:Pe.operation,valueType:m.getFilterValueType(Fe),values:Pe.values,dataType:Fe.dataType,fieldMeta:Fe.fieldMeta,semanticContext:Fe.semanticContext})}return Ee}if(!S||!z)return;const ye=z,ce=m.useDashboardStore.getState(),re=ce.reportContextSessionAccessToken===g&&((Qe=ce.dashboard)==null?void 0:Qe.id)===z.id&&ce.reportContext!==null,ee=x??S.initialReportContext,se=(re?(ct=ce.reportContext)==null?void 0:ct.calendar.tz:void 0)??ee.calendar.tz,{filterValues:ne,defaultLensId:he,lenses:_e}=S;function Le(){if(ne&&(ne==null?void 0:ne.length)>0)return ne;const St=[...m.buildFilterValuesFromDefaults(ye.filters,se)];if(ye.defaultFilterValues&&ye.defaultFilterValues.length>0)for(const Pe of ye.defaultFilterValues){const Fe=St.findIndex(Ge=>Ge.filterId===Pe.filterId);Fe>=0?St[Fe]=Pe:St.push(Pe)}const ke=de(ye,D||[]),Ee=[...St];for(const Pe of ke){const Fe=Ee.findIndex(Ge=>Ge.filterId===Pe.filterId);Fe>=0?Ee[Fe]=Pe:Ee.push(Pe)}return Ee}const Ue=W.current===z.id&&((It=ce.dashboard)==null?void 0:It.id)===z.id,je=Le(),Xe=Ue?m.resolveSameDashboardFilterValues({previousFilters:(yt=ce.dashboard)==null?void 0:yt.filters,nextFilters:ye.filters,currentFilterValues:ce.filterValues,defaultFilterValues:je}):je,Ze=m.computeInlineFilterDefaults(ye,se),at=Ue&&Z.current.controlContractOverridesKey===$?m.flattenRuntimeControlValues({dashboardValues:ce.controlValues,cardValuesMap:ce.cardControlValuesMap}):U.current,Be=ce.selectedSheetId;let lt=T(),Te=Be;Te&&((kt=z==null?void 0:z.sheets)!=null&&kt.some(St=>St.id===Te)||(Te=null)),lt&&((Mt=z==null?void 0:z.sheets)!=null&&Mt.some(St=>St.id===lt)||(E(),lt=null));const nt=m_t({selectedSheetId:d,preservedSelectedSheetId:Te,defaultSheetId:lt,sheets:z==null?void 0:z.sheets}),Oe=!!a,He=!!(y||S!=null&&S.defaultLensId),qe=!Oe&&F.current,Ae=a?BA({dashboard:ye,dashboardInputValues:a.dashboardInputValues,sheetId:a.sheetId,cardId:a.cardId}):(S==null?void 0:S.inputValues)!=null?BA({dashboard:ye,dashboardInputValues:S.inputValues.dashboardInputValues}):void 0;B(ye,Xe||[],at,{selectedSheetId:nt,reportContext:re?void 0:ee,authToken:g?{accessToken:g,refreshToken:b}:void 0,...S!=null&&S.semanticExecutionPayload?{semanticExecutionPayload:S.semanticExecutionPayload}:{},...a?{dashboardInputValues:Ae,dashboardInputReferenceTime:a.generatedAt}:He?{dashboardInputValues:Ae||{},dashboardInputReferenceTime:(S==null?void 0:S.inputValues)!=null?S.inputValues.generatedAt:void 0}:qe?{dashboardInputValues:{},dashboardInputReferenceTime:void 0}:{}}),F.current=Oe,W.current=z.id,Z.current.dashboardId!==z.id&&(Z.current={dashboardId:z.id,defaultControlValuesKey:R.current,controlContractOverridesKey:$}),Q(Ze),_e&&J(_e),he&&oe(he)},[S,y,J,B,oe,Q,D,d,T,E,$,a,z,g,b,x]),w.useEffect(()=>{if(!(z!=null&&z.id))return;const de=Z.current;if(de.dashboardId!==z.id){Z.current={dashboardId:z.id,defaultControlValuesKey:O,controlContractOverridesKey:$};return}de.defaultControlValuesKey===O&&de.controlContractOverridesKey===$||(H(z,U.current),Z.current={dashboardId:z.id,defaultControlValuesKey:O,controlContractOverridesKey:$})},[z,O,$,H]),w.useEffect(()=>{f&&ae&&f(ae)},[ae,f]),w.useEffect(()=>{n&&G(n),r&&ue(r)},[n,G,r,ue]),{isFetching:C,isLoading:N,isError:j,refetch:_}}function C_t({label:e,value:t,onChange:n,placeholder:r="Filter…",className:s}){const[o,i]=te.useState(!1),a=te.useRef(null),c=t.trim().length>0,u=o||c;return te.useEffect(()=>{var d;o&&((d=a.current)==null||d.focus())},[o]),l.jsxs("div",{className:m.cn("relative grid h-4 w-full min-w-0 grid-cols-1 grid-rows-1 items-center",s),children:[l.jsxs("button",{type:"button","aria-label":`Filter ${e.toLowerCase()}`,onClick:()=>i(!0),className:m.cn("col-start-1 row-start-1 flex h-4 w-full min-w-0 items-center gap-1 font-[inherit] text-[inherit] leading-none tracking-[inherit] [text-transform:inherit] text-muted-foreground hover:text-foreground focus:outline-none focus-visible:text-foreground",u&&"invisible"),children:[l.jsx("span",{className:"truncate",children:e}),l.jsx(Ot.Search,{className:"h-3 w-3 shrink-0",strokeWidth:2})]}),l.jsxs("div",{className:m.cn("col-start-1 row-start-1 flex h-4 w-full min-w-0 items-center gap-1",!u&&"invisible"),children:[l.jsx(Ot.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground/60","aria-hidden":!0}),l.jsx("input",{ref:a,value:t,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Escape"&&(c&&n(""),i(!1))},placeholder:r,className:"h-4 w-full min-w-0 border-0 bg-transparent p-0 text-[12px] font-normal normal-case leading-none tracking-normal outline-none placeholder:text-muted-foreground/50"}),l.jsx("button",{type:"button","aria-label":c?"Clear filter":"Close filter",onClick:()=>{c&&n(""),i(!1)},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground focus:outline-none focus-visible:text-foreground",children:l.jsx(Ce.X,{className:"h-3 w-3"})})]})]})}function sxe(){const{authToken:e,tokenProps:t}=Tt(),n=t==null?void 0:t.apiServiceUrl,r=t==null?void 0:t.project_id,s=Kr();return Ao({mutationFn:async({dashboardId:o})=>{if(!n||!e)throw new Error("Missing authentication or API configuration");const i=await fetch(`${n}/management/v1/user-preferences`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e==null?void 0:e.accessToken}`},body:JSON.stringify({defaultDashboardId:o})});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||"Failed to update default dashboard")}return i.json()},onMutate:async({dashboardId:o})=>{await s.cancelQueries({queryKey:["user-preferences",r]});const i=s.getQueryData(["user-preferences",r]);return i&&s.setQueryData(["user-preferences",r],{...i,preference:i.preference?{...i.preference,defaultDashboardId:o}:null}),{previousPreferences:i}},onError:(o,i,a)=>{const c=a;c!=null&&c.previousPreferences&&s.setQueryData(["user-preferences",r],c.previousPreferences),it.error(o.message||"Failed to update default dashboard"),console.error("Error updating default dashboard:",o)},onSuccess:(o,i)=>{s.invalidateQueries({queryKey:["user-preferences",r]}),it.success(i.dashboardId?"Default dashboard set successfully":"Default dashboard cleared")}})}function N_t({dashboard:e,isDeleting:t,isDuplicating:n,shouldHideActions:r,showInlineEditButton:s=!0,showEditInMenu:o=!0,menuButtonClassName:i,isDefault:a,onEditDetails:c,onDeleteClick:u,onDuplicateDashboard:d,onShareDashboard:f,formatDate:h}){var j,_,k;const{isConsoleMode:p}=Vm(),{mutate:g,isPending:b}=sxe(),x=e.kind!=="data_app"&&!!d,y=e.kind!=="data_app"&&a!==void 0,[v,S]=w.useState(!1),[N,C]=w.useState(!1);return w.useEffect(()=>{n?(S(!0),C(!0)):N&&(S(!1),C(!1))},[n,N]),l.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",onClick:I=>I.stopPropagation(),children:[s&&e.permissions.canEdit&&!r&&l.jsx(m.Button,{size:"sm",variant:"ghost",className:"h-7 w-7 rounded-md p-0 text-muted-foreground hover:bg-muted/50 hover:text-foreground",onClick:I=>{I.stopPropagation(),c==null||c(e)},title:"Edit details","aria-label":"Edit dashboard details",children:l.jsx(YM,{className:"h-3 w-3"})}),!r&&l.jsxs(Ys,{modal:!1,open:v,onOpenChange:S,children:[l.jsx(Zs,{asChild:!0,children:l.jsx(m.Button,{size:"sm",variant:"ghost",className:m.cn("h-7 w-7 rounded-md p-0 text-muted-foreground hover:bg-muted/50 hover:text-foreground",i),"aria-label":"Open dashboard actions",children:l.jsx(ym,{className:"h-3 w-3"})})}),l.jsxs(Es,{align:"end",className:"z-[51] w-44 rounded-xl border border-border/60 p-1 shadow-sm",children:[y?l.jsxs(Nn,{onClick:I=>{I.preventDefault(),I.stopPropagation(),g({dashboardId:a?null:e.id})},disabled:b,children:[a?l.jsx(jY,{className:"mr-2 h-3 w-3"}):l.jsx(kY,{className:"mr-2 h-3 w-3"}),a?"Clear default":"Set as default"]}):null,x?l.jsxs(Nn,{onClick:I=>{I.preventDefault(),I.stopPropagation(),d==null||d(e.id)},disabled:n,children:[n?l.jsx(m.LoaderCircle,{className:"mr-2 h-3 w-3 animate-spin"}):l.jsx(_d,{className:"mr-2 h-3 w-3"}),n?"Duplicating...":"Duplicate"]}):null,e.permissions.canEdit&&o&&l.jsxs(Nn,{onClick:I=>{I.stopPropagation(),c==null||c(e)},children:[l.jsx(YM,{className:"mr-2 h-3 w-3"}),"Edit details"]}),e.permissions.canEdit&&f&&l.jsxs(Nn,{onClick:I=>{I.stopPropagation(),f(e)},children:[l.jsx(_k,{className:"mr-2 h-3 w-3"}),"Share"]}),l.jsxs(Nn,{onClick:I=>{var T;I.stopPropagation(),(T=navigator==null?void 0:navigator.clipboard)!=null&&T.writeText?navigator.clipboard.writeText(e.id).then(()=>it.success("Dashboard ID copied")).catch(()=>it.error("Unable to copy dashboard ID")):it.error("Clipboard not available")},children:[l.jsx(_d,{className:"mr-2 h-3 w-3"}),"Copy ID"]}),e.permissions.canDelete&&u&&l.jsxs(l.Fragment,{children:[l.jsx(Sa,{}),l.jsxs(Nn,{onClick:I=>{I.stopPropagation(),u(e)},className:"text-destructive",disabled:t,children:[l.jsx(va,{className:"mr-2 h-3 w-3"}),t?"Deleting...":"Delete"]})]}),l.jsx(Sa,{}),l.jsxs("div",{className:"space-y-1 px-2 py-2 text-xs text-muted-foreground",children:[(((j=e.ownership.createdBy)==null?void 0:j.type)==="tenant"||((_=e.ownership.createdBy)==null?void 0:_.type)==="organization"&&p)&&l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(fO,{className:"h-3 w-3"}),l.jsx("span",{children:((k=e.ownership.createdBy)==null?void 0:k.name)||"Unknown"})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Li,{className:"h-3 w-3"}),l.jsx("span",{children:h(e.lastModified)})]})]})]})]})]})}const oxe="grid-cols-[minmax(0,2.4fr)_minmax(0,1fr)_120px_140px_40px]";function j_t(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),s=Math.floor(r/(1e3*60*60)),o=Math.floor(r/(1e3*60*60*24)),i=Math.floor(o/7),a=Math.floor(o/30);return s<1?"just now":s<24?s===1?"1 hour ago":`${s} hours ago`:o<7?o===1?"1 day ago":`${o} days ago`:i<4?i===1?"1 week ago":`${i} weeks ago`:a<12?a===1?"1 month ago":`${a} months ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function k_t(e){if(!e)return"?";const t=e.trim().split(/\s+/);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[t.length-1][0]).toUpperCase()}function __t({dashboard:e}){var n;const t=((n=e.ownership)==null?void 0:n.sharedCount)??0;return e.isPublic?l.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-muted-foreground",children:[l.jsx(vm,{className:"h-3 w-3 text-muted-foreground/70"}),"Public"]}):t>0?l.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-muted-foreground",children:[l.jsx(_k,{className:"h-3 w-3 text-muted-foreground/70"}),"Shared",l.jsxs("span",{className:"tabular-nums text-muted-foreground/70",children:["· ",t]})]}):l.jsx("span",{className:"text-[13px] text-muted-foreground",children:"Private"})}function I_t({dashboard:e,isDefault:t,onView:n,isDeleting:r=!1,isDuplicating:s=!1,onEditDetails:o,onDeleteClick:i,onDuplicateDashboard:a,onShareDashboard:c,formatDate:u,style:d}){var x,y;const f=e.kind!=="data_app",h=!!i||!!a||!!c,p=((y=(x=e.ownership)==null?void 0:x.createdBy)==null?void 0:y.name)??"Unknown",g=k_t(p),b=e.title||"Untitled Dashboard";return l.jsxs("div",{onClick:()=>n(e.id),style:d,className:m.cn("group grid cursor-pointer items-center gap-4 border-b border-border/60 px-2 py-3 transition-colors hover:bg-muted/40 focus-within:bg-muted/40",oxe),children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.kind==="data_app"?l.jsx(wxe,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}):l.jsx(Hh,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),n(e.id)},title:b,className:"min-w-0 truncate text-left text-[13px] font-medium text-foreground hover:underline focus:outline-none focus-visible:underline",children:b}),f&&t&&l.jsx("span",{className:"shrink-0 rounded-[4px] border border-border/60 px-1.5 py-px text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",title:"Default dashboard",children:"Default"}),e.kind==="data_app"&&l.jsx("span",{className:"shrink-0 rounded-[4px] border border-border/60 px-1.5 py-px text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"App"})]}),l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-[9px] font-medium text-muted-foreground",children:g}),l.jsx("span",{className:"truncate text-[13px] text-muted-foreground",title:p,children:p})]}),l.jsx("div",{className:"text-[13px] text-muted-foreground",children:j_t(e.updatedAt)}),l.jsx("div",{children:l.jsx(__t,{dashboard:e})}),l.jsx("div",{className:"opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:h?l.jsx(N_t,{dashboard:e,isDeleting:r,isDuplicating:s,shouldHideActions:!1,showInlineEditButton:!1,showEditInMenu:!0,menuButtonClassName:"h-7 w-7 px-0",isDefault:f?t:void 0,onEditDetails:o,onDeleteClick:i,onDuplicateDashboard:a,onShareDashboard:c,formatDate:u}):null})]})}function T_t(e){const{onDashboardSelect:t}=e||{},n=Ro(o=>o.actions.selectDashboard),r=Ro(o=>o.actions.updateSelectedDashboard);return{onCreateSuccess:(o,i)=>{o&&(n(o),t==null||t(o.id),i().then(a=>{var d;const u=(((d=a.data)==null?void 0:d.dashboards)||[]).find(f=>f.id===o.id);if(u){const f=Ro.getState().selectedDashboard;(f==null?void 0:f.id)===u.id&&r(u)}}))}}}function ixe(){const{authToken:e,tokenProps:t}=Tt(),n=t==null?void 0:t.apiServiceUrl,r=t==null?void 0:t.project_id;return Gn({queryKey:["user-preferences",r],queryFn:async()=>{if(!n||!(e!=null&&e.accessToken))return{preference:null};try{return await m.getRequest(`${n}/management/v1/user-preferences`,e.accessToken)}catch(s){return console.error("Error fetching user preferences:",s),{preference:null}}},enabled:!!n&&!!(e!=null&&e.accessToken),staleTime:5*60*1e3,gcTime:10*60*1e3})}function E_t(e){return e||"none"}function D_t(e){if(!e||e.kind!=="semantic")return;const t=e.connectionId||"",n=E_t(e.connectionType),r=e.label||e.datasetName,s={id:e.datasetId||e.datasetName,type:"dataset",datasetType:"physical",domainId:e.domainId,label:r,description:e.description,connectionId:t,connectionType:n,database:e.database,schema:e.schema,name:e.datasetName};return{connectionId:t,connectionType:n,mode:"semanticDomain",semanticDomainId:e.domainId,selectedEntities:[s]}}function M_t(e){const t=D_t(e.dataset);if(!t)return;const n=`dashboard_${m.v4()}`,r=m.v4(),s=m.v4(),o=m.v4(),i={id:o,title:"Title",type:"bar",connectionId:t.connectionId,dataSource:t,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},sql:"",data:[]},a={id:s,cards:[i],activeCardId:o};return{id:n,title:e.title,description:e.description,aiContext:{selectedEntities:t.selectedEntities,mode:"fixed"},sheets:[{id:r,kind:"dashboard",title:"Sheet 1",frames:[a],layouts:bxe.createFrameLayouts({id:s,x:0,y:0,w:18,initialHeight:36,minH:10})}]}}function zM(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function A_t(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function R_t(e){const t={projectId:e.dataApp.projectId,dataAppId:e.dataApp.id,versionId:e.runtime.versionId,version:e.runtime.version,apiBaseUrl:e.apiBaseUrl.replace(/\/api\/?$/,""),dataApiBaseUrl:e.apiBaseUrl,assetsBaseUrl:e.runtime.assetsBaseUrl,manifest:e.runtime.manifest,authToken:e.runtime.authToken},n=e.runtime.styleUrls.map(r=>`<link rel="stylesheet" crossorigin="anonymous" href="${zM(r)}">`).join(`
1322
1322
  `);return`<!doctype html>
1323
1323
  <html lang="en">