react-semaphor 0.1.442 → 0.1.443
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-BjqymJeS.js → dashboard-Bd1Quco-.js} +4 -4
- package/dist/chunks/{dashboard-briefing-launcher-D5oHvdYf.js → dashboard-briefing-launcher-BYMLjZxG.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-B7LrrGSM.js → dashboard-briefing-launcher-C60n8LqW.js} +2 -2
- package/dist/chunks/{dashboard-BRj8nq8w.js → dashboard-cB3xmTNn.js} +2 -2
- package/dist/chunks/{dashboard-controls-DjyNG67M.js → dashboard-controls-BH_fZYDU.js} +1 -1
- package/dist/chunks/{dashboard-controls-CUd1yfGB.js → dashboard-controls-ti9Rcel2.js} +3 -3
- package/dist/chunks/{dashboard-json-C5_h_0OT.js → dashboard-json-Bturr634.js} +1 -1
- package/dist/chunks/{dashboard-json-CiMI9PO-.js → dashboard-json-Dw_55vSZ.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-EwylNae5.js → edit-dashboard-visual-BUc3NBQ4.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-BOkzUd4b.js → edit-dashboard-visual-DglMds57.js} +2 -2
- package/dist/chunks/{editor-action-buttons-Bz4ik8DY.js → editor-action-buttons-CRi0fhVW.js} +1 -1
- package/dist/chunks/{editor-action-buttons-C0EXI0VB.js → editor-action-buttons-Cxo7_tNG.js} +1 -1
- package/dist/chunks/{report-preferences-dialog-Cw4Ti1lc.js → report-preferences-dialog-CCvFqH4Q.js} +1 -1
- package/dist/chunks/{report-preferences-dialog-Ck94m-ik.js → report-preferences-dialog-TtwdAuNn.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/data-app-builder/index.cjs +1 -1
- package/dist/data-app-builder/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
|
@@ -789,7 +789,7 @@ ${D}`:D},color:k=>{if(f)return f;const I=k==null?void 0:k.raw,T=B8({raw:I,dimens
|
|
|
789
789
|
`}}),l.jsxs("div",{className:m.cn("semaphor-pagination-container px-4 py-2 text-[13px]",!k&&"text-muted-foreground"),style:y==null?void 0:y.containerStyle,children:[l.jsxs("div",{className:"semaphor-pagination-info hidden flex-1 items-center gap-2",children:[s>0&&l.jsxs(l.Fragment,{children:[s," of ",M," row(s) selected"," "]}),s===0&&l.jsxs(l.Fragment,{children:[M," rows"]}),s>0&&l.jsx(m.Button,{variant:"outline",size:"xs",style:j,onClick:f,className:"h-7 text-foreground",children:"Clear"})]}),p&&l.jsx(m.Button,{variant:"ghost",size:"xs",style:j,onClick:()=>S(!0),className:m.cn("semaphor-pagination-download h-7 w-7 p-0",!k&&"text-muted-foreground hover:text-foreground"),title:"Export",children:l.jsx(gu,{className:"h-3.5 w-3.5"})}),l.jsxs("div",{className:"semaphor-pagination-pagesize ml-2 hidden items-center gap-1.5",children:[l.jsx(m.Label,{htmlFor:"rows-per-page",style:_,className:m.cn("semaphor-pagination-pagesize-label text-[13px] font-normal",!k&&"text-muted-foreground"),children:"Rows"}),l.jsxs(m.Select,{value:`${T}`,onValueChange:D,children:[l.jsx(m.SelectTrigger,{style:j,className:`h-7 w-[72px] text-[12px] ${m.simpleRing}`,id:"rows-per-page",children:l.jsx(m.SelectValue,{placeholder:T})}),l.jsx(m.SelectContent,{side:"top",children:I.map(A=>l.jsx(m.SelectItem,{value:`${A}`,children:A},A))})]})]}),l.jsxs("div",{className:"semaphor-pagination-page-info flex w-fit items-center justify-center font-normal tabular-nums",children:["Page ",t+1," of ",e]}),l.jsxs("div",{className:"semaphor-pagination-nav-container ml-auto flex items-center gap-0.5 md:ml-0",children:[l.jsxs(m.Button,{style:j,variant:"ghost",size:"xs",className:"semaphor-pagination-nav-extended hidden h-7 w-7 p-0",onClick:()=>o(0),disabled:!a,children:[l.jsx("span",{className:"sr-only",children:"Go to first page"}),l.jsx(fY,{className:"h-3.5 w-3.5"})]}),l.jsxs(m.Button,{style:j,variant:"ghost",size:"xs",className:"h-7 w-7 p-0",onClick:u,disabled:!a,children:[l.jsx("span",{className:"sr-only",children:"Go to previous page"}),l.jsx(xm,{className:"h-3.5 w-3.5"})]}),l.jsxs(m.Button,{style:j,variant:"ghost",size:"xs",className:"h-7 w-7 p-0",onClick:d,disabled:!c,children:[l.jsx("span",{className:"sr-only",children:"Go to next page"}),l.jsx(Ot.ChevronRight,{className:"h-3.5 w-3.5"})]}),l.jsxs(m.Button,{style:j,variant:"ghost",size:"xs",className:"semaphor-pagination-nav-extended hidden h-7 w-7 p-0",onClick:()=>o(e-1),disabled:!c,children:[l.jsx("span",{className:"sr-only",children:"Go to last page"}),l.jsx(hY,{className:"h-3.5 w-3.5"})]})]})]}),p&&E&&g&&l.jsx(P_,{isOpen:v,onClose:()=>S(!1),frame:E,card:g,data:x})]})}const XL=tw,W5e=l_,G5e=nw,Yne=te.forwardRef(({className:e,...t},n)=>l.jsx(Tm,{className:m.cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Yne.displayName=Tm.displayName;const K5e=m.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),q_=te.forwardRef(({side:e="right",className:t,children:n,hideOverlay:r=!1,hideClose:s=!1,...o},i)=>l.jsxs(G5e,{children:[!r&&l.jsx(m.PortalScope,{children:l.jsx(Yne,{})}),l.jsx(m.PortalScope,{children:l.jsxs(Em,{ref:i,className:m.cn(K5e({side:e}),t),...o,children:[n,!s&&l.jsxs(rw,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[l.jsx(Ce.X,{className:"h-4 w-4"}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})})]}));q_.displayName=Em.displayName;const Zne=({className:e,...t})=>l.jsx("div",{className:m.cn("flex flex-col space-y-2 text-center sm:text-left",e),...t});Zne.displayName="SheetHeader";const W_=te.forwardRef(({className:e,...t},n)=>l.jsx(cb,{ref:n,className:m.cn("text-lg font-semibold text-foreground",e),...t}));W_.displayName=cb.displayName;const G_=te.forwardRef(({className:e,...t},n)=>l.jsx(ub,{ref:n,className:m.cn("text-sm text-muted-foreground",e),...t}));G_.displayName=ub.displayName;const Xne=[{label:"Date Only",formats:[{label:"MM/DD/YYYY",value:"MM/dd/yyyy"},{label:"DD/MM/YYYY",value:"dd/MM/yyyy"},{label:"YYYY-MM-DD",value:"yyyy-MM-dd"},{label:"Month DD, YYYY",value:"LLLL dd, yyyy"},{label:"DD Month YYYY",value:"dd LLLL yyyy"},{label:"MM-DD-YYYY",value:"MM-dd-yyyy"},{label:"YYYY/MM/DD",value:"yyyy/MM/dd"},{label:"DD.MM.YYYY",value:"dd.MM.yyyy"},{label:"DD Month YY",value:"dd LLL yy"}]},{label:"Date & Time",formats:[{label:"MM/DD/YYYY HH:mm",value:"MM/dd/yyyy HH:mm"},{label:"DD/MM/YYYY HH:mm",value:"dd/MM/yyyy HH:mm"},{label:"YYYY-MM-DD HH:mm:ss",value:"yyyy-MM-dd HH:mm:ss"},{label:"Month DD, YYYY at HH:mm",value:"LLLL dd, yyyy 'at' HH:mm"},{label:"DD Month YYYY HH:mm",value:"dd LLLL yyyy HH:mm"},{label:"MM/DD/YYYY h:mm a",value:"MM/dd/yyyy h:mm a"},{label:"Month DD, YYYY h:mm a",value:"LLLL dd, yyyy h:mm a"}]},{label:"Date & Time with Timezone",formats:[{label:"MM/DD/YYYY HH:mm z",value:"MM/dd/yyyy HH:mm zzz"},{label:"YYYY-MM-DD HH:mm:ss z",value:"yyyy-MM-dd HH:mm:ss zzz"},{label:"Month DD, YYYY at HH:mm z",value:"LLLL dd, yyyy 'at' HH:mm zzz"},{label:"MM/DD/YYYY h:mm a z",value:"MM/dd/yyyy h:mm a zzz"}]},{label:"ISO Standards",formats:[{label:"ISO 8601",value:"yyyy-MM-dd'T'HH:mm:ss"},{label:"ISO 8601 with TZ",value:"yyyy-MM-dd'T'HH:mm:ssXXX"}]}];[...Xne.flatMap(e=>e.formats)];const s9=[{label:"Auto (Use dashboard/browser timezone)",value:"auto"},{label:"UTC",value:"UTC"},{label:"Eastern Time (US)",value:"America/New_York"},{label:"Central Time (US)",value:"America/Chicago"},{label:"Mountain Time (US)",value:"America/Denver"},{label:"Pacific Time (US)",value:"America/Los_Angeles"},{label:"São Paulo",value:"America/Sao_Paulo"},{label:"Buenos Aires",value:"America/Argentina/Buenos_Aires"},{label:"London",value:"Europe/London"},{label:"Paris/Berlin",value:"Europe/Paris"},{label:"Moscow",value:"Europe/Moscow"},{label:"Dubai",value:"Asia/Dubai"},{label:"Mumbai",value:"Asia/Kolkata"},{label:"Singapore",value:"Asia/Singapore"},{label:"Hong Kong",value:"Asia/Hong_Kong"},{label:"Shanghai/Beijing",value:"Asia/Shanghai"},{label:"Tokyo",value:"Asia/Tokyo"},{label:"Seoul",value:"Asia/Seoul"},{label:"Sydney",value:"Australia/Sydney"},{label:"Auckland",value:"Pacific/Auckland"}];function Y5e(){return m.useDashboardStore(e=>{var t;return((t=e.reportContext)==null?void 0:t.calendar)??null})}function al(){return m.useDashboardStore(e=>{var t;return((t=e.reportContext)==null?void 0:t.calendar.tz)??null})}function Z5e(){return m.useDashboardStore(e=>{var t;return((t=e.reportContext)==null?void 0:t.valueFormat)??null})}const rp="__report_default__",X5e=[{value:"absolute",label:"Absolute"},{value:"relative",label:"Relative"}];function ws({label:e,htmlFor:t,children:n,align:r="center"}){return l.jsxs("div",{className:`flex gap-2.5 ${r==="start"?"items-start":"items-center"}`,children:[l.jsx("label",{htmlFor:t,className:`w-[88px] shrink-0 text-[12px] text-muted-foreground ${r==="start"?"pt-1.5":""}`,children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function Q5e({children:e}){return l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})}function bx({label:e}){return l.jsx("div",{className:"flex items-center gap-2 pt-1",children:l.jsx(Q5e,{children:e})})}function o9({children:e}){return l.jsx("div",{className:"rounded-[6px] border border-border/60 bg-muted/40 px-3 py-2",children:l.jsx("div",{className:"text-[12px] text-muted-foreground",children:e})})}function QL({column:e,settings:t,onSettingsChange:n,baseStyle:r={},onBaseStyleChange:s,onApply:o,onReset:i,onResetAll:a,open:c,onOpenChange:u,availableColumns:d=[],tableType:f="data",isSqlCard:h=!1}){var $,V,U,R,q,W,F,Z,K,Y,X,z,B;const p=f==="data",g=al(),{preferences:b}=ka(),x=Intl.DateTimeFormat().resolvedOptions().timeZone,y=h?x:g||x,v=()=>t.dateFormat.timezone&&t.dateFormat.timezone!=="auto"?t.dateFormat.timezone:y,S=h?t.dateFormat.sourceTimezone||"auto":g||"UTC",N=H=>{n({...t,inheritMetricFormat:!1,numberFormat:{...t.numberFormat,...H}})},C=(e==null?void 0:e.id)??"",[j,_]=w.useState(()=>{var H;return((H=t.width)==null?void 0:H.toString())??""}),k=m.fromColumnNumberFormat(t.numberFormat,{preserveOmittedProperties:!0}),I=b&&k&&k.type!=="date"&&k.type!=="duration"&&k.type!=="string"?In.resolveNumericPresentation(k,b):k,T=m.toColumnNumberFormat(I,{preserveOmittedProperties:!0}),E=t.numberFormat.minimumFractionDigits??(T==null?void 0:T.minimumFractionDigits)??0,D=t.numberFormat.maximumFractionDigits??(T==null?void 0:T.maximumFractionDigits)??2,M=b==null?void 0:b.defaultCurrency,A=b==null?void 0:b.locale;w.useEffect(()=>{var H;_(((H=t.width)==null?void 0:H.toString())??"")},[t.width,C,c]);const P=(H,L)=>{s==null||s({...r,[H]:L})},O=H=>{const L=Number(H);!Number.isFinite(L)||H.trim()===""||n({...t,width:L})};return l.jsx(XL,{open:c,onOpenChange:u,modal:!1,children:l.jsxs(q_,{side:"right",hideOverlay:!0,className:"p-0 shadow-2xl sm:max-w-[480px]",children:[l.jsxs(W_,{className:"sr-only",children:["Display Settings For ",(e==null?void 0:e.id)??"Column"]}),l.jsx(G_,{className:"sr-only",children:"Configure table column display and base formatting."}),l.jsxs("div",{className:"flex h-full flex-col",children:[l.jsx("div",{className:"flex h-11 shrink-0 items-center border-b border-border pl-4 pr-10",children:l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("span",{className:"text-[13px] font-medium",children:(e==null?void 0:e.id)??"Column"}),l.jsx("span",{className:"ml-2 text-[12px] text-muted-foreground",children:"Display settings"})]})}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:l.jsxs("div",{className:"space-y-4 px-4 py-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(bx,{label:"General"}),l.jsx(ws,{label:"Type",htmlFor:"column-type",children:l.jsxs(m.Select,{value:t.type,onValueChange:H=>{const L={...t,type:H};n(L)},children:[l.jsx(m.SelectTrigger,{size:"xs",id:"column-type",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select type"})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"none",children:"None"}),l.jsx(m.SelectItem,{value:"text",children:"Text"}),l.jsx(m.SelectItem,{value:"number",children:"Number"}),l.jsx(m.SelectItem,{value:"date",children:"Date"}),l.jsx(m.SelectItem,{value:"badge",children:"Badge"}),p&&l.jsx(m.SelectItem,{value:"link",children:"Link"}),l.jsx(m.SelectItem,{value:"progress",children:"Progress"})]})]})}),l.jsx(ws,{label:"Align",htmlFor:"text-align",children:l.jsxs(m.Select,{value:t.textAlign,onValueChange:H=>n({...t,textAlign:H}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"text-align",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select alignment"})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"left",children:"Left"}),l.jsx(m.SelectItem,{value:"center",children:"Center"}),l.jsx(m.SelectItem,{value:"right",children:"Right"})]})]})}),l.jsx(ws,{label:"Text display",htmlFor:"text-wrap",children:l.jsxs(m.Select,{value:t.textWrap==="nowrap"?"default":t.textWrap,onValueChange:H=>n({...t,textWrap:H}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"text-wrap",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select text wrapping"})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"default",children:"Use table default"}),l.jsx(m.SelectItem,{value:"truncate",children:"Truncate"}),l.jsx(m.SelectItem,{value:"wrap",children:"Wrap"}),l.jsx(m.SelectItem,{value:"preserve",children:"Preserve whitespace"})]})]})}),l.jsx(ws,{label:"Width (px)",htmlFor:"column-width",children:l.jsx(m.Input,{size:"xs",id:"column-width",type:"number",value:j,onChange:H=>{const L=H.target.value;_(L),O(L)},onBlur:()=>{var H;j.trim()===""&&_(((H=t.width)==null?void 0:H.toString())??"")},className:`w-full ${m.removeRing}`,placeholder:"150"})})]}),t.type==="number"&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(bx,{label:"Number format"}),l.jsxs("label",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Tn,{checked:t.inheritMetricFormat!==!1,onCheckedChange:H=>n({...t,inheritMetricFormat:H===!0})}),"Use metric format"]})]}),l.jsx(ws,{label:"Style",htmlFor:"number-style",children:l.jsxs(m.Select,{value:t.numberFormat.style,onValueChange:H=>N({style:H}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"number-style",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select number style"})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"decimal",children:"Decimal"}),l.jsx(m.SelectItem,{value:"currency",children:"Currency"}),l.jsx(m.SelectItem,{value:"percent",children:"Percentage"}),l.jsx(m.SelectItem,{value:"scientific",children:"Scientific"})]})]})}),t.numberFormat.style==="currency"&&l.jsx(ws,{label:"Currency",htmlFor:"currency",children:l.jsxs(m.Select,{value:t.numberFormat.currency??rp,onValueChange:H=>N({currency:H===rp?void 0:H}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"currency",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select currency"})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:rp,children:["Report default",M?` — ${M}`:""]}),l.jsx(m.SelectItem,{value:"USD",children:"USD ($)"}),l.jsx(m.SelectItem,{value:"EUR",children:"EUR (€)"}),l.jsx(m.SelectItem,{value:"GBP",children:"GBP (£)"}),l.jsx(m.SelectItem,{value:"JPY",children:"JPY (¥)"}),l.jsx(m.SelectItem,{value:"CAD",children:"CAD (C$)"}),l.jsx(m.SelectItem,{value:"AUD",children:"AUD (A$)"}),l.jsx(m.SelectItem,{value:"CNY",children:"CNY (¥)"}),l.jsx(m.SelectItem,{value:"INR",children:"INR (₹)"})]})]})}),l.jsx(ws,{label:"Locale",htmlFor:"locale",children:l.jsxs(m.Select,{value:t.numberFormat.locale??rp,onValueChange:H=>N({locale:H===rp?void 0:H}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"locale",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select locale"})}),l.jsxs(m.SelectContent,{children:[l.jsxs(m.SelectItem,{value:rp,children:["Report default",A?` — ${A}`:""]}),l.jsx(m.SelectItem,{value:"en-US",children:"English (US)"}),l.jsx(m.SelectItem,{value:"en-GB",children:"English (UK)"}),l.jsx(m.SelectItem,{value:"fr-FR",children:"French"}),l.jsx(m.SelectItem,{value:"de-DE",children:"German"}),l.jsx(m.SelectItem,{value:"es-ES",children:"Spanish"}),l.jsx(m.SelectItem,{value:"ja-JP",children:"Japanese"}),l.jsx(m.SelectItem,{value:"zh-CN",children:"Chinese (Simplified)"})]})]})}),l.jsx(ws,{label:"Decimals",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Min"}),l.jsxs(m.Select,{value:E.toString(),onValueChange:H=>N({minimumFractionDigits:Number.parseInt(H)}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"min-decimals","aria-label":"Minimum decimals",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:[0,1,2,3,4].map(H=>l.jsx(m.SelectItem,{value:H.toString(),children:H},H))})]})]}),l.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Max"}),l.jsxs(m.Select,{value:D.toString(),onValueChange:H=>N({maximumFractionDigits:Number.parseInt(H)}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"max-decimals","aria-label":"Maximum decimals",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:[0,1,2,3,4,5,6].map(H=>l.jsx(m.SelectItem,{value:H.toString(),children:H},H))})]})]})]})})]})]}),t.type==="date"&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(bx,{label:"Date format"}),h?l.jsxs(l.Fragment,{children:[l.jsx(ws,{label:"Format type",htmlFor:"date-format-type",children:l.jsxs(m.Select,{value:t.dateFormat.useRelativeTime?"relative":"absolute",onValueChange:H=>n({...t,dateFormat:{...t.dateFormat,useRelativeTime:H==="relative"}}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"date-format-type",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select format type"})}),l.jsx(m.SelectContent,{children:X5e.map(H=>l.jsx(m.SelectItem,{value:H.value,children:H.label},H.value))})]})}),!t.dateFormat.useRelativeTime&&l.jsxs(l.Fragment,{children:[l.jsx(ws,{label:"Date format",htmlFor:"date-format",children:l.jsxs(m.Select,{value:t.dateFormat.useCustomFormat?"custom":t.dateFormat.format||"MM/dd/yyyy",onValueChange:H=>{n(H==="custom"?{...t,dateFormat:{...t.dateFormat,useCustomFormat:!0}}:{...t,dateFormat:{...t.dateFormat,format:H,useCustomFormat:!1}})},children:[l.jsx(m.SelectTrigger,{size:"xs",id:"date-format",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select date format"})}),l.jsxs(m.SelectContent,{children:[Xne.map(H=>l.jsxs(m.SelectGroup,{children:[l.jsx(m.SelectLabel,{className:"bg-muted",children:H.label}),H.formats.map(L=>l.jsx(m.SelectItem,{value:L.value,children:L.label},L.value))]},H.label)),l.jsx(m.SelectItem,{value:"custom",children:"Custom"})]})]})}),t.dateFormat.useCustomFormat&&l.jsx(ws,{label:"Custom format",htmlFor:"custom-format",align:"start",children:l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Input,{size:"xs",id:"custom-format",className:`w-full ${m.removeRing}`,value:t.dateFormat.customFormat,onChange:H=>n({...t,dateFormat:{...t.dateFormat,customFormat:H.target.value}}),placeholder:"yyyy-MM-dd'T'HH:mm:ss"}),l.jsx("div",{className:"text-[11px] text-muted-foreground",children:l.jsx("p",{children:"Tokens: yyyy yy · MMMM MMM MM · dd d · HH H · mm ss"})})]})})]}),t.dateFormat.useRelativeTime&&l.jsx(o9,{children:'Displays as relative time: "just now", "5 minutes ago", "3 days ago", etc.'}),l.jsx(ws,{label:"Display TZ",htmlFor:"timezone",children:l.jsxs(m.Select,{value:v(),onValueChange:H=>n({...t,dateFormat:{...t.dateFormat,timezone:H}}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"timezone",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select timezone"})}),l.jsx(m.SelectContent,{children:s9.filter(H=>H.value!=="auto").map(H=>l.jsx(m.SelectItem,{value:H.value,children:H.label},H.value))})]})}),h&&l.jsx(ws,{label:"Source TZ",htmlFor:"source-timezone",align:"start",children:l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs(m.Select,{value:t.dateFormat.sourceTimezone||"auto",onValueChange:H=>n({...t,dateFormat:{...t.dateFormat,sourceTimezone:H}}),children:[l.jsx(m.SelectTrigger,{size:"xs",id:"source-timezone",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select source timezone"})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"auto",children:"Auto (UTC if not specified)"}),l.jsx(m.SelectItem,{value:"UTC",children:"Always UTC"}),l.jsx(m.SelectItem,{value:"local",children:"Browser Local Time"}),s9.filter(H=>H.value!=="auto").slice(1).map(H=>l.jsx(m.SelectItem,{value:H.value,children:H.label},H.value))]})]}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:'How to interpret dates without timezone info. "Auto" assumes UTC.'})]})}),l.jsxs("div",{className:"rounded-[6px] border border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-0.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsx("p",{className:"text-[13px] font-medium",children:t.dateFormat.useRelativeTime?ur.formatRelativeTime("2023-05-15T14:30:45Z"):ur.formatDate("2023-05-15T14:30:45Z",t.dateFormat.useCustomFormat?t.dateFormat.customFormat:t.dateFormat.format,v(),S)}),l.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Timezone: ",v()]})]})]}):l.jsx(o9,{children:"Date formatting is configured in the card's field settings. The data is returned pre-formatted from the query."})]})]}),t.type==="link"&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(bx,{label:"Link format"}),l.jsx(ws,{label:"URL template",htmlFor:"url-template",align:"start",children:l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Input,{size:"xs",id:"url-template",value:(($=t.linkFormat)==null?void 0:$.urlTemplate)||Cl().urlTemplate,onChange:H=>n({...t,linkFormat:{...t.linkFormat||Cl(),urlTemplate:H.target.value}}),className:`w-full ${m.removeRing}`,placeholder:"/users/{value}/details"}),l.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Use"," ",l.jsx("code",{className:"rounded-[4px] bg-muted px-1 font-mono",children:"{value}"})," ","for this column, or"," ",l.jsx("code",{className:"rounded-[4px] bg-muted px-1 font-mono",children:"{column_name}"})," ","for other columns."]})]})}),l.jsx(m.Separator,{className:"my-1"}),l.jsxs(ws,{label:"Display label",align:"start",children:[l.jsxs(Ja,{value:((V=t.linkFormat)==null?void 0:V.labelType)||Cl().labelType,onValueChange:H=>n({...t,linkFormat:{...t.linkFormat||Cl(),labelType:H}}),className:"flex flex-col gap-1.5",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Us,{value:"value",id:"label-value"}),l.jsx(m.Label,{htmlFor:"label-value",className:"text-[13px] font-normal",children:"Cell value"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Us,{value:"static",id:"label-static"}),l.jsx(m.Label,{htmlFor:"label-static",className:"text-[13px] font-normal",children:"Static text"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Us,{value:"column",id:"label-column"}),l.jsx(m.Label,{htmlFor:"label-column",className:"text-[13px] font-normal",children:"Another column"})]})]}),((U=t.linkFormat)==null?void 0:U.labelType)==="static"&&l.jsx("div",{className:"mt-1.5",children:l.jsx(m.Input,{size:"xs",id:"static-label",value:((R=t.linkFormat)==null?void 0:R.staticLabel)||"",onChange:H=>n({...t,linkFormat:{...t.linkFormat||Cl(),staticLabel:H.target.value}}),className:`w-full ${m.removeRing}`,placeholder:"View Details"})}),((q=t.linkFormat)==null?void 0:q.labelType)==="column"&&l.jsx("div",{className:"mt-1.5",children:l.jsxs(m.Select,{value:((W=t.linkFormat)==null?void 0:W.labelColumn)||"",onValueChange:H=>n({...t,linkFormat:{...t.linkFormat||Cl(),labelColumn:H}}),children:[l.jsx(m.SelectTrigger,{size:"xs",className:`w-full ${m.simpleRing}`,children:l.jsx(m.SelectValue,{placeholder:"Select a column"})}),l.jsx(m.SelectContent,{children:d.filter(H=>H!==(e==null?void 0:e.id)).map(H=>l.jsx(m.SelectItem,{value:H,children:H},H))})]})})]}),l.jsx(m.Separator,{className:"my-1"}),l.jsx(ws,{label:"Target",htmlFor:"open-new-tab",children:l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Tn,{id:"open-new-tab",checked:((F=t.linkFormat)==null?void 0:F.openInNewTab)??Cl().openInNewTab,onCheckedChange:H=>n({...t,linkFormat:{...t.linkFormat||Cl(),openInNewTab:!!H}})}),"Open in new tab"]})}),l.jsxs("div",{className:"rounded-[6px] border border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsxs("div",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx("a",{href:"#",className:"font-medium text-blue-600 hover:underline",onClick:H=>H.preventDefault(),children:((Z=t.linkFormat)==null?void 0:Z.labelType)==="static"?((K=t.linkFormat)==null?void 0:K.staticLabel)||"View Details":((Y=t.linkFormat)==null?void 0:Y.labelType)==="column"?`[${((X=t.linkFormat)==null?void 0:X.labelColumn)||"column"}]`:"123"}),l.jsx("span",{className:"text-muted-foreground",children:"→"}),l.jsx("code",{className:"rounded-[4px] bg-background px-1.5 py-0.5 text-[11px]",children:(((z=t.linkFormat)==null?void 0:z.urlTemplate)||"{value}").replace(/{value}/g,"123").replace(/{(\w+)}/g,"[$1]")})]}),l.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:((B=t.linkFormat)==null?void 0:B.openInNewTab)!==!1?"Opens in new tab":"Opens in same window"})]})]})]}),s&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(bx,{label:"Base styling"}),l.jsx(ws,{label:"Style",children:l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsxs("label",{className:"flex items-center gap-1.5 text-[13px]",children:[l.jsx(Tn,{checked:r.fontWeight==="bold",onCheckedChange:H=>P("fontWeight",H===!0?"bold":void 0)}),"Bold"]}),l.jsxs("label",{className:"flex items-center gap-1.5 text-[13px]",children:[l.jsx(Tn,{checked:r.italic===!0,onCheckedChange:H=>P("italic",H===!0?!0:void 0)}),"Italic"]})]})}),l.jsx(ws,{label:"Text Color",htmlFor:"base-text-color",children:l.jsx(m.Input,{size:"xs",id:"base-text-color",value:r.textColor??"",onChange:H=>P("textColor",H.target.value.trim()||void 0),className:`w-full ${m.removeRing}`,placeholder:"#111827"})}),l.jsx(ws,{label:"Fill Color",htmlFor:"base-background-color",children:l.jsx(m.Input,{size:"xs",id:"base-background-color",value:r.backgroundColor??"",onChange:H=>P("backgroundColor",H.target.value.trim()||void 0),className:`w-full ${m.removeRing}`,placeholder:"#f9fafb"})})]})]})]})}),l.jsxs("div",{className:"flex h-11 shrink-0 items-center justify-end gap-1 border-t border-border px-4",children:[l.jsx(m.Button,{variant:"ghost",size:"xs",onClick:a,children:"Reset all"}),l.jsx(m.Button,{variant:"ghost",size:"xs",onClick:i,children:"Reset column"}),o&&l.jsxs(l.Fragment,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:()=>u(!1),children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:o,children:"Apply"})]})]})]})]})})}function Kf({header:e,isResizing:t=!1,inset:n=!1}){const{column:r}=e,s=e.getResizeHandler();return r.getCanResize()?l.jsx("div",{onMouseDown:o=>{o.stopPropagation(),s(o)},onTouchStart:o=>{o.stopPropagation(),s(o)},onDragStartCapture:o=>{o.preventDefault(),o.stopPropagation()},onDoubleClick:()=>r.resetSize(),className:m.cn("group absolute bottom-0 top-0 z-10 flex w-2 cursor-col-resize touch-none select-none items-stretch justify-center",n?"right-0":"-right-1"),"data-resize-handle":"",style:{userSelect:"none",touchAction:"none"},title:"Drag to resize column. Double-click to auto-fit.",children:l.jsx("div",{className:m.cn("w-px transition-all",t?"w-0.5 bg-zinc-900 dark:bg-zinc-50":"bg-zinc-300 group-hover:w-0.5 group-hover:bg-zinc-600 dark:bg-zinc-700 dark:group-hover:bg-zinc-400")})}):null}function J5e(e){var n,r,s;const t={};return(n=e==null?void 0:e.metricColumns)==null||n.forEach(o=>{const i=o.alias??o.name??o.label;t[i]={dataType:o.dataType,isMetric:!0}}),(r=e==null?void 0:e.groupByColumns)==null||r.forEach(o=>{const i=o.alias??o.name??o.label;t[i]={dataType:o.dataType,isMetric:!1}}),(s=e==null?void 0:e.detailColumns)==null||s.forEach(o=>{const i=o.alias??o.name??o.label;t[i]={dataType:o.dataType,isMetric:!1}}),t}function eLe(e,t,n){var a,c,u;if((a=n==null?void 0:n[e])!=null&&a.metricId)return"number";if((c=n==null?void 0:n[e])!=null&&c.dataType){const d=m.getDataType(n[e].dataType);return d==="number"?"number":d==="date"?"date":"text"}const r=Math.min(10,t.length);let s=0,o=0,i=0;for(let d=0;d<t.length&&s<r;d++){const f=(u=t[d])==null?void 0:u[e];f!=null&&f!==""&&(s++,typeof f=="number"&&!isNaN(f)?o++:typeof f=="string"&&tLe(f)&&i++)}return o>s*.7?"number":i>s*.7?"date":"text"}function tLe(e){if(![/^\d{4}-\d{2}-\d{2}/,/^\d{2}\/\d{2}\/\d{4}/,/^\d{4}\/\d{2}\/\d{2}/,/^\d{2}-\d{2}-\d{4}/].some(s=>s.test(e)))return!1;const r=Date.parse(e);return!isNaN(r)}function A0(e,t,n,r){const s=ks(),i={...r?J5e(r):{},...n};switch(eLe(e,t,i)){case"number":return{...s,type:"number",textAlign:"right",numberFormat:{...s.numberFormat,style:"decimal",minimumFractionDigits:0,maximumFractionDigits:2}};case"date":return{...s,type:"date",textAlign:"left",dateFormat:{...s.dateFormat,format:"MMM dd, yyyy"}};default:return{...s,type:"text",textAlign:"left"}}}const Qne=m.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}}),$s=te.forwardRef(({className:e,variant:t,...n},r)=>l.jsx("div",{ref:r,className:m.cn(Qne({variant:t}),e),...n}));$s.displayName="Badge";var oD,K_="HoverCard",[Jne]=m.createContextScope(K_,[m.createPopperScope]),Y_=m.createPopperScope(),[nLe,Z_]=Jne(K_),ere=e=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:s,onOpenChange:o,openDelay:i=700,closeDelay:a=300}=e,c=Y_(t),u=te.useRef(0),d=te.useRef(0),f=te.useRef(!1),h=te.useRef(!1),[p,g]=m.useControllableState({prop:r,defaultProp:s??!1,onChange:o,caller:K_}),b=te.useCallback(()=>{clearTimeout(d.current),u.current=window.setTimeout(()=>g(!0),i)},[i,g]),x=te.useCallback(()=>{clearTimeout(u.current),!f.current&&!h.current&&(d.current=window.setTimeout(()=>g(!1),a))},[a,g]),y=te.useCallback(()=>g(!1),[g]);return te.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(d.current)},[]),l.jsx(nLe,{scope:t,open:p,onOpenChange:g,onOpen:b,onClose:x,onDismiss:y,hasSelectionRef:f,isPointerDownOnContentRef:h,children:l.jsx(m.Root2,{...c,children:n})})};ere.displayName=K_;var tre="HoverCardTrigger",nre=te.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=Z_(tre,n),o=Y_(n);return l.jsx(m.Anchor,{asChild:!0,...o,children:l.jsx(m.Primitive.a,{"data-state":s.open?"open":"closed",...r,ref:t,onPointerEnter:m.composeEventHandlers(e.onPointerEnter,QN(s.onOpen)),onPointerLeave:m.composeEventHandlers(e.onPointerLeave,QN(s.onClose)),onFocus:m.composeEventHandlers(e.onFocus,s.onOpen),onBlur:m.composeEventHandlers(e.onBlur,s.onClose),onTouchStart:m.composeEventHandlers(e.onTouchStart,i=>i.preventDefault())})})});nre.displayName=tre;var JL="HoverCardPortal",[rLe,sLe]=Jne(JL,{forceMount:void 0}),rre=e=>{const{__scopeHoverCard:t,forceMount:n,children:r,container:s}=e,o=Z_(JL,t);return l.jsx(rLe,{scope:t,forceMount:n,children:l.jsx(m.Presence,{present:n||o.open,children:l.jsx(m.Portal,{asChild:!0,container:s,children:r})})})};rre.displayName=JL;var XN="HoverCardContent",sre=te.forwardRef((e,t)=>{const n=sLe(XN,e.__scopeHoverCard),{forceMount:r=n.forceMount,...s}=e,o=Z_(XN,e.__scopeHoverCard);return l.jsx(m.Presence,{present:r||o.open,children:l.jsx(oLe,{"data-state":o.open?"open":"closed",...s,onPointerEnter:m.composeEventHandlers(e.onPointerEnter,QN(o.onOpen)),onPointerLeave:m.composeEventHandlers(e.onPointerLeave,QN(o.onClose)),ref:t})})});sre.displayName=XN;var oLe=te.forwardRef((e,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,...a}=e,c=Z_(XN,n),u=Y_(n),d=te.useRef(null),f=m.useComposedRefs(t,d),[h,p]=te.useState(!1);return te.useEffect(()=>{if(h){const g=document.body;return oD=g.style.userSelect||g.style.webkitUserSelect,g.style.userSelect="none",g.style.webkitUserSelect="none",()=>{g.style.userSelect=oD,g.style.webkitUserSelect=oD}}},[h]),te.useEffect(()=>{if(d.current){const g=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var x;((x=document.getSelection())==null?void 0:x.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",g),()=>{document.removeEventListener("pointerup",g),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),te.useEffect(()=>{d.current&&lLe(d.current).forEach(b=>b.setAttribute("tabindex","-1"))}),l.jsx(m.DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:i,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:m.composeEventHandlers(o,g=>{g.preventDefault()}),onDismiss:c.onDismiss,children:l.jsx(m.Content,{...u,...a,onPointerDown:m.composeEventHandlers(a.onPointerDown,g=>{g.currentTarget.contains(g.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:f,style:{...a.style,userSelect:h?"text":void 0,WebkitUserSelect:h?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),iLe="HoverCardArrow",aLe=te.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=Y_(n);return l.jsx(m.Arrow,{...s,...r,ref:t})});aLe.displayName=iLe;function QN(e){return t=>t.pointerType==="touch"?void 0:e()}function lLe(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var cLe=ere,uLe=nre,dLe=rre,ore=sre;const yb=cLe,vb=uLe,zd=te.forwardRef(({className:e,align:t="center",sideOffset:n=4,forceMount:r,...s},o)=>l.jsx(dLe,{forceMount:r,children:l.jsx(m.PortalScope,{children:l.jsx(ore,{ref:o,align:t,sideOffset:n,forceMount:r,className:m.cn("z-50 w-64 rounded-md border bg-popover p-4 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 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})})}));zd.displayName=ore.displayName;function e3({primaryValue:e,secondaryValue:t,presentation:n={},metricFormatOptions:r,locale:s,decimalPlaces:o=0,suffix:i,polarity:a=Ya.DEFAULT_METRIC_COMPARISON_POLARITY,signedValueFormatter:c,allowSignedValueFormatter:u=!0}){var P,O,$;const{displayMode:d="difference",indicatorStyle:f="arrow_badge",showColor:h=!0,conditionalLabel:p=!1,labelName:g,conditionalLabels:b,colors:x}=n,y=f==="arrow_badge"||f==="arrow",v=f==="arrow_badge"||f==="badge",S=m.normalizeMetricComparisonPrecision(n.precision??o),N=m.fromTFormatOptions(r)??{type:"number",locale:s,minimumFractionDigits:o,maximumFractionDigits:o,suffix:i},C=Ya.evaluateMetricComparison({currentValue:e,comparisonValue:t,polarity:a}),j=ur.formatMetricComparison(C,{displayMode:d,metricFormat:N,locale:s,precision:S}),_=(V,U)=>V?U!==null&&U>0?`+${V}`:V:"—",k=()=>{var V;return u&&c&&C.delta!==null?c(C.delta):_(((V=j.difference)==null?void 0:V.text)??null,C.delta)},I=V=>V.startsWith("(")&&V.endsWith(")")?V:`(${V})`,T=d==="difference"?k():d==="percent_change"?_(((P=j.percentChange)==null?void 0:P.text)??null,C.percentChange):d==="both"?`${_(((O=j.percentChange)==null?void 0:O.text)??null,C.percentChange)} ${I(k())}`:(($=j.ratio)==null?void 0:$.text)??"—";let E="",D={};if(h){const V=(R,q)=>R?R==="green"?"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-400":R==="red"?"bg-red-50 text-red-600 dark:bg-red-950 dark:text-red-400":R==="neutral"?"bg-gray-50 text-gray-700 dark:bg-gray-900 dark:text-gray-400":R.startsWith("#")?(D={color:R},"bg-muted/50"):q:q,U=C.sentiment==="favorable"?"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-400":C.sentiment==="unfavorable"?"bg-red-50 text-red-600 dark:bg-red-950 dark:text-red-400":"bg-gray-50 text-gray-700 dark:bg-gray-900 dark:text-gray-400";C.direction==="increase"?E=V(x==null?void 0:x.increase,U):C.direction==="decrease"?E=V(x==null?void 0:x.decrease,U):E=V(x==null?void 0:x.neutral,"bg-gray-50 text-gray-700 dark:bg-gray-900 dark:text-gray-400")}else E=v?"bg-gray-50 text-gray-700 dark:bg-gray-900 dark:text-gray-400":"bg-transparent text-muted-foreground";let M=null;return y&&(C.direction==="increase"?M=No:C.direction==="decrease"?M=ro:M=Lv),p&&(C.direction==="increase"?b!=null&&b.increase:C.direction==="decrease"?b!=null&&b.decrease:b!=null&&b.neutral),l.jsxs("div",{className:"inline-flex flex-col items-center",children:[l.jsxs($s,{variant:v?"secondary":"outline",className:`select-none gap-1 font-normal ${v?"":"border-0 bg-transparent px-0"} ${E}`,style:D,"aria-label":`${C.direction}, ${C.sentiment}`,children:[y&&M&&l.jsx(M,{className:"h-3 w-3"}),l.jsx("span",{className:"tabular-nums",children:T})]}),!1]})}const fLe=new Set(["day","week","month","quarter","year"]);function hLe(e,t){try{const n=Rn.formatInTimeZone(Wx(e),t,"yyyy-MM-dd"),[r,s,o]=n.split("-").map(Number),i=new Date(Date.UTC(r,s-1,o));return i.setUTCDate(i.getUTCDate()-1),Rn.formatInTimeZone(i,"UTC","yyyy-MM-dd")}catch{return}}function mLe(e,t,n,r=!1){const s=PR(e,t,n,r);return`${s.start} - ${s.end}`}function PR(e,t,n,r=!1){try{if(n&&fLe.has(n)){const s=hLe(e.end,t);if(s){const o=r?"MMM d":"MMM d, yyyy";return{start:Rn.formatInTimeZone(Wx(e.start),t,o),end:Rn.formatInTimeZone(Wx(`${s}T00:00:00Z`),"UTC","MMM d, yyyy")}}}if(n==="second"||n==="minute"||n==="hour"){const s=r?"MMM d, h:mm a":"MMM d, yyyy, h:mm a";return{start:Rn.formatInTimeZone(Wx(e.start),t,s),end:`before ${Rn.formatInTimeZone(Wx(e.end),t,s)}`}}}catch{}return{start:e.start,end:`before ${e.end}`}}const pLe=new Set(["current_window_not_started","insufficient_history","comparison_execution_failed"]);function gLe(e){const t=Object.values(e||{});return t.some(n=>n.output.availability.status==="available")?"active":t.some(n=>{var r;return((r=n.output.request)==null?void 0:r.source)==="explicit"&&n.output.availability.status==="unavailable"})?"attention":t.some(n=>{var r;return((r=n.output.request)==null?void 0:r.source)==="inherited"&&n.output.availability.status==="unavailable"&&pLe.has(n.output.availability.reason)})?"unavailable":"hidden"}function FR(e){const t=e.output;if(t.currentWindow&&t.comparisonWindow)return{current:{start:t.currentWindow.startInclusive,end:t.currentWindow.endExclusive},comparison:{start:t.comparisonWindow.startInclusive,end:t.comparisonWindow.endExclusive},timezone:t.currentWindow.timezone,windowGrain:t.windowGrain}}function Bp(e,t,n){return mLe(e,t.timezone,t.windowGrain,n)}function cC(e){const t=e.output.availability;return t.status==="available"?void 0:{finite_current_window_required:"Choose a finite date range to compare.",current_window_not_started:"The selected current window has not started.",temporal_binding_missing:"Choose a date field for this visual.",temporal_binding_ambiguous:"Choose one date field for this visual.",temporal_binding_invalid:"The configured date field is unavailable.",unsupported_output_shape:"This visual output cannot be compared.",unsupported_raw_sql:"Automatic comparison is unavailable for raw SQL.",insufficient_history:"Historical data is unavailable for this period.",invalid_comparison_spec:"The comparison configuration is invalid.",comparison_execution_failed:"Historical comparison could not be loaded."}[t.reason]}function OR(e){return{previous_period:"vs Previous Period",previous_year:"vs Same Period Last Year",target:"vs Target"}[e]}function LR(e){switch(e){case"previous_period":return l.jsx(JK,{className:"h-3.5 w-3.5"});case"previous_year":return l.jsx(JF,{className:"h-3.5 w-3.5"});case"target":return l.jsx(qxe,{className:"h-3.5 w-3.5"})}}function D1(e){var t,n,r;if(((t=e.output.request)==null?void 0:t.source)==="explicit")return"Set by author";if(((n=e.output.request)==null?void 0:n.source)==="inherited")return((r=e.output.request.owner)==null?void 0:r.kind)==="field_date"?`Inherited from ${e.output.request.owner.label}`:"Inherited from Global Date"}function ire({entries:e}){var u;if(e.length===0)return null;const[t,n]=e[0],r=n.type,s=FR(n),o=s==null?void 0:s.current,i=s==null?void 0:s.comparison,a=n.displayLabel||OR(n.type),c=D1(n);return l.jsx("div",{className:"space-y-2.5",children:e.length===1?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-purple-100/80 dark:bg-purple-900/50",children:LR(r)}),l.jsxs("div",{className:"min-w-0 space-y-0.5",children:[l.jsx("p",{className:"break-words text-left text-xs font-medium text-foreground",children:a}),l.jsx("p",{className:"break-words text-left text-[10px] text-muted-foreground",children:n.displayName||t}),c&&l.jsxs("p",{className:"flex items-center gap-1 text-left text-[10px] text-muted-foreground",children:[((u=n.output.request)==null?void 0:u.source)==="explicit"&&l.jsx(GM,{className:"h-2.5 w-2.5"}),c]})]})]}),o&&i&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"group rounded-lg border border-border/50 bg-muted/30 p-2 transition-colors hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium text-muted-foreground",children:[l.jsx(Li,{className:"h-3 w-3 text-blue-600 dark:text-blue-400"}),l.jsx("span",{children:"Current Period"})]}),l.jsx("p",{className:"mt-1 text-xs text-foreground/90",children:Bp(o,s,!1)})]}),l.jsxs("div",{className:"group rounded-lg border border-border/50 bg-muted/30 p-2 transition-colors hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium text-muted-foreground",children:[l.jsx(Li,{className:"h-3 w-3 text-purple-600 dark:text-purple-400"}),l.jsx("span",{children:"Comparison Period"})]}),l.jsx("p",{className:"mt-1 text-xs text-foreground/90",children:Bp(i,s,!1)})]})]}),cC(n)&&l.jsx("p",{className:"text-xs text-muted-foreground",children:cC(n)})]}):l.jsx("div",{className:"space-y-2",children:e.map(([d,f])=>{var p;const h=FR(f);return l.jsxs("div",{className:"rounded-lg border border-border/50 bg-muted/30 p-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-purple-100/80 dark:bg-purple-900/50",children:LR(f.type)}),l.jsxs("div",{className:"min-w-0 space-y-0.5",children:[l.jsx("p",{className:"break-words text-xs font-medium text-foreground",children:f.displayLabel||OR(f.type)}),l.jsx("p",{className:"break-words text-[10px] text-muted-foreground",children:f.displayName||d}),D1(f)&&l.jsxs("p",{className:"flex items-center gap-1 text-[10px] text-muted-foreground",children:[((p=f.output.request)==null?void 0:p.source)==="explicit"&&l.jsx(GM,{className:"h-2.5 w-2.5"}),D1(f)]})]})]}),h&&l.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[Bp(h.current,h,!0)," ","vs"," ",Bp(h.comparison,h,!0)]}),cC(f)&&l.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:cC(f)})]},d)})})})}function are({metadata:e,variant:t="compact"}){var b;const n=w.useId(),r=Object.entries(e||{});if(r.length===0)return null;const s=gLe(e);if(s==="hidden")return null;const o=s==="active",i=o?r.length>1?"Comparisons":"Comparison":s==="attention"?"Comparison needs attention":"Comparison unavailable",[a,c]=r[0],u=c.type,d=FR(c),f=d==null?void 0:d.current,h=d==null?void 0:d.comparison,p=c.displayLabel||OR(c.type);c.displayName;const g=D1(c);return t==="compact"?l.jsxs(yb,{openDelay:200,children:[l.jsx(vb,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`${i} details`,"aria-describedby":n,className:m.cn(Qne({variant:"outline"}),"h-6 rounded-control px-2 py-0 text-[11px] shadow-none focus:ring-0 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",o?"cursor-pointer select-none border-border bg-background text-foreground transition-colors hover:bg-muted/40":"cursor-pointer select-none border-amber-200/80 bg-amber-50/70 text-amber-900 transition-colors hover:bg-amber-100/70 dark:border-amber-800/60 dark:bg-amber-950/35 dark:text-amber-100 dark:hover:bg-amber-950/55"),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[o?l.jsx(JK,{className:"h-3.5 w-3.5 text-muted-foreground"}):l.jsx(xi,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"font-medium",children:i})]})})}),l.jsx(zd,{id:n,className:"w-80 p-3",align:"start",side:"bottom",children:l.jsx(ire,{entries:r})})]}):l.jsxs("div",{className:o?"rounded-lg border border-purple-200/60 bg-gradient-to-br from-purple-50/40 via-purple-50/30 to-white p-3.5 shadow-sm dark:border-purple-800/40 dark:from-purple-950/30 dark:via-purple-900/20 dark:to-background":"rounded-lg border border-amber-200/70 bg-amber-50/50 p-3.5 shadow-sm dark:border-amber-800/50 dark:bg-amber-950/25",children:[l.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[l.jsx("div",{className:o?"flex h-7 w-7 items-center justify-center rounded-md bg-purple-100 dark:bg-purple-900/60":"flex h-7 w-7 items-center justify-center rounded-md bg-amber-100 dark:bg-amber-900/60",children:o?LR(u):l.jsx(xi,{className:"h-3.5 w-3.5"})}),l.jsx("span",{className:o?"text-sm font-semibold text-purple-950 dark:text-purple-100":"text-sm font-semibold text-amber-950 dark:text-amber-100",children:o?r.length>1?"Multiple comparisons":p:i}),r.length===1&&g&&l.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[((b=c.output.request)==null?void 0:b.source)==="explicit"&&l.jsx(GM,{className:"h-3 w-3"}),g]})]}),r.length===1&&f&&h&&l.jsxs("div",{className:"grid grid-cols-1 gap-2 text-sm sm:grid-cols-2",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-blue-500"}),l.jsx("span",{children:"Current"})]}),l.jsx("p",{className:"text-sm leading-relaxed text-foreground/90",children:Bp(f,d,!0)})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-purple-500"}),l.jsx("span",{children:"Comparison"})]}),l.jsx("p",{className:"text-sm leading-relaxed text-foreground/90",children:Bp(h,d,!0)})]})]})]})}const bLe=50;function xLe({children:e,value:t,className:n,style:r}){const s=w.useRef(null),[o,i]=w.useState(!1),[a,c]=w.useState(!1),u=t.length<=bLe;w.useEffect(()=>{const f=()=>{s.current&&i(s.current.scrollWidth>s.current.clientWidth)};return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[t]);const d=f=>{f.stopPropagation(),navigator.clipboard.writeText(t),c(!0),setTimeout(()=>c(!1),1500)};return o?l.jsxs(yb,{openDelay:300,closeDelay:200,children:[l.jsx(vb,{asChild:!0,children:l.jsx("div",{ref:s,className:m.cn("cursor-default",n),style:r,children:e})}),u?l.jsxs(zd,{className:"w-fit max-w-80 cursor-pointer p-3 transition-colors",align:"start",side:"bottom",onClick:d,children:[l.jsx("span",{className:"block text-sm",children:t}),l.jsx("span",{className:"mt-1 block text-xs text-muted-foreground",children:a?"Copied!":"Click to copy"})]}):l.jsxs(zd,{className:"max-h-64 w-80 overflow-y-auto p-3",align:"start",side:"bottom",children:[l.jsx("div",{className:"mb-2 flex justify-end border-b pb-2",children:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs text-muted-foreground",onClick:d,children:a?l.jsxs(l.Fragment,{children:[l.jsx(m.Check,{className:"size-3"}),"Copied!"]}):l.jsxs(l.Fragment,{children:[l.jsx(_d,{className:"size-3"}),"Click to copy"]})})}),l.jsx("span",{className:"block break-words text-sm",children:t})]})]}):l.jsx("div",{ref:s,className:n,style:r,children:e})}function yLe({data:e,formattingFullRows:t,formattingRenderContext:n={kind:"interactiveDashboard",rowSource:"loadedRows"},sorting:r,columnSettings:s,selectColumnVisible:o=!0,onOpenColumnSettings:i,isVisualEditing:a,contextTimezone:c,browserTimezone:u=Intl.DateTimeFormat().resolvedOptions().timeZone,card:d,comparisonMetadata:f,suppressSortControls:h=!1,suppressCellHoverCards:p=!1,headerTextClassName:g,headerWrapText:b=!1,appearanceWrapText:x,showColumnReorderControls:y=!1,isSqlCard:v=!1,valueFormatPreferences:S,resolveBoundCurrency:N}){var J,oe,Q,ae,ie,le,ue,fe;if(e.length===0)return[];const C=new Map,j=new Map,_=pe=>{const ge=C.get(pe);if(ge)return ge;const de=A0(pe,e,void 0,d==null?void 0:d.config);return C.set(pe,de),de},k=(pe,ge=pe)=>{const de=pe===ge?pe:`${pe}::${ge}`,ye=j.get(de);if(ye)return ye;const ce=Vi({card:d,columnId:pe,resolvedSettings:s[pe],fallbackSettings:_(ge)})||_(ge);return j.set(de,ce),ce},I={id:"select",header:({table:pe})=>l.jsx("div",{className:"flex items-center justify-start pl-3",children:l.jsx(Tn,{checked:pe.getIsAllPageRowsSelected()||pe.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:ge=>pe.toggleAllPageRowsSelected(!!ge),"aria-label":"Select all rows"})}),cell:({row:pe})=>l.jsx("div",{className:"flex items-center justify-start pl-3",onClick:ge=>ge.stopPropagation(),children:l.jsx(Tn,{checked:pe.getIsSelected(),onCheckedChange:ge=>pe.toggleSelected(!!ge),"aria-label":"Select row"})}),size:50,minSize:30,maxSize:100,enableSorting:!1,enableHiding:!1,enableResizing:!0},{keys:T}=Cr(e,f);let E=T;if((d==null?void 0:d.type)==="table"){const pe=((oe=(J=d.config)==null?void 0:J.metricColumns)==null?void 0:oe.length)>0,ge=((ae=(Q=d.config)==null?void 0:Q.groupByColumns)==null?void 0:ae.length)>0,de=!!d.sql;!pe&&ge&&!de&&(E=T.filter(ye=>{if(ye.toLowerCase()!=="count")return!0;const ce=e.find(re=>re[ye]!=null);return ce?typeof ce[ye]!="number":!0}))}const D=(d==null?void 0:d.type)==="table",M=D||(d==null?void 0:d.type)==="detailTable",A=D?(ie=d==null?void 0:d.preferences)==null?void 0:ie.comparisonPresentation:void 0,P=n_(A);if(!P){const{comparisonColumnKeys:pe}=ib(f);E=E.filter(ge=>!pe.has(ge))}const O=((le=d==null?void 0:d.config)==null?void 0:le.metricColumns)||[];(ue=d==null?void 0:d.config)!=null&&ue.groupByColumns;const $=new Map,V=new Map;D&&P&&O.length>0&&O.forEach(pe=>{const{comparisonKind:ge,metadata:de}=C5(f,pe);if(ge==="none")return;const ye=pe.label||pe.name,ce=iw(pe).find(ee=>E.includes(ee));if(!ce)return;const re=KQ(ye,ge,de);re&&($.set(ce,{metric:pe,comparisonKind:ge,comparisonKey:re}),V.set(re,{metric:pe,comparisonKind:ge,comparisonKey:re}))}),E=HA(E,d,pe=>{const ge=$.get(pe);return(ge==null?void 0:ge.comparisonKey)??null});const U=(A==null?void 0:A.indicatorStyle)||"arrow_badge",R=U!=="none",q=(A==null?void 0:A.showColor)!==!1&&(U==="arrow_badge"||U==="badge"),W=(A==null?void 0:A.displayMode)||"difference",F=pe=>{if(typeof pe=="number")return Number.isFinite(pe)?pe:null;if(typeof pe=="string"&&pe.trim()!==""){const ge=Number(pe);return Number.isFinite(ge)?ge:null}return null},Z=(pe,ge)=>{if(!M)return;const de=d&&!ge?jm(d,{columnId:pe}):void 0,ye=ge??(de==null?void 0:de.id),ce=d?Jl({card:d,columnKey:pe,metricId:ye}):void 0,re=ce?N==null?void 0:N(ce):void 0;return{resolvedMetricId:ye,boundCurrency:re}},K=(pe,ge,de)=>{const ye=Z(ge,de);if(ye)return Jk({card:d,columnId:ge,resolvedSettings:s[ge],fallbackSettings:pe,metricId:ye.resolvedMetricId,valueFormatPreferences:S,boundCurrency:ye.boundCurrency})},Y=(pe,ge,de)=>{const ye=Z(de),ce=ye?kg({card:d,columnId:de,resolvedSettings:s[de],fallbackSettings:ge,metricId:ye.resolvedMetricId,valueFormatPreferences:S,boundCurrency:ye.boundCurrency}):void 0;if(ce)return In.formatNumericCanonical(pe,ce);if(!(ge!=null&&ge.numberFormat))return pe.toLocaleString();try{return In.formatNumberWithColumnSettings(pe,ge.numberFormat)}catch{return pe.toLocaleString()}},X=({primaryValue:pe,secondaryValue:ge,displayMode:de,metricFormatOptions:ye,fallbackSettings:ce})=>{var _e,Le,Ue,je,Xe,Ze,at;const re=(ye==null?void 0:ye.locale)||((_e=ce==null?void 0:ce.numberFormat)==null?void 0:_e.locale)||"en-US",ee=m.normalizeMetricComparisonPrecision((A==null?void 0:A.precision)??((Le=ce==null?void 0:ce.numberFormat)==null?void 0:Le.maximumFractionDigits)),se=Ya.evaluateMetricComparison({currentValue:pe,comparisonValue:ge}),ne=ur.formatMetricComparison(se,{displayMode:de,metricFormat:m.fromTFormatOptions(ye)??m.fromColumnNumberFormat(ce==null?void 0:ce.numberFormat),locale:re,...ee!==void 0?{precision:ee}:{}}),he=(Be,lt)=>Be?lt!==null&<>0?`+${Be}`:Be:"—";return de==="difference"?he(((Ue=ne.difference)==null?void 0:Ue.text)??null,se.delta):de==="percent_change"?he(((je=ne.percentChange)==null?void 0:je.text)??null,se.percentChange):de==="both"?`${he(((Xe=ne.percentChange)==null?void 0:Xe.text)??null,se.percentChange)} (${he(((Ze=ne.difference)==null?void 0:Ze.text)??null,se.delta)})`:((at=ne.ratio)==null?void 0:at.text)??"—"},z={...(fe=d==null?void 0:d.preferences)==null?void 0:fe.tablePrefs,columnSettingsMap:s},B=pe=>{var ye;const ge=k(pe).type;return ge==="number"||ge==="date"||ge==="text"?ge:typeof((ye=e.find(ce=>ce[pe]!=null))==null?void 0:ye[pe])=="number"?"number":"text"},H=(d==null?void 0:d.type)==="detailTable"||(d==null?void 0:d.type)==="aggregateTable"||(d==null?void 0:d.type)==="pivotTable"?d.type:"table",L=dNe({tableKind:H,renderContext:n,columns:T.map(pe=>({id:pe,type:B(pe)})),renderedColumnIds:E,rows:e,fullRows:t,tablePreferences:z}),G=E==null?void 0:E.map(pe=>{const ge=V.get(pe),de=k(pe),ye=de!=null&&de.width&&typeof de.width=="number"?de.width:150,ce=(de==null?void 0:de.minWidth)??50,re=(de==null?void 0:de.maxWidth)??500;return{id:pe,accessorFn:ee=>ee[pe],meta:{isNumeric:H==="table"&&(de==null?void 0:de.type)==="number",getConditionalFormatting:(ee,se)=>oB({formatting:L.conditionalFormatting,row:ee,columnId:pe,range:L.range,tablePart:"body"})},enableGlobalFilter:!0,enableSorting:!ge,size:ye,minSize:ce,maxSize:re,enableResizing:!0,header:({column:ee})=>{const ne=(ge?Pje(ge.metric.label||ge.metric.name,ge.comparisonKind):null)??pe,he=r.findIndex(St=>St.id===ee.id),_e=he!==-1,Ue=(_e?r[he].desc?"desc":"asc":null)==="asc"?No:ro,je=_e&&r.length>1,Xe=k(ee.id,pe),Ze=Xe.textAlign||"left",at=Ze==="right",Be=Ze==="center",lt=Xe,Te=(lt==null?void 0:lt.type)==="date";let nt,Oe=!1;Te&&(lt!=null&<.dateFormat)&&(lt.dateFormat.timezone&<.dateFormat.timezone!=="auto"?nt=lt.dateFormat.timezone:nt=v?u:c||u,Oe=nt!==u);const He=ne.charAt(0).toUpperCase()+ne.slice(1),qe=a&&!ee.getIsResizing(),Ae=!h&&ee.getCanSort(),Qe=at?"justify-end":Be?"justify-center":"justify-start",ct=D&&Xe.type==="number",It=b?ct?Qe:"justify-start":Qe,yt=at?"text-right":Be?"text-center":"text-left",kt=m.cn(S1e(b),b&&(ct?yt:"text-left")),Mt=b?"items-start":"items-center",vt=l.jsxs(l.Fragment,{children:[l.jsxs("span",{className:m.cn("min-w-0",kt),title:Oe&&nt?`${He} (${ur.getTimezoneAbbreviation(nt)})`:He,children:[He,Oe&&l.jsxs("span",{className:"ml-1 text-xs font-normal text-muted-foreground",children:["(",ur.getTimezoneAbbreviation(nt),")"]})]}),!h&&_e&&l.jsxs("span",{className:"inline-flex shrink-0 items-center",children:[l.jsx(Ue,{className:"h-3 w-3 shrink-0 text-foreground"}),je&&l.jsx("sup",{className:"ml-0.5 text-[9px] font-semibold tabular-nums text-muted-foreground",children:he+1})]})]});return l.jsxs("div",{className:m.cn("group/table-head relative flex select-none gap-1.5",Mt,y&&"pl-4"),children:[y&&l.jsx("span",{"data-grip-handle":"",className:"absolute left-0 top-1/2 inline-flex -translate-y-1/2 cursor-grab items-center active:cursor-grabbing","aria-label":"Drag to reorder column",children:l.jsx(bu,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-600","aria-hidden":"true"})}),h?l.jsx("div",{className:m.cn("flex min-w-0 flex-1 gap-1 uppercase",It,Mt,g),children:vt}):l.jsx("button",{type:"button",onClick:St=>{St.preventDefault();const ke=St.shiftKey;ee.toggleSorting(ee.getIsSorted()==="asc",ke)},className:m.cn("flex min-w-0 flex-1 cursor-pointer gap-1 uppercase",It,Mt,g),children:vt}),qe&&l.jsxs(Ys,{modal:!1,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Configure ${ne} column`,className:m.cn("inline-flex shrink-0 items-center justify-center rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",b&&"self-start"),onClick:St=>St.stopPropagation(),children:l.jsx(Si,{className:"h-3 w-3"})})}),l.jsxs(Es,{align:"end",className:"w-44",children:[Ae&&l.jsxs(l.Fragment,{children:[l.jsxs(Nn,{className:"gap-2 text-xs",onSelect:()=>ee.toggleSorting(!1,!1),children:[l.jsx(No,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Sort ascending"]}),l.jsxs(Nn,{className:"gap-2 text-xs",onSelect:()=>ee.toggleSorting(!0,!1),children:[l.jsx(ro,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Sort descending"]}),l.jsx(Sa,{})]}),l.jsxs(Nn,{className:"gap-2 text-xs",onSelect:()=>i(ee.id),children:[l.jsx(m.SlidersHorizontal,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Format column"]})]})]})]})},cell:({row:ee,column:se})=>{var Ae,Qe,ct,It,yt,kt,Mt,vt,St;const ne=ee.getValue(pe),he=k(se.id,pe),_e=oB({formatting:L.conditionalFormatting,row:ee.original,rowIndex:ee.index,columnId:se.id,range:L.range,tablePart:"body"});let Le=null;const Ue=he.textAlign==="center"?"text-center":he.textAlign==="right"?"text-right":"text-left",je=s[se.id]??(se.id!==pe?s[pe]:void 0),Xe=(ct=(Qe=(Ae=d==null?void 0:d.preferences)==null?void 0:Ae.tablePrefs)==null?void 0:Qe.tableStyle)==null?void 0:ct.wrapText,Ze=TX(je==null?void 0:je.textWrap),at=f5({tableWrapText:Xe,textWrap:he.textWrap,appearanceWrapText:x,hasColumnTextWrapOverride:Ze}),Be=v1e({tableWrapText:Xe,textWrap:he.textWrap,appearanceWrapText:x,hasColumnTextWrapOverride:Ze}),lt=w1e(at);if(D&&ge){const ke=ge.metric.label||ge.metric.name,Ee=k(ke),Pe=Fje(f,ge.metric),Fe=((It=Pe==null?void 0:Pe.output)==null?void 0:It.currentColumnKey)||ke,Ge=((yt=Pe==null?void 0:Pe.output)==null?void 0:yt.availability.status)==="available"&&Pe.output.comparisonColumnKey||pe,Pt=ee.original[Fe],_t=ee.original[Ge],Ft=F(Pt),Vt=F(_t),Ht=[...Pe?[[Pe.output.outputId,Pe]]:[]],Qn=(Pe==null?void 0:Pe.displayLabel)||Rje(ge.comparisonKind),st=K(Ee,ke,ge.metric.id),De=Vt===null||Ft===null?l.jsx("span",{className:"text-xs text-muted-foreground",children:"—"}):R?l.jsx(e3,{primaryValue:Ft,secondaryValue:Vt,presentation:{...A,indicatorStyle:U,showColor:q},metricFormatOptions:st,locale:(st==null?void 0:st.locale)||((kt=Ee.numberFormat)==null?void 0:kt.locale)||"en-US",decimalPlaces:(Mt=Ee.numberFormat)==null?void 0:Mt.maximumFractionDigits,polarity:m.getMetricComparisonPolarity(ge.metric)}):l.jsx("span",{className:"text-xs text-muted-foreground",children:Vt!==null?X({primaryValue:Ft??0,secondaryValue:Vt,displayMode:W,metricFormatOptions:st,fallbackSettings:Ee}):"—"}),mt=Ft!==null?Y(Ft,Ee,ke):"—",Ct=Vt!==null?Y(Vt,Ee,ke):"—",Kt=!!(Pe!=null&&Pe.output.currentWindow)&&!!Pe.output.comparisonWindow,Bt=l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsx("div",{className:"font-semibold",children:Qn}),l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("span",{children:"Current"}),l.jsx("span",{className:"font-mono",children:mt})]}),l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("span",{children:Qn}),l.jsx("span",{className:"font-mono",children:Ct})]})]}),l.jsx("div",{children:De}),Kt&&l.jsx(ire,{entries:Ht})]});return l.jsx("div",{className:`${Ue} ${lt}`,children:l.jsxs(yb,{children:[l.jsx(vb,{asChild:!0,children:l.jsx("div",{className:"inline-flex items-center",children:De})}),l.jsx(zd,{className:"w-80 p-3",align:"end",side:"bottom",children:Bt})]})})}const Te=EX({formatting:L.baseFormatting,compatibility:{columnSettings:he,tablePreferences:z,columnMeta:L.columns.find(ke=>ke.id===se.id),appearanceWrapText:Ze?void 0:x,hasColumnTextWrapOverride:Ze},columnId:se.id,tablePart:"body"}),nt=!!((vt=_e.cellStyle)!=null&&vt.backgroundColor||(St=_e.rowStyle)!=null&&St.backgroundColor),Oe={width:"100%",display:"block",...$1e({base:nt?{...Te,backgroundColor:void 0}:Te,conditional:{..._e,cellStyle:_e.cellStyle?{..._e.cellStyle,backgroundColor:void 0}:void 0,rowStyle:_e.rowStyle?{..._e.rowStyle,backgroundColor:void 0}:void 0}})};if(Oe.color&&(Oe["--document-table-cell-color"]=String(Oe.color)),ne==null){const ke=he.textAlign==="center"?"justify-center":he.textAlign==="right"?"justify-end":"justify-start";return l.jsx("div",{className:`flex items-center ${ke}`,style:Oe,children:l.jsx(Ac,{className:"h-4 w-4 text-muted-foreground/50"})})}let He;if(he.type==="badge"||he.type==="none"&&typeof ne=="string"&&["department","role"].includes(pe))He=l.jsx($s,{variant:"outline",className:"px-1.5 text-muted-foreground",children:String(ne)});else if(he.type==="number"&&typeof ne=="number"){const ke=Y(ne,he,pe);Le=ke,He=ke}else if(he.type==="date"&&ne)if(!v)He=String(ne);else try{if(he.dateFormat.useRelativeTime)He=ur.formatRelativeTime(String(ne),he.dateFormat.sourceTimezone||"auto");else{const ke=MX(!0,he.dateFormat.timezone,u,c),Ee=he.dateFormat.useCustomFormat?he.dateFormat.customFormat:he.dateFormat.format,Pe=ur.formatDate(String(ne),Ee,ke,he.dateFormat.sourceTimezone||"auto");He=l.jsx("span",{title:`${yN(ke||u)} (${ur.getTimezoneAbbreviation(ke||u)})`,children:Pe})}}catch{He=String(ne)}else if(he.type==="link"&&ne){const ke=he.linkFormat||Cl(),Ee=ke.urlTemplate||"{value}",Pe=String(ne),Fe=Ee.trim()==="{value}";let Ge;Fe?Ge=Pe:(Ge=Ee.replace(/{value}/g,encodeURIComponent(Pe)),Ge=Ge.replace(/{([^}]+)}/g,(Ft,Vt)=>{if(Vt==="value")return Ft;const Ht=ee.original[Vt];return Ht!=null?encodeURIComponent(String(Ht)):""})),Ge.startsWith("http://")||Ge.startsWith("https://")||Ge.startsWith("mailto:")||Ge.startsWith("tel:")||Ge.startsWith("/")||(Ge="https://"+Ge);let _t;switch(ke.labelType){case"static":_t=ke.staticLabel||String(ne);break;case"column":_t=ke.labelColumn&&ee.original[ke.labelColumn]!=null?String(ee.original[ke.labelColumn]):String(ne);break;default:_t=String(ne)}He=l.jsx("a",{href:Ge,target:ke.openInNewTab?"_blank":"_self",rel:ke.openInNewTab?"noopener noreferrer":void 0,className:"text-blue-600 hover:underline",style:Oe.color?{color:"inherit"}:void 0,onClick:Ft=>Ft.stopPropagation(),children:_t})}else if(he.type==="progress"&&typeof ne=="number"){const ke=Math.min(Math.max(0,ne),100);let Ee="#ef4444";ke>=70?Ee="#22c55e":ke>=40&&(Ee="#eab308"),He=l.jsxs("div",{className:"flex w-full items-center gap-2",children:[l.jsx("div",{className:"h-2.5 flex-1 overflow-hidden rounded-full bg-muted",children:l.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${ke}%`,backgroundColor:Ee}})}),l.jsxs("span",{className:"whitespace-nowrap text-xs font-medium",children:[ke,"%"]})]})}else He=String(ne);if(!p&&!Be&&typeof He=="string"){const ke=Le??String(ne);return l.jsx(xLe,{value:ke,className:`${Ue} ${lt}`,style:Oe,children:He})}return l.jsx("div",{className:`${Ue} ${lt}`,style:Oe,children:He})}}});return o?[I,...G]:G}const vLe=(e,t)=>e.length===t.length&&e.every((n,r)=>{var s,o;return n.id===((s=t[r])==null?void 0:s.id)&&!!n.desc==!!((o=t[r])!=null&&o.desc)});function lre({card:e,dataLength:t,pageSize:n,paginationMetadata:r,onPaginationChange:s,sortState:o,onSortChange:i,allowSqlLocalSortingWhenServerPaginated:a=!0}){var E,D,M;const{displayPreferences:c}=sl(),u=Wk(c.mode),d=e?PL(e,c.mode):u?"disabled":"client",f=d==="disabled"?Number.MAX_SAFE_INTEGER:E_(n||((E=e==null?void 0:e.paginationConfig)==null?void 0:E.pageSize)||((M=(D=e==null?void 0:e.preferences)==null?void 0:D.tablePrefs)==null?void 0:M.pageSize)),[h,p]=w.useState(o||[]),[g,b]=w.useState(r&&d==="server"?r.page-1:0),[x,y]=w.useState(f),v=w.useRef(null),S=w.useMemo(()=>({pageIndex:g,pageSize:d==="client"?x:f}),[f,x,g,d]),N=d==="server"&&!(e!=null&&e.sql)&&!!i,C=d!=="server"||!!(e!=null&&e.sql)&&a,j=N||C,_=w.useCallback(A=>{if(!j)return;const P=typeof A=="function"?A(h):A;p(P),N&&(i==null||i(P))},[j,i,N,h]),k=w.useCallback(A=>{const P=typeof A=="function"?A(S):A;b(P.pageIndex),d==="client"&&y(P.pageSize),d==="server"&&(s==null||s(P.pageIndex,P.pageSize))},[s,S,d]),I=w.useCallback((A=f)=>{d==="client"&&(b(0),y(A))},[f,d]),T=w.useRef(null);return w.useEffect(()=>{if(!N){T.current=null;return}const A=JSON.stringify(o??[]);if(A!==T.current){if(T.current=A,!(o!=null&&o.length)){h.length&&p([]);return}vLe(o,h)||p(o)}},[N,o,h]),w.useEffect(()=>{if(!(d==="server"&&!!s&&!r&&!(e!=null&&e.paginationConfig))){v.current=null;return}const P=`${(e==null?void 0:e.id)??"unknown"}:${f}`;v.current!==P&&(v.current=P,s(0,f))},[e==null?void 0:e.id,e==null?void 0:e.paginationConfig,f,s,r,d]),w.useEffect(()=>{d==="server"&&r&&b(r.page-1)},[r,d]),w.useEffect(()=>{d==="client"&&y(f)},[f,d]),w.useEffect(()=>{if(d!=="client")return;const A=Math.max(1,Math.ceil(t/S.pageSize));S.pageIndex<A||b(A-1)},[t,S,d]),{canSort:j,canUseLocalSorting:C,effectivePageSize:f,handlePaginationChange:k,handleSortChange:_,isTablePrintDisplayMode:u,pagination:S,paginationMode:d,resetClientPagination:I,shouldSyncSortWithExternal:N,sorting:h}}function wLe(e){return Object.values(e).some(t=>t!==void 0)}function cre(e){var vt,St,ke;const{data:t,totalsData:n,pageSize:r,comparisonMetadata:s,columnSettings:o,columnVisibility:i,initialColumnVisibility:a,defaultSelectColumnVisible:c,onSelectColumnVisibleChange:u,onInitializeColumnVisibility:d,onUpdateAllColumnVisibility:f,onColumnSettingsChange:h,onResetColumnSettings:p,onResetAllColumnSettings:g,onBaseFormattingChange:b,onColumnVisibilityChange:x,onSortChange:y,sortState:v,onColumnReorder:S,columnSizing:N,onColumnSizingChange:C,card:j,paginationMetadata:_,onPaginationChange:k,suppressSortControls:I=!1,suppressCellHoverCards:T=!1,headerTextClassName:E,headerWrapText:D,appearanceWrapText:M}=e,{displayPreferences:A}=sl(),P=w.useMemo(()=>Object.keys(t[0]||{}),[t]),{preferences:O,resolveBoundCurrency:$}=ka(j,P),[V,U]=w.useState([]),[R,q]=w.useState(""),[W,F]=w.useState({}),Z=Wk(A.mode),{canUseLocalSorting:K,effectivePageSize:Y,handlePaginationChange:X,handleSortChange:z,pagination:B,paginationMode:H,resetClientPagination:L,sorting:G}=lre({card:j,dataLength:t.length,onPaginationChange:k,onSortChange:y,pageSize:r,paginationMetadata:_,sortState:v}),[J,oe]=w.useState(!1),[Q,ae]=w.useState(null),[ie,le]=w.useState({}),ue=o||ie,[fe,pe]=w.useState(c||!1);w.useEffect(()=>{u||pe(c??!1)},[c,u]);const ge=u?c!==void 0?c:!1:fe,[de,ye]=w.useState(a||{}),ce=i!==void 0?i:de,re=w.useRef(null),ee=w.useRef(!1),se=m.useDashboardStore(Ee=>Ee.themeStyle);m.useDashboardStore(Ee=>Ee.isDashboardEditing);const ne=m.useDashboardStore(Ee=>Ee.isVisualEditing),he=al()??void 0,_e=Intl.DateTimeFormat().resolvedOptions().timeZone,Le=w.useMemo(()=>e.formattingRenderContext?e.formattingRenderContext:Z?{kind:"documentPrint",rowSource:e.formattingFullRows?"fullRows":"pageSlice"}:{kind:"interactiveDashboard",rowSource:"loadedRows"},[Z,e.formattingFullRows,e.formattingRenderContext]),Ue=Z?e.formattingFullRows:void 0,je=w.useCallback(Ee=>{ae(Ee),oe(!0)},[]),Xe=w.useMemo(()=>{if(!Q)return ks();let Ee=ue[Q];return Ee||(Ee=t&&t.length>0?A0(Q,t,void 0,j==null?void 0:j.config):ks()),Vi({card:j,columnId:Q,resolvedSettings:Ee,preserveOmittedProperties:!0})||Ee},[Q,j,ue,t]),Ze=w.useMemo(()=>{var Ee,Pe,Fe,Ge;return Q?((Ge=(Fe=ky((Pe=(Ee=j==null?void 0:j.preferences)==null?void 0:Ee.tablePrefs)==null?void 0:Pe.baseFormatting).columns)==null?void 0:Fe[Q])==null?void 0:Ge.body)??{}:{}},[Q,j]),at=w.useMemo(()=>yLe({data:t,formattingFullRows:Ue,formattingRenderContext:Le,sorting:G,columnSettings:ue,selectColumnVisible:ge,isVisualEditing:ne,onOpenColumnSettings:je,contextTimezone:he,browserTimezone:_e,card:j,isSqlCard:!!(j!=null&&j.sql),comparisonMetadata:s,suppressSortControls:I,suppressCellHoverCards:T,headerTextClassName:E,headerWrapText:D,appearanceWrapText:M,showColumnReorderControls:ne&&!!S&&Yh(j),valueFormatPreferences:O,resolveBoundCurrency:$}),[_e,j,ue,s,he,t,Ue,Le,je,ne,S,ge,E,D,M,T,I,G,O,$]),Be=H_({data:t,columns:at,getCoreRowModel:B_(),onSortingChange:z,getSortedRowModel:K?Gne():void 0,onColumnFiltersChange:U,getFilteredRowModel:z5e(),getPaginationRowModel:H==="client"?V_():void 0,onRowSelectionChange:F,onPaginationChange:H==="disabled"?void 0:X,manualPagination:H==="server"||H==="disabled",pageCount:H==="server"&&_?_.pageCount:void 0,onColumnVisibilityChange:Ee=>{if(ee.current)return;let Pe={};if(typeof Ee=="function"){const Fe=Be.getState().columnVisibility;try{Pe=Ee(Fe)}catch(Ge){console.error("Failed to resolve visibility function:",Ge);return}}else Pe=Ee;if(f)f(Pe);else if(x){const Fe=Be.getState().columnVisibility;Object.entries(Pe).forEach(([Ge,Pt])=>{Fe[Ge]!==Pt&&x(Ge,Pt)})}else ye(Pe)},manualSorting:!K,state:{sorting:G,columnFilters:V,globalFilter:R,rowSelection:W,pagination:B,columnVisibility:ce,columnSizing:N||{}},enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:C,enableMultiSort:!0,enableRowSelection:!0}),lt=(vt=Be==null?void 0:Be.getAllColumns())==null?void 0:vt.length,Te=(ke=(St=Be==null?void 0:Be.getCoreRowModel())==null?void 0:St.rows)==null?void 0:ke.length;re.current=Be,w.useEffect(()=>{if(x&&d){const Pe=Be.getAllColumns().filter(Ge=>Ge.id!=="select").map(Ge=>Ge.id).filter(Ge=>typeof Ge=="string");(!i||Object.keys(i).length===0)&&d(Pe)}},[i,x,d,Be]);const nt=(Ee,Pe)=>{ee.current=!0;try{x?x(Ee,Pe):(console.log("Updating internal state",Ee,Pe),ye(Ge=>({...Ge,[Ee]:Pe})));const Fe=Be.getColumn(Ee);Fe&&Fe.toggleVisibility(Pe)}finally{ee.current=!1}},Oe=Ee=>{if(!Q)return;const Pe={...ue,[Q]:Ee};h?h(Q,Ee,Xe):le(Pe)},He=Ee=>{var _t,Ft;if(!Q||!b)return;const Pe=ky((Ft=(_t=j==null?void 0:j.preferences)==null?void 0:_t.tablePrefs)==null?void 0:Ft.baseFormatting),Fe=Pe.columns??{},Ge={...Fe,[Q]:{...Fe[Q],body:wLe(Ee)?{...Ee}:void 0}},Pt=Ge[Q];!Pt.body&&!Pt.header&&!Pt.footer&&delete Ge[Q],b({version:1,...Pe.tableParts?{tableParts:Pe.tableParts}:{},...Object.keys(Ge).length?{columns:Ge}:{}})},qe=()=>{if(Q){if(p)p(Q);else{const Ee={...ue};delete Ee[Q],le(Ee)}He({})}},Ae=()=>{var Ee,Pe;if(g?g():le({}),b){const Fe=ky((Pe=(Ee=j==null?void 0:j.preferences)==null?void 0:Ee.tablePrefs)==null?void 0:Pe.baseFormatting);b({version:1,...Fe.tableParts?{tableParts:Fe.tableParts}:{}})}oe(!1)},Qe=Ee=>{u?u(Ee):pe(Ee)},ct=Ee=>({}),It=Object.keys(W).length,yt={};Be.getAllColumns().forEach(Ee=>{if(Ee.id==="select")return;const Pe=t&&t.length>0?A0(Ee.id,t,void 0,j==null?void 0:j.config):ks();yt[Ee.id]=Vi({card:j,columnId:Ee.id,resolvedSettings:ue[Ee.id],fallbackSettings:Pe})||Pe});const kt={rows:Be.getFilteredRowModel().rows.map(Ee=>{const Pe={};return Be.getAllColumns().filter(Fe=>Fe.id!=="select"&&Fe.getIsVisible()).forEach(Fe=>{const Ge=Fe.id;Pe[Ge]=Ee.getValue(Ge)}),Pe}),selectedRows:Be.getFilteredSelectedRowModel().rows.map(Ee=>{const Pe={};return Be.getAllColumns().filter(Fe=>Fe.id!=="select"&&Fe.getIsVisible()).forEach(Fe=>{const Ge=Fe.id;Pe[Ge]=Ee.getValue(Ge)}),Pe}),visibleColumns:Be.getAllColumns().filter(Ee=>Ee.id!=="select"&&Ee.getIsVisible()).map(Ee=>Ee.id),columnSettings:yt,contextTimezone:he,browserTimezone:_e},Mt=w.useRef(ne);return w.useEffect(()=>{!ne&&Mt.current&&(ye(a||{}),H!=="server"&&H!=="disabled"&&L(Y)),Mt.current=ne},[a,ne,H,Y,L]),w.useEffect(()=>{if(i&&Object.keys(i).length>0){if(ee.current)return;ee.current=!0;try{const Ee=re.current;if(!Ee)return;Ee.getAllColumns().forEach(Pe=>{if(Pe.id!=="select"&&Pe.getCanHide()&&typeof Pe.id=="string"){const Fe=i[Pe.id]!==void 0?i[Pe.id]:!0;Pe.getIsVisible()!==Fe&&Pe.toggleVisibility(Fe)}})}finally{ee.current=!1}}},[i]),{table:Be,columnSettingsToUse:ue,selectColumnVisible:ge,columnVisibilityToUse:ce,handleColumnVisibilityChange:nt,resetColumnSettings:qe,resetAllColumnSettings:Ae,handleSelectColumnVisibleChange:Qe,selectedRowsCount:It,exportData:kt,globalFilter:R,setGlobalFilter:q,setRowSelection:F,columnSettingsOpen:J,activeColumnId:Q,activeColumnSettings:Xe,activeColumnBaseStyle:Ze,handleColumnSettingsChange:Oe,handleColumnBaseStyleChange:He,isHandlingVisibilityChange:ee,themeStyle:se,tableRef:re,internalColumnSettings:ie,internalSelectColumnVisible:fe,getRowStyle:ct,setColumnSettingsOpen:oe,columns:at,internalColumnVisibility:de,totalColumns:lt,totalRows:Te,isTablePrintDisplayMode:Z,onSortChange:y,paginationMode:H,paginationMetadata:_,contextTimezone:he,browserTimezone:_e,valueFormatPreferences:O,resolveBoundCurrency:$}}function t3({card:e,enabled:t=!0,columnSizing:n,onColumnSizingCommit:r,onResizeStateChange:s}){var S,N;const o=m.useDashboardStore(C=>C.isVisualEditing),{updateCurrentDashboardCard:i}=m.useDashboardActions(),a=m.useEditorStore(C=>{var j;return(j=C.actions)==null?void 0:j.updateColumnSizing}),c=w.useMemo(()=>{var C,j;return n??((j=(C=e==null?void 0:e.preferences)==null?void 0:C.tablePrefs)==null?void 0:j.columnSizing)??{}},[(N=(S=e==null?void 0:e.preferences)==null?void 0:S.tablePrefs)==null?void 0:N.columnSizing,n]),[u,d]=w.useState(c),f=w.useRef(c),h=w.useRef(!1),p=w.useRef(!1),g=w.useRef(null),b=w.useRef({}),x=w.useCallback((C,j)=>{const _=Object.keys(C),k=Object.keys(j);if(_.length!==k.length)return!1;for(const I of _)if(C[I]!==j[I])return!1;return!0},[]);w.useEffect(()=>{!h.current&&c&&(x(c,u)||(f.current=c,d(c)))},[c,x,u]);const y=w.useCallback(C=>{var I;if(!t)return;const j=C||{},k=Object.keys(j).length>0?j:b.current;!k||Object.keys(k).length===0||(r?r(k):o&&a?a(k):i({...e,preferences:{...e.preferences,tablePrefs:{...(I=e.preferences)==null?void 0:I.tablePrefs,columnSizing:k}}}))},[t,o,a,i,e,r]),v=w.useCallback(C=>{h.current||(h.current=!0,s==null||s(!0)),d(j=>{const _=typeof C=="function"?C(j):C;return f.current=_,_&&Object.keys(_).length>0&&(b.current={..._}),_}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,!p.current&&h.current&&(h.current=!1,y(f.current),s==null||s(!1))},0)},[s,y]);return w.useEffect(()=>{if(!t)return;const C=()=>{p.current=!0},j=()=>{p.current=!1,h.current&&(g.current&&(clearTimeout(g.current),g.current=null),h.current=!1,y(f.current),s==null||s(!1))};return window.addEventListener("pointerdown",C),window.addEventListener("mousedown",C),window.addEventListener("touchstart",C),window.addEventListener("pointerup",j),window.addEventListener("mouseup",j),window.addEventListener("touchend",j),window.addEventListener("blur",j),()=>{g.current&&clearTimeout(g.current),window.removeEventListener("pointerdown",C),window.removeEventListener("mousedown",C),window.removeEventListener("touchstart",C),window.removeEventListener("pointerup",j),window.removeEventListener("mouseup",j),window.removeEventListener("touchend",j),window.removeEventListener("blur",j)}},[t,s,y]),{columnSizing:u,onColumnSizingChange:v}}const Th=m.create()(e=>({panels:{dashboard:{isOpen:!1,container:null},editor:{isOpen:!1,container:null}},fullscreen:null,setPanelOpen:(t,n)=>e(r=>r.panels[t].isOpen===n?r:{panels:{...r.panels,[t]:{...r.panels[t],isOpen:n}},fullscreen:!n&&r.fullscreen===t?null:r.fullscreen}),setFullscreen:t=>e(n=>n.fullscreen===t?n:{fullscreen:t}),setContainer:(t,n)=>e(r=>r.panels[t].container===n?r:{panels:{...r.panels,[t]:{...r.panels[t],container:n}}})})),ure=e=>Th(t=>t.panels[e]),dre=()=>Th(e=>e.fullscreen),fre=e=>Th(t=>t.panels[e].container??null);function i9({resolvedCardConfig:e,card:t,row:n}){const r=e||t.config,{groupByColumns:s=[],metricColumns:o=[],detailColumns:i=[]}=r||{},a=t.type==="detailTable",c=a?i:s,u=a?[]:o,d=[];for(const h of c){const p=n.getValue(h.label);p!=null&&d.push({field:h,operator:"=",value:String(p)})}if(d.length===0)return;const f=[];for(const h of u){const p=n.getValue(h.label);p!=null&&f.push({field:h,value:Number(p)})}return{conditions:d,metrics:f.length>0?f:void 0}}function SLe(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,o,i){if(typeof o=="string"){const a=o.charCodeAt(0);if(a>=48&&a<=57){const c=+o;if(Number.isInteger(c)&&c>=0&&c<e){let u=s[c];if(!u){const d=t[c*2];u=s[c]={index:c,key:n(c),start:d,size:t[c*2+1],end:d+t[c*2+1],lane:0}}return u}}if(o==="length")return e}return Reflect.get(s,o,i)}})}function sp(e,t,n){let r=n.initialDeps??[],s,o=!0;function i(){var a;const c=process.env.NODE_ENV!=="production"&&!!n.key&&!!((a=n.debug)!=null&&a.call(n));let u=0;c&&(u=Date.now());const d=e();if(!(d.length!==r.length||d.some((p,g)=>r[g]!==p)))return s;r=d;let h=0;if(c&&(h=Date.now()),s=t(...d),c){const p=Math.round((Date.now()-u)*100)/100,g=Math.round((Date.now()-h)*100)/100,b=g/16,x=(y,v)=>{for(y=String(y);y.length<v;)y=" "+y;return y};console.info(`%c⏱ ${x(g,5)} /${x(p,5)} ms`,`
|
|
790
790
|
font-size: .6rem;
|
|
791
791
|
font-weight: bold;
|
|
792
|
-
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(s),o=!1,s}return i.updateDeps=a=>{r=a},i}function a9(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const CLe=(e,t)=>Math.abs(e-t)<1.01,NLe=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let xx;const iD=()=>{if(xx!==void 0)return xx;if(typeof navigator>"u")return xx=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return xx=!0;const e=navigator.maxTouchPoints;return xx=navigator.platform==="MacIntel"&&e!==void 0&&e>0},l9=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},jLe=e=>e,kLe=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let o=0;o<r;o++)s[o]=t+o;return s},_Le=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:a,height:c}=i;t({width:Math.round(a),height:Math.round(c)})};if(s(l9(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const a=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(l9(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},JN={passive:!0},ILe=typeof window>"u"?!0:"onscrollend"in window,TLe=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const o=e.options.useScrollendEvent&&ILe;let i=0;const a=o?null:NLe(s,()=>t(i,!1),e.options.isScrollingResetDelay),c=f=>()=>{i=n(r),a==null||a(),t(i,f)},u=c(!0),d=c(!1);return r.addEventListener("scroll",u,JN),o&&r.addEventListener("scrollend",d,JN),()=>{r.removeEventListener("scroll",u),o&&r.removeEventListener("scrollend",d)}},ELe=(e,t)=>TLe(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),DLe=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),o=n.itemSizeCache.get(s);if(o!==void 0)return o}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},MLe=(e,{adjustments:t=0,behavior:n},r)=>{var s,o;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},ALe=MLe;class RLe{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const i=()=>{const a=o.target,c=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);for(const[u,d]of this.elementsCache)if(d===a){this.elementsCache.delete(u);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(a,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:jLe,rangeExtractor:kLe,onChange:()=>{},measureElement:DLe,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in n){const p=n[h];p!==void 0&&(o[h]=p)}const i=this.options;let a=null,c=null,u=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,p=o.count,g=this.getMeasurements(),b=h>0?((r=g[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((s=g[h-1])==null?void 0:s.key)??i.getItemKey(h-1):null;if(p!==h||h>0&&p>0&&(o.getItemKey(0)!==b||o.getItemKey(p-1)!==x)){u=!0;const S=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??g[0]:null;S&&(a=[S.key,this.getScrollOffset()-S.start]);const N=o.followOnAppend===!0?"auto":o.followOnAppend||null;N&&p>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(p-1)!==x)&&(c=N)}}this.options=o,u&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(a&&this.scrollOffset!==null){const[h,p]=a,g=this.getMeasurements(),{count:b,getItemKey:x}=this.options;let y=0;for(;y<b&&x(y)!==h;)y++;if(y<b){const v=g[y];if(v){const S=v.start+p;S!==this.scrollOffset&&(f=S-this.scrollOffset,this.scrollOffset=S,d=!0)}}}(d||c)&&(this.pendingScrollAnchor=[d?a[0]:null,d?a[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=sp(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:process.env.NODE_ENV!=="production"&&"maybeNotify",debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const a=this.getScrollOffset();this.scrollDirection=i?a===o?this.scrollDirection:a<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},a=()=>{this._iosTouching=!1,!(!iD()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,JN),o.addEventListener("touchend",a,JN),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",a),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[o,i,a,c]=s;o!==null&&!a&&(iD()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),a&&this.scrollToEnd({behavior:a})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=sp(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,s,o,i,a,c,u)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i,lanes:a,laneAssignmentMode:c,gap:u}),{key:!1}),this.getMeasurements=sp(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i,lanes:a,laneAssignmentMode:c,gap:u},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),a===1){const y=n*2;let v=this._flatMeasurements;if(!v||v.length<y){const C=new Float64Array(y);v&&h>0&&C.set(v.subarray(0,h*2)),v=C,this._flatMeasurements=v}let S;if(h===0)S=r+s;else{const C=h-1;S=v[C*2]+v[C*2+1]+u}for(let C=h;C<n;C++){const j=o(C),_=f.get(j),k=typeof _=="number"?_:this.options.estimateSize(C);v[C*2]=S,v[C*2+1]=k,S+=k+u}const N=SLe(n,v,o);return this.measurementsCache=N,N}const p=this.measurementsCache.slice(0,h),g=new Array(a).fill(void 0),b=new Float64Array(a);let x=0;for(let y=0;y<h;y++){const v=p[y];v&&(g[v.lane]===void 0&&x++,g[v.lane]=y,b[v.lane]=v.end)}for(let y=h;y<n;y++){const v=o(y),S=this.laneAssignments.get(y);let N,C;const j=c==="estimate"||f.has(v);if(S!==void 0&&this.options.lanes>1){N=S;const T=g[N],E=T!==void 0?p[T]:void 0;C=E?E.end+u:r+s}else if(x===a){let T=0,E=b[0],D=g[0];for(let M=1;M<a;M++){const A=b[M];(A<E||A===E&&g[M]<D)&&(T=M,E=A,D=g[M])}N=T,C=E+u,j&&this.laneAssignments.set(y,N)}else N=y%this.options.lanes,C=r+s,j&&this.laneAssignments.set(y,N);const _=f.get(v),k=typeof _=="number"?_:this.options.estimateSize(y),I=C+k;p[y]={index:y,start:C,size:k,end:I,key:v,lane:N},g[N]===void 0&&x++,g[N]=y,b[N]=I}return this.measurementsCache=p,p},{key:process.env.NODE_ENV!=="production"&&"getMeasurements",debug:()=>this.options.debug}),this.calculateRange=sp(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>n.length===0||r===0?(this.range=null,null):(this.range=FLe(n,r,s,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:process.env.NODE_ENV!=="production"&&"calculateRange",debug:()=>this.options.debug}),this.getVirtualIndexes=sp(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,i)=>o===null||i===null?[]:n({startIndex:o,endIndex:i,overscan:r,count:s}),{key:process.env.NODE_ENV!=="production"&&"getVirtualIndexes",debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-o),a=Math.min(this.options.count-1,s+o);return n>=i&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((i,a)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(a))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),o=this.elementsCache.get(s);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,o;if(n<0||n>=this.options.count)return;let i,a,c;const u=this._flatMeasurements;if(this.options.lanes===1&&u!==null)c=this.options.getItemKey(n),a=u[n*2],i=u[n*2+1];else{const h=this.measurementsCache[n];if(!h)return;c=h.key,a=h.start,i=h.size}const d=this.itemSizeCache.get(c)??i,f=r-d;if(f!==0){const h=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,p=h?this.getTotalSize():0,g=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:a,size:i,end:a+i,lane:0},f,this):a<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(c)||this.scrollDirection!=="backward"));(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-p):g&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=sp(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,i=n.length;o<i;o++){const a=n[o],c=r[a];s.push(c)}return s},{key:process.env.NODE_ENV!=="production"&&"getVirtualItems",debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,o=this.options.lanes===1&&s!=null,i=hre(0,r.length-1,o?a=>s[a*2]:a=>a9(r[a]).start,n);return a9(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=o+s-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,i.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[i,a]=o,c=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?s=i[o*2]+i[o*2+1]:s=((n=r[o])==null?void 0:n.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(a=>a===null);){const a=r[i];o[a.lane]===null&&(o[a.lane]=a.end),i--}s=Math.max(...o.filter(a=>a!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(process.env.NODE_ENV!=="production"&&this.options.debug&&console.info("correction",t),iD()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&CLe(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const a=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),u=this.scrollState.behavior==="smooth"&&c>a;this.scrollState.lastTargetOffset=s,u||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:u?"smooth":"auto"})}this.scheduleScrollReconcile()}}const hre=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,o=n(s);if(o<r)e=s+1;else if(o>r)t=s-1;else return s}return e>0?e-1:0};function PLe(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,o=e[s*2];if(o<n)r=s+1;else if(o>n)t=s-1;else return s}return r>0?r-1:0}function FLe(e,t,n,r,s){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&s!==null){const u=PLe(s,o,n);let d=u;const f=n+t;for(;d<o&&s[d*2]+s[d*2+1]<f;)d++;return{startIndex:u,endIndex:d}}let a=hre(0,o,u=>e[u].start,n),c=a;if(r===1)for(;c<o&&e[c].end<n+t;)c++;else if(r>1){const u=Array(r).fill(0);for(;c<o&&u.some(f=>f<n+t);){const f=e[c];u[f.lane]=f.end,c++}const d=Array(r).fill(n+t);for(;a>=0&&d.some(f=>f>=n);){const f=e[a];d[f.lane]=f.start,a--}a=Math.max(0,a-a%r),c=Math.min(o,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const aD=typeof document<"u"?te.useLayoutEffect:te.useEffect;function OLe({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=te.useReducer(u=>u+1,0)[1],o=te.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const i=u=>{const d=o.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=u.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!u.options.horizontal,p=d.mode==="transform",g=h?"left":"top",b=u.options.scrollMargin,x=u.getVirtualItems();for(const y of x){const v=y.start-b,S=u.elementsCache.get(y.key);S&&d.lastPositions.get(S)!==v&&(d.lastPositions.set(S,v),p?S.style.transform=h?`translate3d(${v}px, 0, 0)`:`translate3d(0, ${v}px, 0)`:S.style[g]=`${v}px`)}},a={...r,onChange:(u,d)=>{var f;const h=o.current;let p=!0;if(h.enabled){i(u);const g=u.range,b=h.prevRange;p=!b||b.isScrolling!==u.isScrolling||b.startIndex!==(g==null?void 0:g.startIndex)||b.endIndex!==(g==null?void 0:g.endIndex),p&&(h.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:u.isScrolling}:null)}p&&(e&&d?Dr.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=te.useState(()=>{const u=new RLe(a);return Object.assign(u,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=u.getTotalSize();f.lastSize=h;const p=u.options.horizontal?"width":"height";d.style[p]=`${h}px`}}})});return c.setOptions(a),aD(()=>c._didMount(),[]),aD(()=>c._willUpdate()),aD(()=>{i(c)}),c}function X_(e){return OLe({observeElementRect:_Le,observeElementOffset:ELe,scrollToFn:ALe,...e})}function LLe(e){if(!e)return!1;const t=/Safari/i.test(e),n=/Chrome|Chromium|CriOS|Edg|OPR|Firefox|FxiOS|Android/i.test(e);return t&&!n}function n3(){return typeof navigator>"u"?!1:LLe(navigator.userAgent)}const $Le={compact:"compact",comfortable:"comfortable",spacious:"spacious"};function Q_(e,t,n="appearance"){const{compiledAppearance:r}=m.useAppearance();return w.useMemo(()=>zLe({compiledAppearance:r,surface:e,cardDensity:t,layoutScope:n}),[t,r,n,e])}function zLe({compiledAppearance:e,surface:t,cardDensity:n,layoutScope:r="appearance"}){var R,q,W,F,Z,K,Y,X,z,B,H,L,G,J,oe,Q,ae,ie,le,ue,fe,pe,ge,de,ye,ce,re,ee,se,ne,he,_e,Le,Ue,je,Xe,Ze,at,Be,lt,Te,nt,Oe,He,qe,Ae,Qe,ct,It,yt,kt;const s=ULe(e,t),o=e.scheme.tokens,i=r==="document",a=n??WLe(HLe(s)),c=zPe(a),u=((R=s.container)==null?void 0:R.borderRadius)??((q=o==null?void 0:o.radius)==null?void 0:q.table)??((W=o==null?void 0:o.radius)==null?void 0:W.card),d=(F=o==null?void 0:o.radius)==null?void 0:F.control,f=VLe(e),h=i?void 0:((Z=s.cell)==null?void 0:Z.paddingX)??f,p=BLe(e),g=i||n?void 0:((K=s.cell)==null?void 0:K.paddingY)??p,b=to({backgroundColor:(Y=s.container)==null?void 0:Y.background,borderColor:(X=s.container)==null?void 0:X.borderColor,borderRadius:u,boxShadow:(z=s.container)==null?void 0:z.shadow}),x=to({backgroundColor:(B=s.header)==null?void 0:B.background,color:(H=s.header)==null?void 0:H.foreground,borderColor:(L=s.header)==null?void 0:L.dividerColor}),y=to({backgroundColor:(G=s.header)==null?void 0:G.background,color:(J=s.header)==null?void 0:J.foreground,borderColor:(oe=s.header)==null?void 0:oe.dividerColor,paddingLeft:h,paddingRight:h,fontWeight:(Q=s.header)==null?void 0:Q.fontWeight,textTransform:((ae=s.header)==null?void 0:ae.uppercase)===void 0?void 0:s.header.uppercase?"uppercase":"none"}),v=to({backgroundColor:(ie=s.header)==null?void 0:ie.dividerColor}),S=((le=s.header)==null?void 0:le.uppercase)===!1?"normal-case semaphor-table-header-normal-case":void 0,N=((ue=s.header)==null?void 0:ue.sticky)!==!1,C=i||(fe=s.cell)==null?void 0:fe.wrap,j=C==="wrap",_=i||(pe=s.row)==null?void 0:pe.height,k=to({borderColor:(ge=s.row)==null?void 0:ge.dividerColor,height:_}),I=to({backgroundColor:((de=s.row)==null?void 0:de.zebraBackground)??((ye=o==null?void 0:o.color)==null?void 0:ye.muted)}),T=(ce=s.row)!=null&&ce.hoverBackground?"semaphor-table-row-hover-background":void 0,E=to({paddingLeft:h,paddingRight:h,paddingTop:g,paddingBottom:g,verticalAlign:(re=s.cell)==null?void 0:re.verticalAlign,whiteSpace:C===void 0?void 0:C==="wrap"?"normal":"nowrap",overflowWrap:C==="wrap"?"anywhere":void 0}),D=to({overflow:j?void 0:"hidden",textOverflow:j?void 0:"ellipsis"}),M=to({borderBottomColor:(ee=s.row)==null?void 0:ee.dividerColor}),A=j?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap",P=to({backgroundColor:(se=s.subtotal)==null?void 0:se.background,color:(ne=s.subtotal)==null?void 0:ne.foreground,fontWeight:(he=s.subtotal)==null?void 0:he.fontWeight,borderColor:(_e=s.row)==null?void 0:_e.dividerColor}),O=to({backgroundColor:(Le=s.subtotal)==null?void 0:Le.background,color:(Ue=s.subtotal)==null?void 0:Ue.foreground,fontWeight:(je=s.subtotal)==null?void 0:je.fontWeight}),$=to({backgroundColor:(Xe=s.grandTotal)==null?void 0:Xe.background,color:(Ze=s.grandTotal)==null?void 0:Ze.foreground,fontWeight:(at=s.grandTotal)==null?void 0:at.fontWeight,borderColor:((Be=s.grandTotal)==null?void 0:Be.borderColor)??((lt=s.row)==null?void 0:lt.dividerColor)}),V=to({backgroundColor:(Te=s.grandTotal)==null?void 0:Te.background,color:(nt=s.grandTotal)==null?void 0:nt.foreground,fontWeight:(Oe=s.grandTotal)==null?void 0:Oe.fontWeight,borderColor:(He=s.grandTotal)==null?void 0:He.borderColor}),U={containerStyle:to({backgroundColor:(qe=s.pagination)==null?void 0:qe.background,color:(Ae=s.pagination)==null?void 0:Ae.foreground,borderColor:(Qe=s.pagination)==null?void 0:Qe.borderColor}),controlStyle:to({borderColor:(ct=s.pagination)==null?void 0:ct.borderColor,borderRadius:d,color:(It=s.pagination)==null?void 0:It.foreground}),textStyle:to({color:(yt=s.pagination)==null?void 0:yt.foreground})};return{densitySpec:c,containerStyle:b,headerStyle:x,headerCellStyle:y,headerDividerStyle:v,dataRowStyle:k,dataRowClassName:T,cellStyle:E,rowDividerCellStyle:M,subtotalRowStyle:P,subtotalCellStyle:O,grandTotalRowStyle:$,grandTotalCellStyle:V,pagination:U,headerTextClassName:S,isHeaderSticky:N,dataRowHeight:_,stripedDataRowStyle:I,cellOverflowStyle:D,cellContentClassName:A,isCellWrapping:j,hasHoverRowStyle:!!((kt=s.row)!=null&&kt.hoverBackground),getDataRowStyle:(Mt,vt)=>{var Pe,Fe,Ge;const St=vt!=null&&vt.isSelected?(Pe=s.row)==null?void 0:Pe.selectedBackground:void 0,ke=(Fe=s.row)!=null&&Fe.zebra&&Mt%2===1&&!(vt!=null&&vt.isSelected)&&!(vt!=null&&vt.suppressZebra)?s.row.zebraBackground:void 0,Ee=(Ge=s.row)!=null&&Ge.hoverBackground?{"--semaphor-table-row-hover-background":s.row.hoverBackground}:{};return to({...k,...Ee,backgroundColor:St??ke})}}}function BLe(e){var r,s,o,i;const t=(s=(r=e.scheme.tokens)==null?void 0:r.spacing)==null?void 0:s.tableCellY,n=(i=(o=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens)==null?void 0:o.spacing)==null?void 0:i.tableCellY;return t!==void 0&&t!==n?t:void 0}function VLe(e){var r,s,o,i;const t=(s=(r=e.scheme.tokens)==null?void 0:r.spacing)==null?void 0:s.tableCellX,n=(i=(o=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens)==null?void 0:o.spacing)==null?void 0:i.tableCellX;return t!==void 0&&t!==n?t:void 0}function HLe(e){var n,r;const t=(r=(n=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes.light.components)==null?void 0:n.table)==null?void 0:r.density;return e.density!==void 0&&e.density!==t?e.density:void 0}function ULe(e,t){var s,o;const n=e.table,r=t==="table"?(s=e.scheme.components)==null?void 0:s.table:(o=e.scheme.components)==null?void 0:o[t];return qLe(n,r)}function qLe(e,t){return{density:(t==null?void 0:t.density)??(e==null?void 0:e.density),container:{...e==null?void 0:e.container,...t==null?void 0:t.container},header:{...e==null?void 0:e.header,...t==null?void 0:t.header},row:{...e==null?void 0:e.row,...t==null?void 0:t.row},cell:{...e==null?void 0:e.cell,...t==null?void 0:t.cell},subtotal:{...e==null?void 0:e.subtotal,...t==null?void 0:t.subtotal},grandTotal:{...e==null?void 0:e.grandTotal,...t==null?void 0:t.grandTotal},pagination:{...e==null?void 0:e.pagination,...t==null?void 0:t.pagination}}}function WLe(e){return e?$Le[e]:"compact"}function to(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}function GLe({tableAppearance:e,className:t,style:n}){return{style:{...e.headerCellStyle,...n},className:m.cn(t,e.densitySpec.header,e.headerTextClassName)}}function Eh({tableAppearance:e,className:t,style:n,divider:r="none",overflow:s="clip",textFlow:o="content"}){return r3({tableAppearance:e,className:t,style:{...r==="row"?e.rowDividerCellStyle:void 0,...n},overflow:s,textFlow:o})}function hd({tableAppearance:e,className:t,style:n,divider:r="none",overflow:s="clip",textFlow:o="content"}){return r3({tableAppearance:e,className:t,style:{...e.subtotalCellStyle,...r==="row"?e.rowDividerCellStyle:void 0,...n},overflow:s,textFlow:o})}function Vc({tableAppearance:e,className:t,style:n,overflow:r="clip"}){return r3({tableAppearance:e,className:t,style:{...e.grandTotalCellStyle,...n},overflow:r,textFlow:"direct"})}function Dh(e,t,n){return(n==null?void 0:n.textFlow)==="delegate"?m.cn(t):m.cn(t,e.cellContentClassName)}function r3({tableAppearance:e,className:t,style:n,overflow:r,textFlow:s}){const o=r==="clip";return{style:{...e.cellStyle,...n,...o?e.cellOverflowStyle:void 0},className:m.cn(t,o&&!e.isCellWrapping&&"overflow-hidden",s==="direct"&&!e.isCellWrapping&&"whitespace-nowrap",e.densitySpec.rowPad,e.densitySpec.cell)}}function s3({displayMode:e,isVisualEditing:t=!1,printBehavior:n="table-print-only",renderPlainWrapper:r=!1}){const s=n==="any-print"?nf(e):Wk(e),o=s?"document-print":t?"editor":"dashboard",i=!s;return{mode:o,isInteractive:i,isPrint:s,allowStickyHeader:i,allowPagination:i,allowVirtualization:i,allowRowSpan:i,showEditorControls:i&&t,usePlainWrapper:s||r}}const mre=["spacious","comfortable","standard","compact","dense"],KLe={spacious:"Spacious",comfortable:"Comfortable",standard:"Standard",compact:"Compact",dense:"Dense"},pre=["plain","filled","accent"],YLe={plain:"Plain",filled:"Filled",accent:"Accent"},gre=["full","outer","inner","horizontal","vertical","top","right","bottom","left","none"],ZLe={none:"None",outer:"Outer",inner:"Inner",horizontal:"Horizontal",vertical:"Vertical",top:"Top",right:"Right",bottom:"Bottom",left:"Left",full:"Full"},Nd={density:"compact",headerStyle:"filled",headerWrapText:!1,stripedRows:!1,gridLines:"horizontal",wrapText:!1},bre=["normal","medium","semibold","bold"],XLe={normal:"Normal",medium:"Medium",semibold:"Semibold",bold:"Bold"},QLe=["solid","dashed","dotted","double"],JLe={solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double"},ha={enabled:!1,backgroundColor:"#fafafa",textColor:"#18181b",fontWeight:"medium",borderTop:!0,borderTopStyle:"solid",borderTopColor:"#e4e4e7"},xre={plain:{background:"#ffffff",color:"#3f3f46"},filled:{background:"#f4f4f5",color:"#27272a"},accent:{background:"#eef2ff",color:"#312e81"}};function e3e(e){return mre.includes(e)?e:Nd.density}function t3e(e){return pre.includes(e)?e:Nd.headerStyle}function n3e(e){return gre.includes(e)?e:Nd.gridLines}function r3e(e){return bre.includes(e)?e:ha.fontWeight}function s3e(e){return e==="solid"||e==="dashed"||e==="dotted"||e==="double"?e:ha.borderTopStyle}function o3(e){const t=e==null?void 0:e.tableStyle,n=t3e(t==null?void 0:t.headerStyle),r=xre[n],s=t==null?void 0:t.totals;return{density:e3e(e==null?void 0:e.density),headerStyle:n,headerBackgroundColor:(t==null?void 0:t.headerBackgroundColor)??r.background,headerTextColor:(t==null?void 0:t.headerTextColor)??r.color,headerWrapText:(t==null?void 0:t.headerWrapText)??Nd.headerWrapText,stripedRows:(t==null?void 0:t.stripedRows)??Nd.stripedRows,gridLines:n3e(t==null?void 0:t.gridLines),wrapText:(t==null?void 0:t.wrapText)??Nd.wrapText,totalsStyle:{enabled:(s==null?void 0:s.enabled)??ha.enabled,backgroundColor:(s==null?void 0:s.backgroundColor)??ha.backgroundColor,textColor:(s==null?void 0:s.textColor)??ha.textColor,fontWeight:r3e(s==null?void 0:s.fontWeight),borderTop:(s==null?void 0:s.borderTop)??ha.borderTop,borderTopStyle:s3e(s==null?void 0:s.borderTopStyle),borderTopColor:(s==null?void 0:s.borderTopColor)??ha.borderTopColor}}}function yre(e){switch(e){case"normal":return 400;case"medium":return 500;case"semibold":return 600;case"bold":return 700;default:return 500}}function o3e(e){return e==="double"?3:1}function i3e(e){switch(e){case"none":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"outer":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"inner":return"[&_tr]:border-b [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"vertical":return"[&_tr]:!border-b-0 [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"top":case"right":case"bottom":case"left":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"full":return"[&_tr]:border-b [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"horizontal":default:return"[&_tr]:border-b [&_th]:!border-r-0 [&_td]:!border-r-0"}}function a3e(e){if(!e)return"border border-border/60";switch(e){case"full":case"outer":return"border border-border/60";case"top":return"border-t border-border/60";case"right":return"border-r border-border/60";case"bottom":return"border-b border-border/60";case"left":return"border-l border-border/60";case"inner":case"horizontal":case"vertical":case"none":default:return"border-0"}}function l3e(e){return e?e==="full"||e==="inner"||e==="horizontal":!0}function c9(e){return e.mode==="clickFilter"}function c3e(e,t){if(!t||t.type==="metric")return e;if(t.type==="attribute"){const n=e.find(r=>r.field.id===t.field.id);return n?[n]:[]}return e}function u3e({children:e,className:t,scrollAreaRef:n,style:r,usePlainWrapper:s}){return s?l.jsx("div",{className:t,style:r,children:e}):l.jsxs(il,{ref:n,className:t,style:r,children:[e,l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-20"})]})}function d3e(e){var Ge,Pt,_t,Ft,Vt,Ht,Qn;const{card:t,isLoading:n,frameId:r,sheetId:s,onMultipleInteractions:o,onColumnReorder:i}=e,a=w.useRef(null),c=w.useRef(!1),u=w.useRef(!1),{columnSizing:d,onColumnSizingChange:f}=t3({card:t,columnSizing:e.columnSizing,onColumnSizingCommit:e.onColumnSizingChange,onResizeStateChange:e.onColumnResizeStateChange}),h=m.useDashboardStore(st=>st.isVisualEditing),{updatePageSize:p}=m.useEditorActions(),{displayPreferences:g,shouldShowElement:b}=sl(),x=s3({displayMode:g.mode,isVisualEditing:h}),y=x.showEditorControls&&!!i&&Yh(t),v=x.showEditorControls||e.showColumnResizeHandles,S=x.isPrint,N=Q_("table",(Pt=(Ge=t==null?void 0:t.preferences)==null?void 0:Ge.tablePrefs)==null?void 0:Pt.density,x.mode==="document-print"?"document":"appearance"),C=w.useMemo(()=>{var st;return o3((st=t==null?void 0:t.preferences)==null?void 0:st.tablePrefs)},[(_t=t==null?void 0:t.preferences)==null?void 0:_t.tablePrefs]),j=(Vt=(Ft=t==null?void 0:t.preferences)==null?void 0:Ft.tablePrefs)==null?void 0:Vt.tableStyle,_=!!(j!=null&&j.headerStyle||j!=null&&j.headerBackgroundColor||j!=null&&j.headerTextColor),k=(j==null?void 0:j.gridLines)!==void 0,I=(j==null?void 0:j.stripedRows)!==void 0,T=j==null?void 0:j.totals,E=!!(T!=null&&T.backgroundColor||T!=null&&T.textColor||T!=null&&T.fontWeight||(T==null?void 0:T.borderTop)!==void 0||T!=null&&T.borderTopStyle||T!=null&&T.borderTopColor),D=k?C.gridLines:void 0,M=_?{backgroundColor:C.headerBackgroundColor,color:C.headerTextColor}:void 0,A=E?{backgroundColor:C.totalsStyle.backgroundColor,color:C.totalsStyle.textColor,fontWeight:yre(C.totalsStyle.fontWeight),borderTopWidth:C.totalsStyle.borderTop?o3e(C.totalsStyle.borderTopStyle):0,borderTopStyle:C.totalsStyle.borderTopStyle,borderTopColor:C.totalsStyle.borderTopColor}:void 0,P=l3e(D),O=C.totalsStyle.enabled===!0,$=w.useMemo(()=>m.getInteractions(t.interactionConfig),[t.interactionConfig]),V=w.useMemo(()=>$.filter(c9),[$]),U=V.length>0,{table:R,columnSettingsToUse:q,getRowStyle:W,activeColumnId:F,activeColumnSettings:Z,activeColumnBaseStyle:K,handleColumnSettingsChange:Y,handleColumnBaseStyleChange:X,resetColumnSettings:z,resetAllColumnSettings:B,columnSettingsOpen:H,columns:L,setColumnSettingsOpen:G,totalColumns:J,totalRows:oe,paginationMode:Q,paginationMetadata:ae,contextTimezone:ie,browserTimezone:le,valueFormatPreferences:ue,resolveBoundCurrency:fe}=cre({...e,columnSizing:d,onColumnSizingChange:f,headerTextClassName:N.headerTextClassName,headerWrapText:C.headerWrapText,appearanceWrapText:N.isCellWrapping?!0:void 0,defaultSelectColumnVisible:U&&x.isInteractive}),pe=m.useResolvedCardConfig(t),{handlePointerInteraction:ge}=m.useEventEngine(t,r||"",s||"",o),de=w.useMemo(()=>$.some(st=>st.trigger!==void 0&&st.mode!=="clickFilter"),[$]),ye=w.useMemo(()=>n3(),[]),ce=w.useMemo(()=>typeof document<"u"&&"onscrollend"in document,[]),re=w.useMemo(()=>C.wrapText||Object.values(q??{}).some(st=>(st==null?void 0:st.textWrap)==="wrap"||(st==null?void 0:st.textWrap)==="preserve"),[q,C.wrapText]),ee=R.getRowModel().rows,se=R.getFilteredSelectedRowModel().rows,ne=se.length>0,he=R.getFilteredRowModel().rows,_e=w.useMemo(()=>e.totalsData?e.totalsData.map(st=>({original:st})):he,[he,e.totalsData]),Le=R.getVisibleLeafColumns(),[Ue,je]=w.useState(null),[Xe,Ze]=w.useState(null),at=()=>{const st=BPe({currentOrder:R.getAllLeafColumns().map(De=>De.id),draggingColId:Ue,dropTarget:Xe});if(st){if(!((i==null?void 0:i({draggingColumnId:Ue,targetColumnId:Xe.colId,side:Xe.side}))??!0)){je(null),Ze(null);return}R.setColumnOrder(st)}je(null),Ze(null)},Be=w.useMemo(()=>e.totalsByColumnId??(Q==="server"?{}:O?_te({rows:_e,columns:Le,columnSettings:q}):{}),[q,O,Q,e.totalsByColumnId,_e,Le]),lt=Object.keys(Be).length>0,Te=w.useMemo(()=>w5(t,Le.map(st=>st.id)),[t,Le]),nt=!S&&Yh(t),Oe=w.useMemo(()=>{var st,De;return ky((De=(st=t==null?void 0:t.preferences)==null?void 0:st.tablePrefs)==null?void 0:De.baseFormatting)},[(Qn=(Ht=t==null?void 0:t.preferences)==null?void 0:Ht.tablePrefs)==null?void 0:Qn.baseFormatting]),He=(st,De)=>{var Kt;const mt=q[st],Ct=x1e({textWrap:mt==null?void 0:mt.textWrap,appearanceWrapText:N.isCellWrapping});return EX({formatting:Oe,compatibility:{columnSettings:mt,tablePreferences:(Kt=t==null?void 0:t.preferences)==null?void 0:Kt.tablePrefs,...Ct},columnId:st,tablePart:De})},qe=(st,De,mt)=>{try{const Ct=jm(t,{columnId:st}),Kt=Jl({card:t,columnKey:st,metricId:Ct==null?void 0:Ct.id}),Bt=Kt?fe(Kt):void 0,Xt=kg({card:t,columnId:st,resolvedSettings:mt,metricId:Ct==null?void 0:Ct.id,valueFormatPreferences:ue,boundCurrency:Bt});return Xt?In.formatNumericCanonical(De,Xt):mt!=null&&mt.numberFormat?In.formatNumberWithColumnSettings(De,mt.numberFormat,mt.numberFormat.locale||"en-US"):De.toLocaleString()}catch{return De.toLocaleString()}},Qe=x.allowVirtualization&&ee.length>75,ct=N.isCellWrapping,It=Qe&&(!ye||re||ct),yt=X_({count:Qe?ee.length:0,getScrollElement:()=>a.current,estimateSize:()=>N.dataRowHeight??42,overscan:ye?5:10,useScrollendEvent:ye&&ce,isScrollingResetDelay:ye?240:150}),kt=Qe?yt.getVirtualItems():[],Mt=Qe&&kt.length>0?kt[0].start:0,vt=Qe&&kt.length>0?yt.getTotalSize()-kt[kt.length-1].end:0,St=Math.max(L.length,1),ke=m.useInteractionStore(st=>st.interactionStates[t.id]);w.useEffect(()=>{const st=(ke==null?void 0:ke.appliedClickFilters)||[],De=R.getFilteredSelectedRowModel().rows.length;st.length===0&&De>0&&R.resetRowSelection()},[ke==null?void 0:ke.appliedClickFilters,R]);const Ee=w.useRef(""),Pe=R.getState().rowSelection;w.useEffect(()=>{if(!U||!r||!s)return;const st=JSON.stringify(Pe);if(st===Ee.current)return;Ee.current=st;const De=se.map(mt=>{var Se;const Ct=i9({resolvedCardConfig:pe,card:t,row:mt});if(!Ct)return null;const Bt=m.findAllMatchingV2Interactions($,{conditions:Ct.conditions,metrics:Ct.metrics}).find(c9)??V[0];if(!Bt)return null;const Xt=c3e(Ct.conditions,Bt.trigger);return{interactionMode:"clickFilter",sourceCardId:t.id,filterGroups:[{filters:Xt}],metric:(Se=Ct.metrics)==null?void 0:Se[0],applyToCardIds:Bt.applyToCardIds,excludeCardIds:Bt.excludeCardIds}}).filter(mt=>!!mt);m.useInteractionStore.getState().setInteractionState(t.id,{...ke??m.createInitialInteractionState(),appliedClickFilters:De})},[t,t.id,V,se,r,U,ke,$,pe,Pe,s]);const Fe=(st,De)=>{if(st.stopPropagation(),!de||!r||!s)return;const mt=i9({resolvedCardConfig:pe,card:t,row:De});mt&&ge({context:mt,gesture:"leftClick",modifierKeys:{shift:st.shiftKey,ctrl:st.ctrlKey,meta:st.metaKey},position:{x:st.clientX,y:st.clientY}})};return l.jsx(m.TooltipProvider,{children:l.jsxs("div",{onMouseDown:st=>st.stopPropagation(),className:m.cn("flex w-full flex-col",!h&&"gap-2"),children:[l.jsx(u3e,{scrollAreaRef:a,style:N.containerStyle,usePlainWrapper:x.usePlainWrapper,className:m.cn("data-table-scroll-container relative h-full rounded-none bg-muted/20",a3e(D),S&&"border-gray-300 print:border-gray-400"),children:l.jsxs("table",{className:m.cn("w-full text-sm [border-spacing:0]",S&&"print:break-inside-avoid",D&&i3e(D)),"data-table-type":"data","data-total-rows":oe,"data-total-columns":J,children:[l.jsx(Pm,{style:{...N.headerStyle,...M},className:m.cn("[&_tr]:border-b-0",!S&&"bg-muted",S&&"bg-gray-50 text-foreground print:table-header-group print:bg-gray-100"),children:R.getHeaderGroups().map(st=>l.jsx(Or,{children:st.headers.map((De,mt)=>{const Ct=mt===st.headers.length-1,Kt=y&&De.column.id!=="select",Bt=Ue===De.column.id,Xt=(Xe==null?void 0:Xe.colId)===De.column.id,Yn=De.column.columnDef.meta,Se=GLe({tableAppearance:N,style:{width:De.getSize(),minWidth:De.getSize(),maxWidth:Ct?void 0:De.getSize(),position:S?"relative":void 0,transition:"none",...He(De.column.id,"header"),...M},className:m.cn("h-auto border-b border-transparent px-4 py-2 align-middle font-medium uppercase tracking-[0.08em] text-muted-foreground",!S&&"relative bg-muted/95",x.allowStickyHeader&&N.isHeaderSticky&&"sticky top-0 z-10 supports-[backdrop-filter]:bg-muted/80 supports-[backdrop-filter]:backdrop-blur-sm",S&&"text-foreground/90 print:bg-gray-100",Bt&&"opacity-40")});return l.jsxs(hs,{colSpan:De.colSpan,"data-column-id":De.id,draggable:Kt,onMouseDownCapture:Ne=>{var tt,At;const Ve=Ne.target;c.current=!!((tt=Ve.closest)!=null&&tt.call(Ve,"[data-resize-handle]")),u.current=!!((At=Ve.closest)!=null&&At.call(Ve,"[data-grip-handle]"))},onDragStart:Ne=>{if(Kt){if(c.current||!u.current){Ne.preventDefault();return}Ne.dataTransfer.effectAllowed="move",Ne.dataTransfer.setData("text/column-id",De.column.id),je(De.column.id)}},onDragOver:Ne=>{if(!y||!Ue||Ue===De.column.id||De.column.id==="select")return;Ne.preventDefault();const Ve=Ne.currentTarget.getBoundingClientRect(),tt=Ve.left+Ve.width/2,At={colId:De.column.id,side:Ne.clientX<tt?"before":"after"};Ze($t=>($t==null?void 0:$t.colId)===At.colId&&$t.side===At.side?$t:At)},onDrop:Ne=>{y&&(Ne.preventDefault(),at())},onDragEnd:()=>{je(null),Ze(null)},style:Se.style,className:m.cn(Se.className,(Yn==null?void 0:Yn.isNumeric)&&"numeric"),children:[!S&&P&&l.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 bottom-0 h-px bg-border",style:N.headerDividerStyle}),De.isPlaceholder?null:l.jsxs(l.Fragment,{children:[Xt&&(Xe==null?void 0:Xe.side)==="before"&&l.jsx("div",{className:"pointer-events-none absolute -left-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),Xt&&(Xe==null?void 0:Xe.side)==="after"&&l.jsx("div",{className:"pointer-events-none absolute -right-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),l.jsx("span",{className:"block",children:pi(De.column.columnDef.header,De.getContext())}),v&&l.jsx(Kf,{header:De,isResizing:De.column.getIsResizing(),inset:Ct})]})]},De.id)})},st.id))}),l.jsx($d,{children:ee.length?l.jsxs(l.Fragment,{children:[Qe&&Mt>0&&l.jsx(Or,{"aria-hidden":!0,className:"pointer-events-none border-none hover:bg-transparent",children:l.jsx(Wn,{colSpan:St,style:{height:Mt,padding:0,border:"none"}})}),(Qe?kt:ee).map((st,De)=>{const mt=Qe?st.index:De,Ct=Qe?ee[st.index]:st;if(!Ct)return null;const Kt=Ct.getIsSelected();return l.jsx(Or,{ref:It?yt.measureElement:void 0,onClick:x.isInteractive?Bt=>Fe(Bt,Ct):void 0,"data-index":Qe?mt:De,"data-state":Kt?"selected":void 0,style:{...N.getDataRowStyle(mt,{isSelected:Kt,suppressZebra:I}),...I&&C.stripedRows&&mt%2===1&&!Kt?N.stripedDataRowStyle:null,...W(Ct)},className:m.cn("border-border/40",(ye||N.hasHoverRowStyle)&&"!transition-none",!ye&&!N.hasHoverRowStyle&&"transition-colors duration-150",N.dataRowClassName,Kt?"bg-primary/12 border-primary/50 hover:bg-primary/15":ne?"opacity-55 hover:opacity-70":"hover:bg-muted/40",S&&"border-gray-300 print:break-inside-avoid print:border-gray-400",x.isInteractive&&de&&"cursor-pointer"),children:Ct.getVisibleCells().map((Bt,Xt,Yn)=>{var Fn,Re,rt,pt;const Se=Xt===Yn.length-1,Ne=Eh({tableAppearance:N,style:{width:Bt.column.getSize(),minWidth:Bt.column.getSize(),maxWidth:Se?void 0:Bt.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90",S&&"border-gray-300 print:border-gray-400")}),Ve=Bt.column.columnDef.meta,tt=(Fn=Ve==null?void 0:Ve.getConditionalFormatting)==null?void 0:Fn.call(Ve,Ct.original,Ct.index),At=((Re=tt==null?void 0:tt.overlay)==null?void 0:Re.kind)==="dataBar"?tt.overlay:void 0,$t=At?Math.max(0,Math.min(1,At.ratio)):0,Dn=((rt=tt==null?void 0:tt.cellStyle)==null?void 0:rt.color)??((pt=tt==null?void 0:tt.rowStyle)==null?void 0:pt.color);return l.jsxs(Wn,{"data-column-id":Bt.column.id,style:{...Ne.style,...At?{position:"relative",overflow:"hidden"}:null,...tt==null?void 0:tt.rowStyle,...tt==null?void 0:tt.cellStyle,...Dn?{"--document-table-cell-color":Dn}:null,...At?{textAlign:"left"}:null},className:m.cn(Ne.className,(Ve==null?void 0:Ve.isNumeric)&&"numeric"),children:[At?l.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-1 left-4 right-4 overflow-hidden rounded-[2px]",children:l.jsx("div",{"aria-hidden":"true",className:"h-full rounded-[2px]",style:{width:`${$t*100}%`,backgroundColor:At.color,opacity:.4}})}):null,(At==null?void 0:At.showValue)!==!1?l.jsx("div",{className:m.cn(Dh(N,"leading-5",{textFlow:"delegate"}),At&&"relative z-[1]"),children:pi(Bt.column.columnDef.cell,Bt.getContext())}):null]},Bt.id)})},Ct.id)}),Qe&&vt>0&&l.jsx(Or,{"aria-hidden":!0,className:"pointer-events-none border-none hover:bg-transparent",children:l.jsx(Wn,{colSpan:St,style:{height:vt,padding:0,border:"none"}})})]}):l.jsx(Or,{className:"border-b-0 hover:bg-transparent",children:l.jsx(Wn,{colSpan:L.length,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:n?null:"No results."})})}),lt&&ee.length>0&&l.jsx("tfoot",{"data-row-type":"grand-total",style:{...N.grandTotalRowStyle,...A},children:l.jsx("tr",{style:{...N.grandTotalRowStyle,...A},children:Le.map((st,De,mt)=>{const Ct=q==null?void 0:q[st.id],Kt=Be[st.id],Bt=st.id===Te,Xt=typeof Kt=="number"||(Ct==null?void 0:Ct.type)==="number"?ow(Kt):null,Yn=(Ct==null?void 0:Ct.type)==="number"||Xt!==null,Se=(Ct==null?void 0:Ct.textAlign)??(Yn?"right":"left"),Ne=De===mt.length-1;let Ve="";Kt!=null?Xt!==null?Ve=qe(st.id,Xt,Ct):Ve=String(Kt):Bt&&(Ve="Total");const tt=Vc({tableAppearance:N,style:{width:st.getSize(),minWidth:st.getSize(),maxWidth:Ne?void 0:st.getSize(),textAlign:Se,position:nt?"sticky":void 0,bottom:nt?0:void 0,zIndex:nt?20:void 0,...He(st.id,"grandTotal"),...A},className:m.cn(C.totalsStyle.borderTop?"border-t border-border/60":"border-t-0","bg-muted/95 px-4 font-medium text-foreground/90",Yn&&"numeric tabular-nums",S&&"border-gray-300 print:border-gray-400")}),At=!S&&typeof Kt=="string"&&Ve.trim().length>0;return l.jsx("td",{"data-column-id":st.id,style:tt.style,className:tt.className,children:At?l.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l.jsx("span",{children:Ve}),l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":"About totals",className:"inline-flex cursor-help text-muted-foreground/80",children:l.jsx(m.Info,{className:"h-3.5 w-3.5"})})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-[240px]",children:"Totals are calculated across the full filtered dataset, not just the rows currently visible."})]})]}):Ve},st.id)})})})]})}),(()=>{if(Object.entries(q).some(([De,mt])=>mt.type!=="date"||!mt.dateFormat?!1:(mt.dateFormat.timezone==="auto"||!mt.dateFormat.timezone?ie||le:mt.dateFormat.timezone)!==le)){const De=new Set;Object.entries(q).forEach(([Ct,Kt])=>{if(Kt.type==="date"&&Kt.dateFormat){const Bt=Kt.dateFormat.timezone==="auto"||!Kt.dateFormat.timezone?ie||le:Kt.dateFormat.timezone;Bt&&Bt!==le&&De.add(Bt)}});const mt=Array.from(De).map(Ct=>`${yN(Ct)} (${ur.getTimezoneAbbreviation(Ct)})`).join(", ");return l.jsx("div",{className:"flex items-center justify-center px-4 py-2 text-xs text-muted-foreground",children:l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(UM,{className:"h-3 w-3"}),"Date/time values displayed in: ",mt]})})}return null})(),x.allowPagination&&b("showPagination")&&(Q==="server"||R.getFilteredRowModel().rows.length>10)&&l.jsx(U_,{totalColumns:J,pageCount:Q==="server"&&ae?ae.pageCount:R.getPageCount(),pageIndex:R.getState().pagination.pageIndex,pageSize:R.getState().pagination.pageSize,rowCount:Q==="server"&&ae?ae.totalCount:R.getFilteredRowModel().rows.length,selectedRowCount:R.getFilteredSelectedRowModel().rows.length,setPageIndex:R.setPageIndex,setPageSize:R.setPageSize,canPreviousPage:Q==="server"&&ae?ae.hasPrevPage:R.getCanPreviousPage(),canNextPage:Q==="server"&&ae?ae.hasNextPage:R.getCanNextPage(),previousPage:R.previousPage,nextPage:R.nextPage,onPageSizePreferenceChange:x.showEditorControls?p:void 0,onClearSelection:()=>{R.resetRowSelection(),((ke==null?void 0:ke.appliedClickFilters)||[]).filter(mt=>mt.sourceCardId===t.id).forEach(mt=>{m.useInteractionStore.getState().toggleClickFilter(t.id,mt)})},paginationMode:Q,showExport:!1,card:t,frameId:r,exportData:e.data,appearance:N.pagination}),b("showColumnSettings")&&l.jsx(QL,{column:F?R.getColumn(F)??null:null,settings:Z,onSettingsChange:Y,baseStyle:K,onBaseStyleChange:X,onReset:z,onResetAll:B,open:H,onOpenChange:G,availableColumns:R.getAllColumns().filter(st=>st.id!=="select").map(st=>st.id),isSqlCard:!!(t!=null&&t.sql)})]})})}const uC=e=>e==null?void 0:e.toString().trim(),dC=e=>e==null?void 0:e.toLowerCase().replace(/\s+/g,""),f3e=e=>{if(e)return e.label||e.qualifiedFieldName||e.name},h3e=(e,t,n,r)=>{const s=uC(e),o=dC(e),i=a=>[uC(a.label),uC(a.qualifiedFieldName),uC(a.name),dC(a.label),dC(a.qualifiedFieldName),dC(a.name)].filter(Boolean).some(u=>u===s||u===o);return(t==null?void 0:t.find(i))||(n==null?void 0:n.find(i))||(r==null?void 0:r.find(i))};function vre(e){return e!=null&&e.length?e.map(t=>{const n=f3e(t);return n?{id:n,desc:t.direction==="desc"}:null}).filter(t=>t!==null):[]}function wre(e,t,n,r){return e!=null&&e.length?e.map(({id:s,desc:o})=>{if(!s)return null;const i=h3e(s,t,n,r);return i?{...i,id:wte("sortBy",i),role:"sortby",direction:o?"desc":"asc"}:null}).filter(s=>s!==null):[]}function m3e({data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,card:s,comparisonMetadata:o,onSortChange:i,sortState:a,paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,columnSizing:p,onColumnSizingChange:g,onColumnResizeStateChange:b,showColumnResizeHandles:x,frameId:y,sheetId:v,onMultipleInteractions:S}){var z,B,H,L,G,J,oe,Q,ae,ie,le,ue;const N=m.useDashboardStore(fe=>fe.isVisualEditing),C=((B=(z=s==null?void 0:s.preferences)==null?void 0:z.tablePrefs)==null?void 0:B.columnSettingsMap)??m.EMPTY_COLUMN_SETTINGS,j=w.useMemo(()=>ec(C),[C]),_=(L=(H=s==null?void 0:s.preferences)==null?void 0:H.tablePrefs)==null?void 0:L.columnVisibility,k=p??((J=(G=s==null?void 0:s.preferences)==null?void 0:G.tablePrefs)==null?void 0:J.columnSizing),I=(Q=(oe=s==null?void 0:s.preferences)==null?void 0:oe.tablePrefs)==null?void 0:Q.selectColumnVisible,T=((ae=s==null?void 0:s.paginationConfig)==null?void 0:ae.pageSize)||((le=(ie=s==null?void 0:s.preferences)==null?void 0:ie.tablePrefs)==null?void 0:le.pageSize),{updateColumnSettingsMap:E,updateTableBaseFormatting:D,updateColumnVisibility:M,updateColumnSizing:A,setCard:P,updateCardInFrame:O,showAllColumns:$,hideAllColumns:V,toggleSelectColumn:U}=m.useEditorStore(fe=>fe.actions),R=w.useMemo(()=>{var fe;return vre((fe=s.config)==null?void 0:fe.sortByColumns)},[(ue=s.config)==null?void 0:ue.sortByColumns]),q=a??R,W=fe=>{if(!Yh(s))return!0;const pe=Lje(s,fe);if(!pe)return!1;const ge={...s,config:pe};return P(ge),O(ge),!0},F=w.useCallback(fe=>{const pe=typeof fe=="function"?fe(k||{}):fe;if(g){g(pe);return}A(pe)},[k,g,A]),Z=w.useCallback((fe,pe,ge)=>{E(p5({persisted:C,columnId:fe,baseline:ge,next:pe}))},[C,E]),K=w.useCallback(fe=>{E(BX(C,fe))},[C,E]),Y={card:s,data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,comparisonMetadata:o,pageSize:T,columnSettings:j,onColumnSettingsChange:Z,onResetColumnSettings:K,onResetAllColumnSettings:()=>E({}),onBaseFormattingChange:D,columnVisibility:_,onColumnVisibilityChange:M,columnSizing:k,onColumnSizingChange:F,onColumnResizeStateChange:b,showColumnResizeHandles:x,onShowAllColumns:$,onHideAllColumns:V,defaultSelectColumnVisible:I,onSelectColumnVisibleChange:U,exportFileName:"export",paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,sortState:q,onSortChange:i,onColumnReorder:W,frameId:y,sheetId:v,onMultipleInteractions:S},X={card:s,data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,comparisonMetadata:o,pageSize:T,columnSettings:j,columnSizing:k,onColumnSizingChange:g?F:void 0,onColumnResizeStateChange:b,showColumnResizeHandles:x,columnVisibility:_||m.EMPTY_COLUMN_VISIBILITY,defaultSelectColumnVisible:I,exportFileName:"export",paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,sortState:q,onSortChange:i,frameId:y,sheetId:v,onMultipleInteractions:S};return l.jsx(d3e,{...N?Y:X})}function p3e(e,t){return e.card===t.card&&e.data===t.data&&e.totalsData===t.totalsData&&e.formattingFullRows===t.formattingFullRows&&e.totalsByColumnId===t.totalsByColumnId&&e.comparisonMetadata===t.comparisonMetadata&&e.paginationMetadata===t.paginationMetadata&&e.onPaginationChange===t.onPaginationChange&&e.isLoading===t.isLoading&&e.sortState===t.sortState&&e.onSortChange===t.onSortChange&&e.columnSizing===t.columnSizing&&e.onColumnSizingChange===t.onColumnSizingChange&&e.onColumnResizeStateChange===t.onColumnResizeStateChange&&e.showColumnResizeHandles===t.showColumnResizeHandles&&e.suppressSortControls===t.suppressSortControls&&e.suppressCellHoverCards===t.suppressCellHoverCards&&e.frameId===t.frameId&&e.sheetId===t.sheetId&&e.onMultipleInteractions===t.onMultipleInteractions}const Bd=w.memo(m3e,p3e),u9=36,lD=280,g3e=16,b3e=12,x3e=[],y3e=[],$R={left:0,width:lD,minWidth:lD,maxWidth:lD},i3=150,Sre=240;function v3e(e,t){return e===t-1?Sre:i3}function zR(e,t){const n=v3e(e,t);return{left:e*i3,width:n,minWidth:n,maxWidth:n}}function w3e(e){return Math.max(e-1,0)*i3+Sre}function J_({card:e,result:t,grid:n,payload:r,isLoading:s,expansionState:o,onExpansionChange:i,loadingRowPathKeys:a,onSortChange:c,onLoadMoreRows:u}){const d=Q_("pivotTable"),{preferences:f,resolveBoundCurrency:h}=ka(e),p=w.useMemo(()=>iX({card:e,result:t,presentation:{preferences:f,resolveBoundCurrency:h}}),[e,f,h,t]),g=w.useMemo(()=>n||(t?$te(t):void 0),[n,t]),[b,x]=w.useState(()=>g?qu(g):null);w.useEffect(()=>{x(g?qu(g):null)},[g]);const y=o||b||void 0,v=w.useMemo(()=>!g&&!t?null:Lte({grid:g,result:t,payload:r,expansionState:y}),[y,g,t,r]),S=v==null?void 0:v.rows,N=v==null?void 0:v.headerRows,C=w.useMemo(()=>_3e(t),[t]),j=w.useMemo(()=>I3e(S??x3e),[S]),_=w.useMemo(()=>S3e(N??y3e),[N]),k=w.useMemo(()=>C3e({result:t,grid:g}),[g,t]);if(s)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"Loading matrix"});if(!v)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"Matrix payload unavailable"});if(!v.rows.length)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"No matrix rows to display"});const I=v.headerRows.length,T=v.rowHeaderLevels,E=T.map(oe=>oe.label).join(" · ")||"Rows",D=v.allRows.some(oe=>oe.canExpand),M=!D&&T.length>1,A=M?T.length:1,P=v.allRows.filter(oe=>oe.canExpand),O=P.length>0&&P.every(oe=>oe.isExpanded),$=v.columns.length-1,V=v.columns.reduce((oe,Q)=>Math.max(oe,Q.columnPath.length),0),U=v.columns.map((oe,Q)=>j3e(oe,v.columns[Q-1])),R=(C==null?void 0:C.rowLevels.filter(oe=>j.has(oe.publicId)))??[],q=R.at(-1),W=_.length>0,F=I+(W?1:0),Z=W?u9:0,K=y||(g?qu(g):void 0),Y=_.length>0&&K!==void 0&&_.every(oe=>M_(K,oe)),X=oe=>{if(!g)return;const Q=y||qu(g),ae=fFe({state:Q,rowPath:oe.rowPath});o||x(ae.state),i==null||i(ae)},z=oe=>{const Q=Nre(oe);Q&&(u==null||u(Q))},B=oe=>{if(!g)return;const Q=y||qu(g),ae=hFe({state:Q,columnPath:oe});o||x(ae.state),i==null||i(ae)},H=()=>{if(!g)return;const oe=y||qu(g),Q={schemaVersion:1,expandedRowPaths:O?[]:P.map(ae=>ae.rowPath),expandedColumnPaths:oe.expandedColumnPaths};x(Q),i==null||i({state:Q,kind:"bulkRows",isExpanded:!O})},L=()=>{if(!g)return;const Q={schemaVersion:1,expandedRowPaths:(y||qu(g)).expandedRowPaths,expandedColumnPaths:Y?[]:_};o||x(Q),i==null||i({state:Q,kind:"bulkColumns",isExpanded:!Y})},G=(oe,Q,ae)=>{if(!C)return;const ie={axis:"row",targetId:oe.publicId,direction:Q,by:ae==="value"?{kind:"value",valueId:C.measurePublicId}:{kind:"label"},nulls:"last",scope:"withinParent"};c==null||c([ie])},J=(oe,Q)=>{if(!C||!oe.measureInstanceId||!q)return;const ae={axis:"row",targetId:q.publicId,direction:Q,by:{kind:"value",valueId:R0(oe.measureInstanceId,"measure"),columnPath:T3e(oe.columnPath,"column")},nulls:"last",scope:"withinParent"};c==null||c([ae])};return l.jsxs(il,{className:"data-table-scroll-container h-full min-h-0 w-full rounded-none border border-border/60 bg-background",viewportClassName:"overscroll-none",scrollBarClassName:"z-40",children:[l.jsxs(Kne,{containerClassName:"overflow-visible",className:"min-w-max border-separate border-spacing-0",style:d.containerStyle,"data-matrix-table":"true","aria-label":"Matrix table",role:"treegrid","aria-rowcount":v.allRows.length+F,"aria-colcount":A+v.columns.length,children:[l.jsxs(Pm,{children:[W?l.jsxs(Or,{className:"hover:bg-transparent",children:[M?T.map((oe,Q)=>l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:oe.label,style:{...zR(Q,A),top:0},className:m.cn("sticky top-0 z-30 overflow-hidden text-ellipsis whitespace-nowrap border-b border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",Q===A-1&&"border-r",d.headerTextClassName),children:oe.label},oe.id)):l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:E,style:{...$R,top:0},className:m.cn("group/row-header sticky left-0 top-0 z-30 overflow-hidden whitespace-nowrap border-b border-r border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[D&&P.length>0?l.jsx("button",{type:"button",onClick:H,"aria-label":O?"Collapse all rows":"Expand all rows","aria-expanded":O,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})}):null,l.jsx("span",{className:"truncate",children:E}),c&&C&&R.length?l.jsx(d9,{rowLevels:R,measureLabel:C.measureLabel,onSort:G}):null]})}),l.jsx(hs,{colSpan:v.columns.length,scope:"colgroup",style:{...d.headerCellStyle,top:0},className:m.cn("sticky top-0 z-20 h-9 whitespace-nowrap border-b border-l border-border/70 bg-muted text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:L,"aria-label":Y?"Collapse all columns":"Expand all columns","aria-expanded":Y,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",Y&&"rotate-90"),"aria-hidden":"true"})}),l.jsx("span",{className:"flex min-w-0 items-center gap-1.5 truncate font-medium leading-5 text-muted-foreground",children:k.map((oe,Q)=>l.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[Q>0?l.jsx(Ot.ChevronRight,{className:"size-3.5 shrink-0 text-muted-foreground/70","aria-hidden":"true"}):null,l.jsx("span",{className:"truncate",children:oe})]},`${oe}:${Q}`))})]})})]}):null,v.headerRows.map((oe,Q)=>l.jsxs(Or,{className:"hover:bg-transparent",children:[!W&&Q===0&&(M?T.map((ae,ie)=>l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:ae.label,style:{...zR(ie,A),top:0},className:m.cn("sticky top-0 z-30 overflow-hidden text-ellipsis whitespace-nowrap border-b border-border/60 bg-muted px-3 text-left align-bottom text-[13px] font-medium normal-case",ie===A-1&&"border-r",d.headerTextClassName),children:ae.label},ae.id)):l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:E,style:{...$R,top:0},className:m.cn("group/row-header sticky left-0 top-0 z-30 overflow-hidden whitespace-nowrap border-b border-r border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[D&&P.length>0?l.jsx("button",{type:"button",onClick:H,"aria-label":O?"Collapse all rows":"Expand all rows","aria-expanded":O,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})}):null,l.jsx("span",{className:"truncate",children:E}),c&&C&&R.length?l.jsx(d9,{rowLevels:R,measureLabel:C.measureLabel,onSort:G}):null]})})),oe.cells.map((ae,ie)=>l.jsx(E3e,{cell:ae,top:Z+Q*u9,stickyRight:ie===oe.cells.length-1&&ae.role==="grandTotal",tableAppearance:d,onToggle:B,rowSortTargetLabel:q==null?void 0:q.label,maxColumnPathDepth:V,onValueSort:c?J:void 0},ae.id))]},oe.id))]}),l.jsx($d,{children:v.rows.map((oe,Q)=>l.jsxs(Or,{className:"hover:bg-muted/30",style:oe.isGrandTotal?d.grandTotalRowStyle:oe.isSubtotal?d.subtotalRowStyle:void 0,role:"row","aria-level":oe.ariaLevel,"aria-expanded":oe.canExpand?oe.isExpanded:void 0,children:[M?l.jsx(P3e,{row:oe,previousRow:v.rows[Q-1],rowHeaderCount:A}):l.jsx(A3e,{row:oe,isStickyBottom:oe.isGrandTotal,loadingRowPathKeys:a,onToggle:X,onLoadMore:z}),oe.cells.map((ae,ie)=>{var le;return l.jsx(O3e,{cell:ae,displayValue:aX({cell:{measureId:ae.measureInstanceId,value:ae.rawValue,presence:ae.presence},formatsByMeasureId:p}),divider:U[ie],isGrandTotalRow:oe.isGrandTotal,isStickyBottom:oe.isGrandTotal,isStickyRight:ie===$&&!!((le=v.columns[ie])!=null&&le.isGrandTotal),tableAppearance:d},ae.id)})]},oe.id))})]}),l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-40"})]})}function S3e(e){const t=new Map;for(const n of e)for(const r of n.cells)!r.isExpandable||!r.expansionPath||t.set(as(r.expansionPath),r.expansionPath);return Array.from(t.values())}function C3e(e){var n,r;const t=((n=e.result)==null?void 0:n.axes.columns.levels.map(s=>s.label).filter(Boolean))??[];if(!t.length){const s=new Map;for(const o of((r=e.grid)==null?void 0:r.columns)??[])for(const i of o.columnPath)s.has(i.instanceId)||s.set(i.instanceId,N3e(i.instanceId));t.push(...s.values())}return t.length?t:["Columns"]}function N3e(e){return e.replace(/^(row|column|measure):/,"").replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().split(/\s+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function j3e(e,t){if(e.isGrandTotal)return"grandTotal";if(e.isSubtotal)return"subtotal";if(!t)return"none";const n=ej(e.columnPath[0]),r=ej(t.columnPath[0]);return n!==r?"group":"none"}function k3e(e){switch(e){case"grandTotal":return"border-l-2 border-l-border";case"subtotal":return"border-l border-l-border/60";case"group":return"border-l border-l-border/40";default:return""}}function _3e(e){var r;const t=(e==null?void 0:e.axes.rows.levels.map(s=>({publicId:R0(s.instanceId,"row"),label:s.label})))??[],n=Object.values((e==null?void 0:e.measuresById)??{})[0];return!t.length||!n?null:{rowLevels:t,deepestRowLevelLabel:((r=t.at(-1))==null?void 0:r.label)??"Rows",measurePublicId:R0(n.instanceId,"measure"),measureLabel:n.label}}function I3e(e){const t=new Set;for(const n of e){const r=n.rowPath.at(-1);r&&t.add(R0(r.instanceId,"row"))}return t}function R0(e,t){const n=`${t}:`;return e.startsWith(n)?e.slice(n.length):e}function T3e(e,t){return e.map(n=>({levelId:R0(n.instanceId,t),value:n.value}))}function d9({rowLevels:e,measureLabel:t,onSort:n}){const[r,s]=w.useState(!1),o=(i,a,c)=>{n(i,a,c),s(!1),Cre()};return l.jsxs(Ys,{open:r,onOpenChange:s,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Sort row levels",title:"Sort row levels",className:"pointer-events-none ml-auto inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-opacity hover:bg-muted-foreground/10 hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/row-header:pointer-events-auto group-hover/row-header:opacity-100",children:l.jsx(Si,{className:"size-3.5","aria-hidden":"true"})})}),l.jsxs(Es,{align:"end",className:"w-64 p-1",children:[l.jsx($a,{children:"Sort row levels"}),e.map((i,a)=>l.jsxs("div",{children:[a>0?l.jsx(Sa,{}):null,l.jsx(BR,{label:i.label,onAscending:()=>o(i,"asc","label"),onDescending:()=>o(i,"desc","label"),ascendingLabel:`Sort ${i.label} A to Z`,descendingLabel:`Sort ${i.label} Z to A`}),l.jsx(BR,{label:t,onAscending:()=>o(i,"asc","value"),onDescending:()=>o(i,"desc","value"),ascendingLabel:`Sort ${i.label} by ${t} ascending`,descendingLabel:`Sort ${i.label} by ${t} descending`})]},i.publicId))]})]})}function BR({label:e,onAscending:t,onDescending:n,ascendingLabel:r,descendingLabel:s}){return l.jsxs("div",{className:"flex h-7 items-center justify-between gap-2 rounded-sm px-2",children:[l.jsx("span",{className:"min-w-0 truncate text-[13px] text-foreground",children:e}),l.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5",children:[l.jsx("button",{type:"button","aria-label":r,className:"inline-flex size-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:t,children:l.jsx(No,{className:"size-3.5","aria-hidden":"true"})}),l.jsx("button",{type:"button","aria-label":s,className:"inline-flex size-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:n,children:l.jsx(ro,{className:"size-3.5","aria-hidden":"true"})})]})]})}function E3e({cell:e,top:t,stickyRight:n,tableAppearance:r,onToggle:s,onValueSort:o,rowSortTargetLabel:i,maxColumnPathDepth:a}){const c=!!o&&e.colSpan===1&&!!e.measureInstanceId&&e.columnPath.length>0&&e.columnPath.length===a&&e.role!=="grandTotal"&&e.role!=="subtotal";return l.jsx(hs,{colSpan:e.colSpan,rowSpan:e.rowSpan,scope:"colgroup",style:{...r.headerCellStyle,top:t,...n?{right:0}:{}},className:m.cn("group/matrix-col-header sticky z-20 h-9 whitespace-nowrap border-b border-l border-border/40 bg-muted",e.isExpandable?"text-left":"text-right",e.role==="grandTotal"&&"border-l-2 border-l-border font-semibold",e.role==="subtotal"&&"border-l-border/60 font-semibold",n&&"z-30","text-[13px] font-medium normal-case",r.headerTextClassName),children:e.isExpandable&&e.expansionPath?l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-expanded":e.isExpanded,"aria-label":`${e.isExpanded?"Collapse":"Expand"} ${e.label}`,"data-spr-expand-id":`matrix-column:${e.id}`,onClick:()=>s(e.expansionPath),children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",e.isExpanded&&"rotate-90"),"aria-hidden":"true"})}),l.jsx("span",{children:e.label}),c&&i?l.jsx(f9,{columnLabel:e.label,rowSortTargetLabel:i,onSort:u=>o==null?void 0:o(e,u)}):null]}):l.jsxs("span",{className:"relative inline-flex w-full items-center justify-end overflow-hidden",children:[l.jsx("span",{className:m.cn("min-w-0 truncate text-right transition-transform duration-150 ease-out",c&&i&&"group-hover/matrix-col-header:-translate-x-6"),children:e.label}),c&&i?l.jsx(f9,{columnLabel:e.label,rowSortTargetLabel:i,onSort:u=>o==null?void 0:o(e,u)}):null]})})}function f9({columnLabel:e,rowSortTargetLabel:t,onSort:n}){const[r,s]=w.useState(!1),o=i=>{n(i),s(!1),Cre()};return l.jsxs(Ys,{open:r,onOpenChange:s,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Sort ${e} value column`,title:`Sort ${e}`,className:"pointer-events-none absolute right-0 top-1/2 inline-flex size-5 -translate-y-1/2 translate-x-1 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-all duration-150 ease-out hover:bg-muted-foreground/10 hover:text-foreground focus-visible:pointer-events-auto focus-visible:translate-x-0 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/matrix-col-header:pointer-events-auto group-hover/matrix-col-header:translate-x-0 group-hover/matrix-col-header:opacity-100",children:l.jsx(Si,{className:"size-3.5","aria-hidden":"true"})})}),l.jsxs(Es,{align:"end",className:"w-60 p-1",children:[l.jsx($a,{children:e}),l.jsx(BR,{label:t,onAscending:()=>o("asc"),onDescending:()=>o("desc"),ascendingLabel:`Sort ${t} by ${e} ascending`,descendingLabel:`Sort ${t} by ${e} descending`})]})]})}function Cre(){const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function D3e(e){if(e.rowPath.length===0)return{label:e.label,indent:0};const t=VR(e.rowPath[e.rowPath.length-1]);return e.hasParentRow?{label:t,indent:Math.max(e.depth,0)}:e.depth===0?{label:t,indent:0}:{label:e.rowPath.map(VR).join(" · "),indent:0}}function VR(e){return(e==null?void 0:e.label)??jre(e)}function M3e(e){var t;return((t=e.rowPath.at(-1))==null?void 0:t.instanceId)==="__matrix_remaining__"}function Nre(e){return!M3e(e)||e.rowPath.length<2?null:e.rowPath.slice(0,-1)}function A3e({row:e,isStickyBottom:t,loadingRowPathKeys:n,onToggle:r,onLoadMore:s}){const{label:o,indent:i}=D3e(e),a=b3e+i*g3e,c=n==null?void 0:n.has(h9(e.rowPath)),u=Nre(e),d=u?n==null?void 0:n.has(h9(u)):!1,f=R3e(e),h=e.visibleChildCount<e.childCount?`Showing ${e.visibleChildCount} of ${e.childCount} child rows`:`${e.childCount} child rows`;return l.jsx(Wn,{scope:"row",title:o,style:{...$R,paddingLeft:a},className:m.cn("sticky left-0 z-10 overflow-hidden whitespace-nowrap border-b border-r border-border/60 py-1.5 pr-3 text-left text-[13px]",t&&"bottom-0 z-20",!e.isSubtotal&&!e.isGrandTotal&&"bg-background",e.isSubtotal&&"bg-muted font-medium",e.isGrandTotal&&"bg-muted font-semibold",e.isGrandTotal&&"border-t-2 border-t-border"),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[e.canExpand?l.jsx("button",{type:"button",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`${e.isExpanded?"Collapse":"Expand"} ${o}`,"aria-expanded":e.isExpanded,"data-spr-expand-id":`matrix-row:${e.rowNodeId}`,onClick:()=>r(e),onKeyDown:p=>{(p.key==="ArrowRight"&&!e.isExpanded||p.key==="ArrowLeft"&&e.isExpanded)&&(p.preventDefault(),r(e))},children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",e.isExpanded&&"rotate-90"),"aria-hidden":"true"})}):l.jsx("span",{className:"inline-block size-4 shrink-0","aria-hidden":"true"}),l.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate",children:o}),e.canExpand&&f?l.jsx("span",{className:"shrink-0 text-[10px] font-normal tabular-nums text-muted-foreground",title:h,children:f}):null]}),c?l.jsx(m.LoaderCircle,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground","aria-label":"Loading row children"}):null,u&&s?l.jsx("button",{type:"button",className:"ml-auto inline-flex shrink-0 items-center gap-1 rounded-sm px-1.5 py-0.5 text-xs font-medium text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-70","aria-label":`Show hidden rows for ${o}`,disabled:d,onClick:()=>s(e),children:d?l.jsx(m.LoaderCircle,{className:"size-3.5 animate-spin","aria-label":"Loading hidden rows"}):"Show"}):null]})})}function R3e(e){return!e.canExpand||e.childCount<=0?null:e.visibleChildCount>0&&e.visibleChildCount<e.childCount?`${e.visibleChildCount}/${e.childCount}`:String(e.childCount)}function P3e({row:e,previousRow:t,rowHeaderCount:n}){const r=m.cn(!e.isSubtotal&&!e.isGrandTotal&&"bg-background",e.isSubtotal&&"bg-muted font-medium",e.isGrandTotal&&"bg-muted font-semibold");if(e.rowPath.length<n){const o=w3e(n);return l.jsx(Wn,{scope:"row",colSpan:n,style:{left:0,width:o,minWidth:o,maxWidth:o},className:m.cn("sticky left-0 z-10 overflow-hidden whitespace-nowrap border-b border-r border-border/60 px-3 py-1.5 text-left text-[13px]",e.isGrandTotal&&"bottom-0 z-20 border-t-2 border-t-border",r),children:e.label})}const s=F3e(e,t);return l.jsx(l.Fragment,{children:Array.from({length:n},(o,i)=>{const a=e.rowPath[i],c=i>=s,u=VR(a);return l.jsx(Wn,{scope:i===0?"row":void 0,title:c?u:void 0,style:zR(i,n),className:m.cn("sticky z-10 overflow-hidden whitespace-nowrap border-b border-border/60 py-1.5 pr-3 text-left text-[13px]",i===0?"pl-3":"pl-2",i===n-1&&"border-r",r),children:l.jsx("span",{className:"truncate",children:c?u:""})},`${e.id}:rh:${i}`)})})}function F3e(e,t){if(!t)return 0;const n=Math.max(e.rowPath.length,t.rowPath.length);for(let r=0;r<n;r+=1)if(ej(e.rowPath[r])!==ej(t.rowPath[r]))return r;return e.rowPath.length}function O3e({cell:e,displayValue:t,divider:n,isGrandTotalRow:r,isStickyRight:s,isStickyBottom:o,tableAppearance:i}){const a=m.cn("whitespace-nowrap border-b border-border/60 text-right tabular-nums",k3e(n),r&&"border-t-2 border-t-border",e.role==="rowSubtotal"&&"bg-muted/50 font-medium",e.role==="columnSubtotal"&&"bg-muted/50 font-medium",e.role==="subtotalIntersection"&&"bg-muted/70 font-medium",e.role==="rowGrandTotal"&&"bg-muted font-semibold",e.role==="columnGrandTotal"&&"bg-muted font-semibold",e.role==="matrixGrandTotal"&&"bg-muted font-semibold",e.isSparse&&"text-muted-foreground/55",s&&"sticky right-0 bg-muted",o&&"sticky bottom-0 bg-muted",s&&o?"z-20":s||o?"z-10":""),c=e.isGrandTotal?Vc({tableAppearance:i,className:a}):e.isSubtotal?hd({tableAppearance:i,className:a,divider:"row"}):Eh({tableAppearance:i,className:a,divider:"row"});return l.jsx(Wn,{...c,children:t})}function ej(e){if(e)return`${e.instanceId}:${jre(e)}`}function jre(e){const t=e==null?void 0:e.value;return t==null?"":t instanceof Date?t.toISOString():String(t)}function h9(e){return JSON.stringify(e.map(t=>({instanceId:t.instanceId,fieldKey:t.fieldKey,value:t.value instanceof Date?t.value.toISOString():t.value})))}function Vd({size:e="md",color:t="muted",className:n=""}){const r={xs:"w-0.5 h-0.5",sm:"w-1 h-1",md:"w-2 h-2",lg:"w-3 h-3"},s={muted:"bg-muted-foreground/70",primary:"bg-primary",secondary:"bg-secondary-foreground",accent:"bg-accent-foreground",destructive:"bg-destructive",gray:"bg-gray-400 dark:bg-gray-500",blue:"bg-blue-500 dark:bg-blue-400",green:"bg-green-500 dark:bg-green-400",red:"bg-red-500 dark:bg-red-400"},o=m.cn(r[e],s[t],"rounded-full animate-pulse");return l.jsxs("div",{className:m.cn("flex items-center gap-1",n),children:[l.jsx("div",{className:o,style:{animationDelay:"0ms",animationDuration:"1.4s"}}),l.jsx("div",{className:o,style:{animationDelay:"200ms",animationDuration:"1.4s"}}),l.jsx("div",{className:o,style:{animationDelay:"400ms",animationDuration:"1.4s"}})]})}function L3e(e,t){var C,j;const n=m.useDashboardStore(_=>_.isVisualEditing),{updateCurrentDashboardCard:r}=m.useDashboardActions(),s=m.useEditorStore(_=>{var k;return(k=_.actions)==null?void 0:k.updateColumnSettingsMap}),o=((j=(C=e==null?void 0:e.preferences)==null?void 0:C.tablePrefs)==null?void 0:j.columnSettingsMap)??m.EMPTY_COLUMN_SETTINGS,i=w.useMemo(()=>ec(o),[o]),[a,c]=w.useState(!1),[u,d]=w.useState(null),[f,h]=w.useState(ks()),[p,g]=w.useState(!1),b=w.useRef(ks()),x=w.useCallback(_=>{var M,A;d(_);let k=i[_];k||(k=t&&t.length>0?A0(_,t):ks());const I=t&&t.length>0?Object.keys(t[0]||{}):[],T=((A=(M=e.config)==null?void 0:M.groupByColumns)==null?void 0:A.length)||0,D=I.indexOf(_)-T;k=D>=0?Zh({card:e,columnId:_,metricIndex:D,groupByColumnCount:T,columnSettingsMap:i,preserveOmittedProperties:!0}):Vi({card:e,columnId:_,resolvedSettings:k,preserveOmittedProperties:!0})||k,b.current=k,h(k),g(!1),c(!0)},[e,i,t]),y=w.useCallback(()=>{var _;if(u&&f){const k=p5({persisted:o,columnId:u,baseline:b.current,next:f,reset:p});if(n&&s)s(k);else if(r){const I={...e,preferences:{...e.preferences,tablePrefs:{...(_=e.preferences)==null?void 0:_.tablePrefs,columnSettingsMap:k}}};r(I)}}c(!1)},[u,f,p,o,n,s,r,e]),v=w.useCallback(()=>{u&&(h(ks()),g(!0))},[u]),S=w.useCallback(_=>{g(!1),h(_)},[]),N=w.useCallback(()=>{var _;if(n&&s)s({});else if(r){const k={...e,preferences:{...e.preferences,tablePrefs:{...(_=e.preferences)==null?void 0:_.tablePrefs,columnSettingsMap:{}}}};r(k)}c(!1)},[n,s,r,e]);return{columnSettings:i,columnSettingsOpen:a,activeColumnId:u,tempColumnSettings:f,isVisualEditing:n,openColumnSettings:x,applyColumnSettings:y,resetColumnSettings:v,resetAllColumnSettings:N,setColumnSettingsOpen:c,setTempColumnSettings:S}}function P0(e,t,n,r=!1){if(e==null)return l.jsx(Ac,{className:"h-4 w-4 text-muted-foreground"});if(!n)return typeof e=="number"?e.toLocaleString():String(e);if(n.type==="badge")return $3e(e);if(n.type==="link"&&e)return z3e(e);if(n.type==="progress"&&typeof e=="number")return B3e(e);if(n.type==="number"){const s=QQ(e,n);if(s!==null){const o=q5(e);return o!==null?V3e(o,n):s}}return n.type==="date"&&e&&r?H3e(e,n):String(e)}function $3e(e){return l.jsx($s,{variant:"outline",className:"px-1.5 text-muted-foreground",children:String(e)})}function z3e(e){let t=String(e);return!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),l.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 underline hover:text-blue-700",onClick:n=>n.stopPropagation(),children:String(e)})}function B3e(e){const t=Math.min(Math.max(0,e),100);let n="#ef4444";return t>=70?n="#22c55e":t>=40&&(n="#eab308"),l.jsxs("div",{className:"relative flex h-5 w-full items-center",children:[l.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-gray-200",children:l.jsx("div",{className:"h-full transition-all duration-300",style:{width:`${t}%`,backgroundColor:n}})}),l.jsxs("span",{className:"absolute inset-0 flex items-center justify-center text-xs font-medium",children:[t,"%"]})]})}function V3e(e,t){const{numberFormat:n}=t;let r=e.toLocaleString();try{r=In.formatNumberWithColumnSettings(e,n,n.locale||"en-US")||e.toLocaleString()}catch{r=e.toLocaleString()}if(n.showDataBar){const s=n.dataBarMinValue??0,o=n.dataBarMaxValue??100,i=(e-s)/(o-s)*100,a=Math.min(Math.max(0,i),100),c=n.dataBarColor||"#3b82f6";return l.jsxs("div",{className:"relative flex items-center",children:[l.jsx("div",{className:"absolute inset-y-0 left-0 bg-opacity-20",style:{width:`${a}%`,backgroundColor:c}}),l.jsx("span",{className:"relative px-2",children:r})]})}if(t.colorRanges&&t.colorRanges.length>0){for(const s of t.colorRanges)if(e>=s.min&&e<=s.max){const i=z1e(s.color);return l.jsx("span",{style:{backgroundColor:s.color,color:i,padding:"2px 6px",borderRadius:"4px"},children:r})}}return r}function H3e(e,t){const n=t.dateFormat;if(n!=null&&n.useRelativeTime)return ur.formatRelativeTime(String(e),(n==null?void 0:n.sourceTimezone)||"auto");const r=n!=null&&n.useCustomFormat&&(n!=null&&n.customFormat)?n.customFormat:(n==null?void 0:n.format)||"MM/dd/yyyy";return ur.formatDate(String(e),r,n==null?void 0:n.timezone,(n==null?void 0:n.sourceTimezone)||"auto")}function U3e({columnId:e,label:t,isVisualEditing:n,isTablePrintDisplayMode:r,groupByColumns:s,card:o,isResizing:i=!1,onOpenColumnSettings:a,onAggregationChange:c}){var u,d;return l.jsxs("div",{className:m.cn("group/table-head relative flex items-center gap-1.5",n&&"transition-[padding] duration-150 hover:pl-4 focus-within:pl-4"),children:[n&&l.jsx("span",{"data-grip-handle":"",className:"pointer-events-none absolute left-0 top-1/2 inline-flex -translate-y-1/2 cursor-grab items-center opacity-0 transition-opacity duration-150 group-hover/table-head:pointer-events-auto group-hover/table-head:opacity-100 group-focus-within/table-head:pointer-events-auto group-focus-within/table-head:opacity-100 active:cursor-grabbing","aria-label":"Drag to reorder column",children:l.jsx(bu,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-600","aria-hidden":"true"})}),l.jsx("span",{className:m.cn("min-w-0 flex-1 truncate"),title:t,children:t}),!i&&(n||c&&!r)&&l.jsx(kre,{label:t,isVisualEditing:n,groupByColumns:s,currentAggregation:{rowAggregates:((u=o==null?void 0:o.config)==null?void 0:u.rowAggregates)||[],columnAggregates:((d=o==null?void 0:o.config)==null?void 0:d.columnAggregates)||[]},onOpenColumnSettings:()=>a(e),onAggregationChange:r?void 0:c})]})}function q3e({columnId:e,displayLabel:t,isVisualEditing:n,isResizing:r=!1,onOpenColumnSettings:s}){return l.jsxs("div",{className:m.cn("group/table-head relative flex items-center gap-1.5",n&&"transition-[padding] duration-150 hover:pl-4 focus-within:pl-4"),children:[n&&l.jsx("span",{"data-grip-handle":"",className:"pointer-events-none absolute left-0 top-1/2 inline-flex -translate-y-1/2 cursor-grab items-center opacity-0 transition-opacity duration-150 group-hover/table-head:pointer-events-auto group-hover/table-head:opacity-100 group-focus-within/table-head:pointer-events-auto group-focus-within/table-head:opacity-100 active:cursor-grabbing","aria-label":"Drag to reorder column",children:l.jsx(bu,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-600","aria-hidden":"true"})}),l.jsx("span",{className:"min-w-0 flex-1 truncate",title:t,children:t}),n&&!r&&l.jsx(kre,{label:t,isVisualEditing:n,groupByColumns:[],onOpenColumnSettings:()=>s(e)})]})}function kre({label:e,isVisualEditing:t,groupByColumns:n,currentAggregation:r,onOpenColumnSettings:s,onAggregationChange:o}){const i=[{value:"SUM",label:"Sum"},{value:"MAX",label:"Max"},{value:"MIN",label:"Min"},{value:"AVG",label:"Avg"},{value:"MEDIAN",label:"Median"}],a=!!o,c=(u,d)=>{var h;const f=d==="all"?"ALL":d;return(h=r==null?void 0:r.rowAggregates)==null?void 0:h.some(p=>p.function===u&&p.groupLevel===f)};return l.jsxs(Ys,{modal:!1,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Configure ${e} column`,className:"inline-flex shrink-0 items-center justify-center rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",onClick:u=>u.stopPropagation(),children:l.jsx(Si,{className:"h-3 w-3"})})}),l.jsxs(Es,{align:"end",className:"w-56",children:[t&&l.jsxs(Nn,{className:"gap-2 text-xs",onClick:u=>{u.stopPropagation(),s()},children:[l.jsx(m.SlidersHorizontal,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Format column"]}),t&&a&&l.jsx(Sa,{}),a&&l.jsxs(l.Fragment,{children:[l.jsx($a,{className:"text-xs font-normal text-muted-foreground",children:"AGGREGATE"}),i.map(u=>{var f;const d=((f=r==null?void 0:r.rowAggregates)==null?void 0:f.some(h=>h.function===u.value))||!1;return l.jsxs(WL,{children:[l.jsx(L_,{className:"text-xs",children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsx("span",{children:u.label}),d&&l.jsx("span",{className:"ml-2 rounded bg-blue-100 px-1 py-0.5 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:"R"})]})}),l.jsxs($_,{className:"w-48",children:[l.jsx($a,{className:"text-xs font-normal text-muted-foreground",children:"ROWS"}),l.jsx(Nn,{className:"text-xs",onClick:()=>o==null?void 0:o({function:u.value,rowLevel:"all"}),children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsx("span",{children:"of all rows"}),c(u.value,"all")&&l.jsx(m.Check,{className:"h-4 w-4"})]})}),n.map(h=>l.jsx(Nn,{className:"text-xs",onClick:()=>o==null?void 0:o({function:u.value,rowLevel:h.id}),children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsxs("span",{children:["within ",h.label||h.name]}),c(u.value,h.id)&&l.jsx(m.Check,{className:"h-4 w-4"})]})},h.id))]})]},`${u.value}-${u.label}`)})]})]})]})}function W3e({row:e,columnId:t,columnAlias:n,groupByColumns:r,card:s,settings:o,alignment:i,idx:a}){var h,p,g;const c=e,u=!!(s!=null&&s.sql);if(c.isGrandTotal)return l.jsx(l.Fragment,{children:a===0?"Grand Total":""});if(c.isSubtotal){if(c.subtotalContext){const x=c.subtotalLevel,y=r.findIndex(v=>v.alias===x);if(a===y){const v=c.aggregate||"SUM",S=(g=(p=(h=s==null?void 0:s.config)==null?void 0:h.rowAggregates)==null?void 0:p.find(N=>N.groupLevel===c.subtotalLevel&&N.function===v))==null?void 0:g.label;return l.jsx(l.Fragment,{children:eJ(c,n,v,S)})}else if(a<y){const v=c[n];if(v&&v!=="__TOTAL__"){const S=P0(v,t,o,u);return l.jsx("div",{className:m.cn(i==="right"?"text-right":i==="center"?"text-center":"text-left"),children:S})}}}return l.jsx(l.Fragment,{})}const d=c[n],f=P0(d,t,o,u);return l.jsx("div",{className:m.cn(i==="right"?"text-right":i==="center"?"text-center":"text-left",d==null?"flex items-center":"",d==null?i==="right"?"justify-end":i==="center"?"justify-center":"justify-start":""),children:f})}function _re(e,t,n="left"){const r=t[e]||ks(),s=(r==null?void 0:r.textAlign)||n,o=r!=null&&r.width&&typeof r.width=="number"?r.width:150,i=(r==null?void 0:r.minWidth)??50,a=(r==null?void 0:r.maxWidth)??500;return{settings:r,alignment:s,size:o,minSize:i,maxSize:a}}function G3e({groupByColumns:e,pivotSchema:t,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a,valueFormatPreferences:c,resolveBoundCurrency:u}){const d=[],f=K3e({groupByColumns:e,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a});d.push(...f);const h=Y3e({pivotSchema:t,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a,groupByColumns:e,valueFormatPreferences:c,resolveBoundCurrency:u});return d.push(...h),d}function K3e({groupByColumns:e,columnSettings:t,card:n,isVisualEditing:r,isTablePrintDisplayMode:s,onOpenColumnSettings:o,onAggregationChange:i}){return e.map((a,c)=>{const u=a.alias||a.name,{settings:d,alignment:f,size:h,minSize:p,maxSize:g}=_re(u,t,"left");return{id:u,accessorFn:b=>b[u],size:h,minSize:p,maxSize:g,enableResizing:!0,header:({column:b})=>l.jsx(U3e,{columnId:u,label:a.label||a.name,alignment:f,isVisualEditing:r,isTablePrintDisplayMode:s,groupByColumns:e,card:n,idx:c,isResizing:b.getIsResizing(),onOpenColumnSettings:o,onAggregationChange:i}),cell:({row:b})=>l.jsx(W3e,{row:b.original,columnId:u,columnAlias:a.alias||a.name,groupByColumns:e,card:n,settings:d,alignment:f,idx:c})}})}function Y3e({pivotSchema:e,columnSettings:t,card:n,isVisualEditing:r,isTablePrintDisplayMode:s,onOpenColumnSettings:o,onAggregationChange:i,groupByColumns:a,valueFormatPreferences:c,resolveBoundCurrency:u}){const d=!!(n!=null&&n.sql);return e.filter(f=>f.isMetricColumn).map((f,h)=>{var C,j,_;const p=f.alias,{settings:g,size:b,minSize:x,maxSize:y}=_re(p,t,"right"),v=Jl({card:n,columnKey:p,metricId:(_=(j=(C=n.config)==null?void 0:C.metricColumns)==null?void 0:j[h])==null?void 0:_.id}),S=Zh({card:n,columnId:p,metricIndex:h,groupByColumnCount:a.length,columnSettingsMap:t,valueFormatPreferences:c,boundCurrency:v?u(v):void 0}),N="right";return{id:p,accessorFn:k=>k[p],size:b,minSize:x,maxSize:y,enableResizing:!0,header:({column:k})=>l.jsx(q3e,{columnId:p,metricName:f.metricName,displayLabel:f.displayLabel||f.metricLabel||f.metricName,alignment:N,isVisualEditing:r,isTablePrintDisplayMode:s,groupByColumns:a,card:n,isResizing:k.getIsResizing(),onOpenColumnSettings:o,onAggregationChange:i}),cell:({row:k})=>{const I=k.original[p],T=P0(I,p,S||g,d);return l.jsx("div",{className:m.cn("text-right",I==null?"flex items-center justify-end":""),children:T})}}})}function Z3e({table:e,columns:t,groupByColumns:n,columnSettings:r,isTablePrintDisplayMode:s,disableRowTransitions:o=!1,tableAppearance:i}){const a=e.getRowModel().rows;return a!=null&&a.length?l.jsx($d,{children:a.map((c,u)=>{const d=c.original,f=d.isSubtotal&&!d.isGrandTotal;return l.jsx(Or,{"data-row-type":f?"subtotal":"data","data-subtotal-level":f?d.subtotalLevel:void 0,style:f?i.subtotalRowStyle:i.getDataRowStyle(u),className:m.cn("border-border/40",(o||i.hasHoverRowStyle)&&"!transition-none",!o&&!i.hasHoverRowStyle&&"transition-colors duration-150",!f&&i.dataRowClassName,f&&!s&&"border-t border-t-border/50 bg-muted/70 font-medium",!f&&"hover:bg-muted/40",f&&s&&"print:bg-gray-150 border-t-2 border-gray-300 bg-gray-100 font-semibold text-foreground print:border-gray-400",s&&"border-gray-300 print:break-inside-avoid print:border-gray-400"),children:c.getVisibleCells().map((h,p)=>{const g=p<n.length;return f?l.jsx(X3e,{cell:h,cellIndex:p,originalRow:d,groupByColumns:n,columnSettings:r,isGroupByColumn:g,isTablePrintDisplayMode:s,tableAppearance:i},h.id):l.jsx(Q3e,{cell:h,cellIndex:p,visibleRowIndex:u,originalRow:d,rows:a,groupByColumns:n,columnSettings:r,isGroupByColumn:g,isTablePrintDisplayMode:s,tableAppearance:i},h.id)})},c.id)})}):l.jsx($d,{children:l.jsx(Or,{className:"border-b-0 hover:bg-transparent",children:l.jsx(Wn,{colSpan:t.length,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:"No results."})})})}function X3e({cell:e,cellIndex:t,originalRow:n,groupByColumns:r,columnSettings:s,isGroupByColumn:o,isTablePrintDisplayMode:i,tableAppearance:a}){const c=r.findIndex(u=>u.alias===n.subtotalLevel);if(t===c){const u=r.length-c;return l.jsx(Wn,{colSpan:u,...hd({tableAppearance:a,className:m.cn("px-4 font-medium text-foreground/90",i&&"border-gray-300 font-semibold text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}else{if(t<c)return l.jsx(Wn,{...hd({tableAppearance:a,className:m.cn("px-4 font-medium text-foreground/90",i&&"border-gray-300 font-semibold text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id);if(o&&t>c)return null}if(!o){const u=e.column.id,d=s[u],f=(d==null?void 0:d.textAlign)||"right";return l.jsx(Wn,{...hd({tableAppearance:a,className:m.cn("px-4 font-semibold text-foreground/90",f==="right"?"text-right":f==="center"?"text-center":"text-left",i&&"border-gray-300 text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}return null}function Q3e({cell:e,cellIndex:t,visibleRowIndex:n,originalRow:r,rows:s,groupByColumns:o,columnSettings:i,isGroupByColumn:a,isTablePrintDisplayMode:c,tableAppearance:u}){const d=e.column.id,f=i[d],h=(f==null?void 0:f.textAlign)||(a?"left":"right");if(a){if(c)return l.jsx(Wn,{...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90","align-top",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id);let p=!0,g=1;if(n>0){const x=o.map(v=>v.alias||v.name),y=s[n-1].original;if(!y.isSubtotal&&!y.isGrandTotal){let v=!0;for(let S=0;S<=t;S++)if(r[x[S]]!==y[x[S]]){v=!1;break}v&&(p=!1)}}if(!p)return null;const b=o.map(x=>x.alias||x.name);for(let x=n+1;x<s.length;x++){const y=s[x].original;if(y.isSubtotal||y.isGrandTotal)break;let v=!0;for(let S=0;S<=t;S++)if(r[b[S]]!==y[b[S]]){v=!1;break}if(v)g++;else break}return l.jsx(Wn,{rowSpan:g,...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90","align-top",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}return l.jsx(Wn,{...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90",h==="right"?"text-right":h==="center"?"text-center":"text-left",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}function m9({grandTotalRow:e,groupByColumns:t,pivotSchema:n,columnSettings:r,card:s,isTablePrintDisplayMode:o,tableAppearance:i,valueFormatPreferences:a,resolveBoundCurrency:c}){var g,b;if(!e)return null;const u=!!(s!=null&&s.sql),d=e.aggregate||"SUM",f=(b=(g=s==null?void 0:s.config)==null?void 0:g.rowAggregates)==null?void 0:b.find(x=>x.groupLevel==="ALL"),h=f==null?void 0:f.label,p=tJ(d,h);return o?l.jsxs(Or,{style:i.grandTotalRowStyle,className:m.cn("border-t-2 border-gray-300 bg-gray-100 font-semibold","print:break-inside-avoid print:border-gray-400 print:bg-gray-200"),children:[l.jsx(Wn,{colSpan:t.length,...Vc({tableAppearance:i,overflow:"visible",className:"border-r px-4 font-semibold border-gray-300 text-foreground print:border-gray-400"}),children:p}),n.filter(x=>x.isMetricColumn).map((x,y)=>{var _,k,I;const v=x.alias,S=e[v],N=Jl({card:s,columnKey:v,metricId:(I=(k=(_=s.config)==null?void 0:_.metricColumns)==null?void 0:k[y])==null?void 0:I.id}),C=Zh({card:s,columnId:v,metricIndex:y,groupByColumnCount:t.length,columnSettingsMap:r,valueFormatPreferences:a,boundCurrency:N?c(N):void 0}),j=P0(S,v,C,u);return l.jsx(Wn,{...Vc({tableAppearance:i,overflow:"visible",className:"border-r px-4 text-right font-semibold text-foreground last:border-r-0 border-gray-300 print:border-gray-400"}),children:j},v)})]}):l.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t border-border/60 bg-muted/95",style:i.grandTotalRowStyle,children:l.jsxs(Or,{className:"border-b-0",style:i.grandTotalRowStyle,children:[l.jsx(Wn,{colSpan:t.length,...Vc({tableAppearance:i,className:"px-4 font-semibold text-foreground/90"}),children:p}),n.filter(x=>x.isMetricColumn).map((x,y)=>{var _,k,I;const v=x.alias,S=e[v],N=Jl({card:s,columnKey:v,metricId:(I=(k=(_=s.config)==null?void 0:_.metricColumns)==null?void 0:k[y])==null?void 0:I.id}),C=Zh({card:s,columnId:v,metricIndex:y,groupByColumnCount:t.length,columnSettingsMap:r,valueFormatPreferences:a,boundCurrency:N?c(N):void 0}),j=P0(S,v,C,u);return l.jsx(Wn,{...Vc({tableAppearance:i,className:"numeric px-4 text-right font-semibold tabular-nums text-foreground/90"}),children:j},v)})]})})}function J3e({children:e,className:t,style:n,usePlainWrapper:r}){return r?l.jsx("div",{style:n,className:t,onMouseDown:s=>s.stopPropagation(),children:e}):l.jsxs(il,{style:n,className:t,onMouseDown:s=>s.stopPropagation(),children:[e,l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-20"})]})}function eI({card:e,data:t,groupByColumns:n=[],pivotSchema:r=[],paginationMetadata:s,onPaginationChange:o,onAggregationChange:i,isLoading:a}){var ue,fe;const c=w.useMemo(()=>Object.keys(t[0]||{}),[t]),{preferences:u,resolveBoundCurrency:d}=ka(e,c),{displayPreferences:f,shouldShowElement:h}=sl(),p=w.useMemo(()=>n3(),[]),g=!!(e!=null&&e.sql),{setCard:b,updateCardInFrame:x,updatePageSize:y}=m.useEditorActions(),{columnSettings:v,columnSettingsOpen:S,activeColumnId:N,tempColumnSettings:C,isVisualEditing:j,openColumnSettings:_,applyColumnSettings:k,resetColumnSettings:I,resetAllColumnSettings:T,setColumnSettingsOpen:E,setTempColumnSettings:D}=L3e(e,t),M=s3({displayMode:f.mode,isVisualEditing:j}),A=M.isPrint,{columnSizing:P,onColumnSizingChange:O}=t3({card:e}),$=Q_("aggregateTable",(fe=(ue=e==null?void 0:e.preferences)==null?void 0:ue.tablePrefs)==null?void 0:fe.density,M.mode==="document-print"?"document":"appearance"),V=$.densitySpec,[U,R]=w.useState(null),[q,W]=w.useState(null),F=w.useRef(!1),Z=w.useRef(!1),K=w.useMemo(()=>h_(n,e.config),[e.config,n]),Y=w.useMemo(()=>m_(r,e.config),[e.config,r]),X=w.useMemo(()=>G5(t,K),[t,K]),z=w.useMemo(()=>K5(t),[t]),B=w.useMemo(()=>G3e({groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isVisualEditing:j,isTablePrintDisplayMode:A,onOpenColumnSettings:_,onAggregationChange:i,valueFormatPreferences:u,resolveBoundCurrency:d}),[K,Y,v,e,j,A,_,i,u,d]),[{pageIndex:H,pageSize:L},G]=w.useState({pageIndex:0,pageSize:M.allowPagination?50:Number.MAX_SAFE_INTEGER}),J=M.allowPagination?L:Number.MAX_SAFE_INTEGER,oe=!!s&&M.allowPagination,Q=H_({data:X,columns:B,getCoreRowModel:B_(),getPaginationRowModel:!oe&&M.allowPagination?V_():void 0,manualPagination:oe||!M.allowPagination,pageCount:oe?s.pageCount:void 0,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:O,state:{pagination:oe?{pageIndex:(s.page||1)-1,pageSize:s.pageSize||50}:{pageIndex:H,pageSize:L},columnSizing:P},onPaginationChange:oe?void 0:G}),{setRowSelection:ae,paginationMode:ie}=cre({data:X,card:e,pageSize:J,paginationMetadata:s,onPaginationChange:o}),le=()=>{if(!U||!q||U===q.colId){R(null),W(null);return}const pe=SB(e,K,Y,{draggingColumnId:U,targetColumnId:q.colId,side:q.side});if(!pe){R(null),W(null);return}const ge=Q.getAllLeafColumns().map(se=>se.id),de=ge.indexOf(U),ye=ge.indexOf(q.colId);if(de===-1||ye===-1){R(null),W(null);return}const ce=[...ge];ce.splice(de,1);const re=q.side==="before"?ye>de?ye-1:ye:ye>de?ye:ye+1;ce.splice(re,0,U);const ee={...e,config:pe};b(ee),x(ee),Q.setColumnOrder(ce),R(null),W(null)};return!t||t.length===0?l.jsx("div",{className:"flex h-full w-full items-center justify-center",children:l.jsx(Vd,{size:"md",color:"muted","aria-label":"Loading data"})}):l.jsxs("div",{className:"flex h-full w-full flex-col gap-2",children:[l.jsxs(J3e,{style:$.containerStyle,usePlainWrapper:M.usePlainWrapper,className:m.cn("data-table-scroll-container relative h-full rounded-none border border-border/60 bg-muted/20",A&&"overflow-visible"),children:[a&&ie==="server"&&l.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:l.jsx(Vd,{size:"md",color:"muted","aria-label":"Loading data"})}),l.jsx("div",{className:m.cn("relative",A&&"border border-gray-300 print:border-gray-400"),children:l.jsxs("table",{className:m.cn("w-full text-sm [border-spacing:0]",A&&"print:break-inside-avoid"),onMouseDown:pe=>pe.stopPropagation(),"data-table-type":"aggregate","data-group-by-count":K.length,"data-has-grand-total":!!z,children:[l.jsx(Pm,{style:$.headerStyle,className:m.cn("[&_tr]:border-b-0",!A&&"bg-muted",A&&"bg-gray-50 text-foreground print:table-header-group print:bg-gray-100"),children:Q.getHeaderGroups().map(pe=>l.jsx(Or,{children:pe.headers.map((ge,de)=>{const ye=de===pe.headers.length-1,ce=M.showEditorControls,re=U===ge.column.id,ee=(q==null?void 0:q.colId)===ge.column.id;return l.jsxs(hs,{colSpan:ge.colSpan,draggable:ce,onMouseDownCapture:se=>{var he,_e;const ne=se.target;F.current=!!((he=ne.closest)!=null&&he.call(ne,"[data-resize-handle]")),Z.current=!!((_e=ne.closest)!=null&&_e.call(ne,"[data-grip-handle]"))},onDragStart:se=>{if(ce){if(F.current||!Z.current){se.preventDefault();return}se.dataTransfer.effectAllowed="move",se.dataTransfer.setData("text/column-id",ge.column.id),R(ge.column.id)}},onDragOver:se=>{if(!M.showEditorControls||!U||U===ge.column.id)return;se.preventDefault();const ne=se.currentTarget.getBoundingClientRect(),he=ne.left+ne.width/2,_e={colId:ge.column.id,side:se.clientX<he?"before":"after"};if(!SB(e,K,Y,{draggingColumnId:U,targetColumnId:_e.colId,side:_e.side})){W(null);return}W(_e)},onDrop:se=>{M.showEditorControls&&(se.preventDefault(),le())},onDragEnd:()=>{R(null),W(null)},style:{...$.headerCellStyle,width:ge.getSize(),minWidth:ge.getSize(),maxWidth:ye?void 0:ge.getSize(),position:A?"relative":void 0,transition:"none",overflow:"hidden"},className:m.cn("h-auto border-b border-transparent px-4 py-2 align-middle font-medium uppercase tracking-[0.08em] text-muted-foreground",V.header,$.headerTextClassName,!A&&"relative bg-muted/95",M.allowStickyHeader&&$.isHeaderSticky&&"sticky top-0 z-10 supports-[backdrop-filter]:bg-muted/80 supports-[backdrop-filter]:backdrop-blur-sm",A&&"border-gray-300 font-semibold text-foreground print:border-gray-400",re&&"opacity-40"),children:[!A&&l.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 bottom-0 h-px bg-border",style:$.headerDividerStyle}),ge.isPlaceholder?null:l.jsxs(l.Fragment,{children:[ee&&(q==null?void 0:q.side)==="before"&&l.jsx("div",{className:"pointer-events-none absolute -left-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),ee&&(q==null?void 0:q.side)==="after"&&l.jsx("div",{className:"pointer-events-none absolute -right-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),pi(ge.column.columnDef.header,ge.getContext()),M.showEditorControls&&l.jsx(Kf,{header:ge,isResizing:ge.column.getIsResizing(),inset:ye})]})]},ge.id)})},pe.id))}),l.jsx(Z3e,{table:Q,columns:B,groupByColumns:K,columnSettings:v,isTablePrintDisplayMode:A,disableRowTransitions:p,tableAppearance:$}),A&&l.jsx(m9,{grandTotalRow:z,groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isTablePrintDisplayMode:A,tableAppearance:$,valueFormatPreferences:u,resolveBoundCurrency:d}),!A&&z&&l.jsx(m9,{grandTotalRow:z,groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isTablePrintDisplayMode:A,tableAppearance:$,valueFormatPreferences:u,resolveBoundCurrency:d})]})})]}),M.allowPagination&&h("showPagination")&&(ie==="server"||Q.getFilteredRowModel().rows.length>10)&&l.jsx(U_,{totalColumns:B.length,pageCount:ie==="server"&&s?s.pageCount||0:Q.getPageCount(),pageIndex:Q.getState().pagination.pageIndex,pageSize:Q.getState().pagination.pageSize,rowCount:ie==="server"&&s?s.totalCount||0:Q.getFilteredRowModel().rows.length,selectedRowCount:Q.getFilteredSelectedRowModel().rows.length,setPageIndex:Q.setPageIndex,setPageSize:Q.setPageSize,canPreviousPage:ie==="server"&&s?s.hasPrevPage??!1:Q.getCanPreviousPage(),canNextPage:ie==="server"&&s?s.hasNextPage??!1:Q.getCanNextPage(),previousPage:Q.previousPage,nextPage:Q.nextPage,onPageSizePreferenceChange:M.showEditorControls?y:void 0,onClearSelection:()=>ae({}),paginationMode:ie,appearance:$.pagination}),h("showColumnSettings")&&l.jsx(QL,{column:N?Q.getColumn(N)??null:null,settings:C,onSettingsChange:D,onApply:k,onReset:I,onResetAll:T,open:S,onOpenChange:E,tableType:"aggregate",isSqlCard:g})]})}const e$e=e=>{const t=window.getSelection();if(!t||t.rangeCount===0)return 0;const n=t.getRangeAt(0),r=n.cloneRange();return r.selectNodeContents(e),r.setEnd(n.endContainer,n.endOffset),r.toString().length},t$e=(e,t)=>{var i,a;const n=window.getSelection(),r=document.createRange();let s=0;const o=c=>{var u;if(c.nodeType===Node.TEXT_NODE){const d=((u=c.textContent)==null?void 0:u.length)||0;if(s+d>=t)return r.setStart(c,t-s),r.setEnd(c,t-s),!0;s+=d}else for(let d=0;d<c.childNodes.length;d++)if(o(c.childNodes[d]))return!0;return!1};if(!o(e)&&e.childNodes.length>0){const c=e.childNodes[e.childNodes.length-1];c.nodeType===Node.TEXT_NODE&&(r.setStart(c,((i=c.textContent)==null?void 0:i.length)||0),r.setEnd(c,((a=c.textContent)==null?void 0:a.length)||0))}n==null||n.removeAllRanges(),n==null||n.addRange(r)};function cD({value:e,onSave:t,placeholder:n="Click to add content...",className:r,disabled:s=!1,isDynamicText:o=!1}){const i=w.useRef(null),[a,c]=w.useState(!1),[u,d]=w.useState(!1),f=w.useRef(void 0),h=w.useRef(e),[p,g]=w.useState(e),b=w.useRef(!1),y=m.useDashboardStore(k=>k.isVisualEditing)&&!s&&!o;w.useEffect(()=>{!b.current&&i.current&&(i.current.innerHTML=e||"",b.current=!0)},[e]),w.useEffect(()=>{!a&&e!==p&&(g(e),i.current&&b.current&&(i.current.innerHTML=e||""),h.current=e)},[e,a,p]);const v=w.useCallback(()=>{if(!i.current||!y)return;d(!0);const k=i.current.innerHTML;g(k),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{var T;const I=((T=i.current)==null?void 0:T.innerHTML)||"";if(I!==h.current){const E=i.current?e$e(i.current):0;t(I),h.current=I,g(I),d(!1),setTimeout(()=>{i.current&&a&&(i.current.focus(),t$e(i.current,E))},0)}},500)},[y,t,a]),S=w.useCallback(k=>{k.preventDefault();const I=k.clipboardData.getData("text/plain"),T=k.clipboardData.getData("text/html");let E="";if(T&&!I){const P=document.createElement("div");P.innerHTML=T,P.querySelectorAll("script, style").forEach(O=>O.remove()),P.querySelectorAll("p, div, br").forEach(O=>{if(O.tagName==="BR")O.replaceWith(`
|
|
792
|
+
color: hsl(${Math.max(0,Math.min(120-120*b,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(o&&n.skipInitialOnChange)&&n.onChange(s),o=!1,s}return i.updateDeps=a=>{r=a},i}function a9(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const CLe=(e,t)=>Math.abs(e-t)<1.01,NLe=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let xx;const iD=()=>{if(xx!==void 0)return xx;if(typeof navigator>"u")return xx=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return xx=!0;const e=navigator.maxTouchPoints;return xx=navigator.platform==="MacIntel"&&e!==void 0&&e>0},l9=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},jLe=e=>e,kLe=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let o=0;o<r;o++)s[o]=t+o;return s},_Le=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:a,height:c}=i;t({width:Math.round(a),height:Math.round(c)})};if(s(l9(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const a=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(l9(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},JN={passive:!0},ILe=typeof window>"u"?!0:"onscrollend"in window,TLe=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const o=e.options.useScrollendEvent&&ILe;let i=0;const a=o?null:NLe(s,()=>t(i,!1),e.options.isScrollingResetDelay),c=f=>()=>{i=n(r),a==null||a(),t(i,f)},u=c(!0),d=c(!1);return r.addEventListener("scroll",u,JN),o&&r.addEventListener("scrollend",d,JN),()=>{r.removeEventListener("scroll",u),o&&r.removeEventListener("scrollend",d)}},ELe=(e,t)=>TLe(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),DLe=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),o=n.itemSizeCache.get(s);if(o!==void 0)return o}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},MLe=(e,{adjustments:t=0,behavior:n},r)=>{var s,o;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},ALe=MLe;class RLe{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const i=()=>{const a=o.target,c=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);for(const[u,d]of this.elementsCache)if(d===a){this.elementsCache.delete(u);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(a,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:jLe,rangeExtractor:kLe,onChange:()=>{},measureElement:DLe,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in n){const p=n[h];p!==void 0&&(o[h]=p)}const i=this.options;let a=null,c=null,u=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,p=o.count,g=this.getMeasurements(),b=h>0?((r=g[0])==null?void 0:r.key)??i.getItemKey(0):null,x=h>0?((s=g[h-1])==null?void 0:s.key)??i.getItemKey(h-1):null;if(p!==h||h>0&&p>0&&(o.getItemKey(0)!==b||o.getItemKey(p-1)!==x)){u=!0;const S=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??g[0]:null;S&&(a=[S.key,this.getScrollOffset()-S.start]);const N=o.followOnAppend===!0?"auto":o.followOnAppend||null;N&&p>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(p-1)!==x)&&(c=N)}}this.options=o,u&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(a&&this.scrollOffset!==null){const[h,p]=a,g=this.getMeasurements(),{count:b,getItemKey:x}=this.options;let y=0;for(;y<b&&x(y)!==h;)y++;if(y<b){const v=g[y];if(v){const S=v.start+p;S!==this.scrollOffset&&(f=S-this.scrollOffset,this.scrollOffset=S,d=!0)}}}(d||c)&&(this.pendingScrollAnchor=[d?a[0]:null,d?a[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=sp(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:process.env.NODE_ENV!=="production"&&"maybeNotify",debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const a=this.getScrollOffset();this.scrollDirection=i?a===o?this.scrollDirection:a<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},a=()=>{this._iosTouching=!1,!(!iD()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,JN),o.addEventListener("touchend",a,JN),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",a),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[o,i,a,c]=s;o!==null&&!a&&(iD()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),a&&this.scrollToEnd({behavior:a})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=sp(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,s,o,i,a,c,u)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i,lanes:a,laneAssignmentMode:c,gap:u}),{key:!1}),this.getMeasurements=sp(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i,lanes:a,laneAssignmentMode:c,gap:u},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),a===1){const y=n*2;let v=this._flatMeasurements;if(!v||v.length<y){const C=new Float64Array(y);v&&h>0&&C.set(v.subarray(0,h*2)),v=C,this._flatMeasurements=v}let S;if(h===0)S=r+s;else{const C=h-1;S=v[C*2]+v[C*2+1]+u}for(let C=h;C<n;C++){const j=o(C),_=f.get(j),k=typeof _=="number"?_:this.options.estimateSize(C);v[C*2]=S,v[C*2+1]=k,S+=k+u}const N=SLe(n,v,o);return this.measurementsCache=N,N}const p=this.measurementsCache.slice(0,h),g=new Array(a).fill(void 0),b=new Float64Array(a);let x=0;for(let y=0;y<h;y++){const v=p[y];v&&(g[v.lane]===void 0&&x++,g[v.lane]=y,b[v.lane]=v.end)}for(let y=h;y<n;y++){const v=o(y),S=this.laneAssignments.get(y);let N,C;const j=c==="estimate"||f.has(v);if(S!==void 0&&this.options.lanes>1){N=S;const T=g[N],E=T!==void 0?p[T]:void 0;C=E?E.end+u:r+s}else if(x===a){let T=0,E=b[0],D=g[0];for(let M=1;M<a;M++){const A=b[M];(A<E||A===E&&g[M]<D)&&(T=M,E=A,D=g[M])}N=T,C=E+u,j&&this.laneAssignments.set(y,N)}else N=y%this.options.lanes,C=r+s,j&&this.laneAssignments.set(y,N);const _=f.get(v),k=typeof _=="number"?_:this.options.estimateSize(y),I=C+k;p[y]={index:y,start:C,size:k,end:I,key:v,lane:N},g[N]===void 0&&x++,g[N]=y,b[N]=I}return this.measurementsCache=p,p},{key:process.env.NODE_ENV!=="production"&&"getMeasurements",debug:()=>this.options.debug}),this.calculateRange=sp(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>n.length===0||r===0?(this.range=null,null):(this.range=FLe(n,r,s,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:process.env.NODE_ENV!=="production"&&"calculateRange",debug:()=>this.options.debug}),this.getVirtualIndexes=sp(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,i)=>o===null||i===null?[]:n({startIndex:o,endIndex:i,overscan:r,count:s}),{key:process.env.NODE_ENV!=="production"&&"getVirtualIndexes",debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-o),a=Math.min(this.options.count-1,s+o);return n>=i&&n<=a}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((i,a)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(a))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),o=this.elementsCache.get(s);o!==n&&(o&&this.observer.unobserve(o),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,o;if(n<0||n>=this.options.count)return;let i,a,c;const u=this._flatMeasurements;if(this.options.lanes===1&&u!==null)c=this.options.getItemKey(n),a=u[n*2],i=u[n*2+1];else{const h=this.measurementsCache[n];if(!h)return;c=h.key,a=h.start,i=h.size}const d=this.itemSizeCache.get(c)??i,f=r-d;if(f!==0){const h=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,p=h?this.getTotalSize():0,g=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:a,size:i,end:a+i,lane:0},f,this):a<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(c)||this.scrollDirection!=="backward"));(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-p):g&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=sp(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,i=n.length;o<i;o++){const a=n[o],c=r[a];s.push(c)}return s},{key:process.env.NODE_ENV!=="production"&&"getVirtualItems",debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,o=this.options.lanes===1&&s!=null,i=hre(0,r.length-1,o?a=>s[a*2]:a=>a9(r[a]).start,n);return a9(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const a=this.getMaxScrollOffset();return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=o+s-this.options.scrollPaddingEnd)r="end";else if(i.start<=o+this.options.scrollPaddingStart)r="start";else return[o,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const a=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,i.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const o=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getOffsetForIndex(n,r);if(!o)return;const[i,a]=o,c=this.now();this.scrollState={index:n,align:a,behavior:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,o=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:o,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const o=r.length-1,i=this._flatMeasurements;i!=null?s=i[o*2]+i[o*2+1]:s=((n=r[o])==null?void 0:n.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(a=>a===null);){const a=r[i];o[a.lane]===null&&(o[a.lane]=a.end),i--}s=Math.max(...o.filter(a=>a!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(process.env.NODE_ENV!=="production"&&this.options.debug&&console.info("correction",t),iD()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,o=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&CLe(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const a=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),u=this.scrollState.behavior==="smooth"&&c>a;this.scrollState.lastTargetOffset=s,u||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:u?"smooth":"auto"})}this.scheduleScrollReconcile()}}const hre=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,o=n(s);if(o<r)e=s+1;else if(o>r)t=s-1;else return s}return e>0?e-1:0};function PLe(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,o=e[s*2];if(o<n)r=s+1;else if(o>n)t=s-1;else return s}return r>0?r-1:0}function FLe(e,t,n,r,s){const o=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:o};if(r===1&&s!==null){const u=PLe(s,o,n);let d=u;const f=n+t;for(;d<o&&s[d*2]+s[d*2+1]<f;)d++;return{startIndex:u,endIndex:d}}let a=hre(0,o,u=>e[u].start,n),c=a;if(r===1)for(;c<o&&e[c].end<n+t;)c++;else if(r>1){const u=Array(r).fill(0);for(;c<o&&u.some(f=>f<n+t);){const f=e[c];u[f.lane]=f.end,c++}const d=Array(r).fill(n+t);for(;a>=0&&d.some(f=>f>=n);){const f=e[a];d[f.lane]=f.start,a--}a=Math.max(0,a-a%r),c=Math.min(o,c+(r-1-c%r))}return{startIndex:a,endIndex:c}}const aD=typeof document<"u"?te.useLayoutEffect:te.useEffect;function OLe({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=te.useReducer(u=>u+1,0)[1],o=te.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const i=u=>{const d=o.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const y=u.options.horizontal?"width":"height";d.container.style[y]=`${f}px`}const h=!!u.options.horizontal,p=d.mode==="transform",g=h?"left":"top",b=u.options.scrollMargin,x=u.getVirtualItems();for(const y of x){const v=y.start-b,S=u.elementsCache.get(y.key);S&&d.lastPositions.get(S)!==v&&(d.lastPositions.set(S,v),p?S.style.transform=h?`translate3d(${v}px, 0, 0)`:`translate3d(0, ${v}px, 0)`:S.style[g]=`${v}px`)}},a={...r,onChange:(u,d)=>{var f;const h=o.current;let p=!0;if(h.enabled){i(u);const g=u.range,b=h.prevRange;p=!b||b.isScrolling!==u.isScrolling||b.startIndex!==(g==null?void 0:g.startIndex)||b.endIndex!==(g==null?void 0:g.endIndex),p&&(h.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:u.isScrolling}:null)}p&&(e&&d?Dr.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=te.useState(()=>{const u=new RLe(a);return Object.assign(u,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=u.getTotalSize();f.lastSize=h;const p=u.options.horizontal?"width":"height";d.style[p]=`${h}px`}}})});return c.setOptions(a),aD(()=>c._didMount(),[]),aD(()=>c._willUpdate()),aD(()=>{i(c)}),c}function X_(e){return OLe({observeElementRect:_Le,observeElementOffset:ELe,scrollToFn:ALe,...e})}function LLe(e){if(!e)return!1;const t=/Safari/i.test(e),n=/Chrome|Chromium|CriOS|Edg|OPR|Firefox|FxiOS|Android/i.test(e);return t&&!n}function n3(){return typeof navigator>"u"?!1:LLe(navigator.userAgent)}const $Le={compact:"compact",comfortable:"comfortable",spacious:"spacious"};function Q_(e,t,n="appearance"){const{compiledAppearance:r}=m.useAppearance();return w.useMemo(()=>zLe({compiledAppearance:r,surface:e,cardDensity:t,layoutScope:n}),[t,r,n,e])}function zLe({compiledAppearance:e,surface:t,cardDensity:n,layoutScope:r="appearance"}){var R,q,W,F,Z,K,Y,X,z,B,H,L,G,J,oe,Q,ae,ie,le,ue,fe,pe,ge,de,ye,ce,re,ee,se,ne,he,_e,Le,Ue,je,Xe,Ze,at,Be,lt,Te,nt,Oe,He,qe,Ae,Qe,ct,It,yt,kt;const s=ULe(e,t),o=e.scheme.tokens,i=r==="document",a=n??WLe(HLe(s)),c=zPe(a),u=((R=s.container)==null?void 0:R.borderRadius)??((q=o==null?void 0:o.radius)==null?void 0:q.table)??((W=o==null?void 0:o.radius)==null?void 0:W.card),d=(F=o==null?void 0:o.radius)==null?void 0:F.control,f=VLe(e),h=i?void 0:((Z=s.cell)==null?void 0:Z.paddingX)??f,p=BLe(e),g=i||n?void 0:((K=s.cell)==null?void 0:K.paddingY)??p,b=to({backgroundColor:(Y=s.container)==null?void 0:Y.background,borderColor:(X=s.container)==null?void 0:X.borderColor,borderRadius:u,boxShadow:(z=s.container)==null?void 0:z.shadow}),x=to({backgroundColor:(B=s.header)==null?void 0:B.background,color:(H=s.header)==null?void 0:H.foreground,borderColor:(L=s.header)==null?void 0:L.dividerColor}),y=to({backgroundColor:(G=s.header)==null?void 0:G.background,color:(J=s.header)==null?void 0:J.foreground,borderColor:(oe=s.header)==null?void 0:oe.dividerColor,paddingLeft:h,paddingRight:h,fontWeight:(Q=s.header)==null?void 0:Q.fontWeight,textTransform:((ae=s.header)==null?void 0:ae.uppercase)===void 0?void 0:s.header.uppercase?"uppercase":"none"}),v=to({backgroundColor:(ie=s.header)==null?void 0:ie.dividerColor}),S=((le=s.header)==null?void 0:le.uppercase)===!1?"normal-case semaphor-table-header-normal-case":void 0,N=((ue=s.header)==null?void 0:ue.sticky)!==!1,C=i||(fe=s.cell)==null?void 0:fe.wrap,j=C==="wrap",_=i||(pe=s.row)==null?void 0:pe.height,k=to({borderColor:(ge=s.row)==null?void 0:ge.dividerColor,height:_}),I=to({backgroundColor:((de=s.row)==null?void 0:de.zebraBackground)??((ye=o==null?void 0:o.color)==null?void 0:ye.muted)}),T=(ce=s.row)!=null&&ce.hoverBackground?"semaphor-table-row-hover-background":void 0,E=to({paddingLeft:h,paddingRight:h,paddingTop:g,paddingBottom:g,verticalAlign:(re=s.cell)==null?void 0:re.verticalAlign,whiteSpace:C===void 0?void 0:C==="wrap"?"normal":"nowrap",overflowWrap:C==="wrap"?"anywhere":void 0}),D=to({overflow:j?void 0:"hidden",textOverflow:j?void 0:"ellipsis"}),M=to({borderBottomColor:(ee=s.row)==null?void 0:ee.dividerColor}),A=j?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap",P=to({backgroundColor:(se=s.subtotal)==null?void 0:se.background,color:(ne=s.subtotal)==null?void 0:ne.foreground,fontWeight:(he=s.subtotal)==null?void 0:he.fontWeight,borderColor:(_e=s.row)==null?void 0:_e.dividerColor}),O=to({backgroundColor:(Le=s.subtotal)==null?void 0:Le.background,color:(Ue=s.subtotal)==null?void 0:Ue.foreground,fontWeight:(je=s.subtotal)==null?void 0:je.fontWeight}),$=to({backgroundColor:(Xe=s.grandTotal)==null?void 0:Xe.background,color:(Ze=s.grandTotal)==null?void 0:Ze.foreground,fontWeight:(at=s.grandTotal)==null?void 0:at.fontWeight,borderColor:((Be=s.grandTotal)==null?void 0:Be.borderColor)??((lt=s.row)==null?void 0:lt.dividerColor)}),V=to({backgroundColor:(Te=s.grandTotal)==null?void 0:Te.background,color:(nt=s.grandTotal)==null?void 0:nt.foreground,fontWeight:(Oe=s.grandTotal)==null?void 0:Oe.fontWeight,borderColor:(He=s.grandTotal)==null?void 0:He.borderColor}),U={containerStyle:to({backgroundColor:(qe=s.pagination)==null?void 0:qe.background,color:(Ae=s.pagination)==null?void 0:Ae.foreground,borderColor:(Qe=s.pagination)==null?void 0:Qe.borderColor}),controlStyle:to({borderColor:(ct=s.pagination)==null?void 0:ct.borderColor,borderRadius:d,color:(It=s.pagination)==null?void 0:It.foreground}),textStyle:to({color:(yt=s.pagination)==null?void 0:yt.foreground})};return{densitySpec:c,containerStyle:b,headerStyle:x,headerCellStyle:y,headerDividerStyle:v,dataRowStyle:k,dataRowClassName:T,cellStyle:E,rowDividerCellStyle:M,subtotalRowStyle:P,subtotalCellStyle:O,grandTotalRowStyle:$,grandTotalCellStyle:V,pagination:U,headerTextClassName:S,isHeaderSticky:N,dataRowHeight:_,stripedDataRowStyle:I,cellOverflowStyle:D,cellContentClassName:A,isCellWrapping:j,hasHoverRowStyle:!!((kt=s.row)!=null&&kt.hoverBackground),getDataRowStyle:(Mt,vt)=>{var Pe,Fe,Ge;const St=vt!=null&&vt.isSelected?(Pe=s.row)==null?void 0:Pe.selectedBackground:void 0,ke=(Fe=s.row)!=null&&Fe.zebra&&Mt%2===1&&!(vt!=null&&vt.isSelected)&&!(vt!=null&&vt.suppressZebra)?s.row.zebraBackground:void 0,Ee=(Ge=s.row)!=null&&Ge.hoverBackground?{"--semaphor-table-row-hover-background":s.row.hoverBackground}:{};return to({...k,...Ee,backgroundColor:St??ke})}}}function BLe(e){var r,s,o,i;const t=(s=(r=e.scheme.tokens)==null?void 0:r.spacing)==null?void 0:s.tableCellY,n=(i=(o=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens)==null?void 0:o.spacing)==null?void 0:i.tableCellY;return t!==void 0&&t!==n?t:void 0}function VLe(e){var r,s,o,i;const t=(s=(r=e.scheme.tokens)==null?void 0:r.spacing)==null?void 0:s.tableCellX,n=(i=(o=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens)==null?void 0:o.spacing)==null?void 0:i.tableCellX;return t!==void 0&&t!==n?t:void 0}function HLe(e){var n,r;const t=(r=(n=pu.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes.light.components)==null?void 0:n.table)==null?void 0:r.density;return e.density!==void 0&&e.density!==t?e.density:void 0}function ULe(e,t){var s,o;const n=e.table,r=t==="table"?(s=e.scheme.components)==null?void 0:s.table:(o=e.scheme.components)==null?void 0:o[t];return qLe(n,r)}function qLe(e,t){return{density:(t==null?void 0:t.density)??(e==null?void 0:e.density),container:{...e==null?void 0:e.container,...t==null?void 0:t.container},header:{...e==null?void 0:e.header,...t==null?void 0:t.header},row:{...e==null?void 0:e.row,...t==null?void 0:t.row},cell:{...e==null?void 0:e.cell,...t==null?void 0:t.cell},subtotal:{...e==null?void 0:e.subtotal,...t==null?void 0:t.subtotal},grandTotal:{...e==null?void 0:e.grandTotal,...t==null?void 0:t.grandTotal},pagination:{...e==null?void 0:e.pagination,...t==null?void 0:t.pagination}}}function WLe(e){return e?$Le[e]:"compact"}function to(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}function GLe({tableAppearance:e,className:t,style:n}){return{style:{...e.headerCellStyle,...n},className:m.cn(t,e.densitySpec.header,e.headerTextClassName)}}function Eh({tableAppearance:e,className:t,style:n,divider:r="none",overflow:s="clip",textFlow:o="content"}){return r3({tableAppearance:e,className:t,style:{...r==="row"?e.rowDividerCellStyle:void 0,...n},overflow:s,textFlow:o})}function hd({tableAppearance:e,className:t,style:n,divider:r="none",overflow:s="clip",textFlow:o="content"}){return r3({tableAppearance:e,className:t,style:{...e.subtotalCellStyle,...r==="row"?e.rowDividerCellStyle:void 0,...n},overflow:s,textFlow:o})}function Vc({tableAppearance:e,className:t,style:n,overflow:r="clip"}){return r3({tableAppearance:e,className:t,style:{...e.grandTotalCellStyle,...n},overflow:r,textFlow:"direct"})}function Dh(e,t,n){return(n==null?void 0:n.textFlow)==="delegate"?m.cn(t):m.cn(t,e.cellContentClassName)}function r3({tableAppearance:e,className:t,style:n,overflow:r,textFlow:s}){const o=r==="clip";return{style:{...e.cellStyle,...n,...o?e.cellOverflowStyle:void 0},className:m.cn(t,o&&!e.isCellWrapping&&"overflow-hidden",s==="direct"&&!e.isCellWrapping&&"whitespace-nowrap",e.densitySpec.rowPad,e.densitySpec.cell)}}function s3({displayMode:e,isVisualEditing:t=!1,printBehavior:n="table-print-only",renderPlainWrapper:r=!1}){const s=n==="any-print"?nf(e):Wk(e),o=s?"document-print":t?"editor":"dashboard",i=!s;return{mode:o,isInteractive:i,isPrint:s,allowStickyHeader:i,allowPagination:i,allowVirtualization:i,allowRowSpan:i,showEditorControls:i&&t,usePlainWrapper:s||r}}const mre=["spacious","comfortable","standard","compact","dense"],KLe={spacious:"Spacious",comfortable:"Comfortable",standard:"Standard",compact:"Compact",dense:"Dense"},pre=["plain","filled","accent"],YLe={plain:"Plain",filled:"Filled",accent:"Accent"},gre=["full","outer","inner","horizontal","vertical","top","right","bottom","left","none"],ZLe={none:"None",outer:"Outer",inner:"Inner",horizontal:"Horizontal",vertical:"Vertical",top:"Top",right:"Right",bottom:"Bottom",left:"Left",full:"Full"},Nd={density:"compact",headerStyle:"filled",headerWrapText:!1,stripedRows:!1,gridLines:"horizontal",wrapText:!1},bre=["normal","medium","semibold","bold"],XLe={normal:"Normal",medium:"Medium",semibold:"Semibold",bold:"Bold"},QLe=["solid","dashed","dotted","double"],JLe={solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double"},ha={enabled:!1,backgroundColor:"#fafafa",textColor:"#18181b",fontWeight:"medium",borderTop:!0,borderTopStyle:"solid",borderTopColor:"#e4e4e7"},xre={plain:{background:"#ffffff",color:"#3f3f46"},filled:{background:"#f4f4f5",color:"#27272a"},accent:{background:"#eef2ff",color:"#312e81"}};function e3e(e){return mre.includes(e)?e:Nd.density}function t3e(e){return pre.includes(e)?e:Nd.headerStyle}function n3e(e){return gre.includes(e)?e:Nd.gridLines}function r3e(e){return bre.includes(e)?e:ha.fontWeight}function s3e(e){return e==="solid"||e==="dashed"||e==="dotted"||e==="double"?e:ha.borderTopStyle}function o3(e){const t=e==null?void 0:e.tableStyle,n=t3e(t==null?void 0:t.headerStyle),r=xre[n],s=t==null?void 0:t.totals;return{density:e3e(e==null?void 0:e.density),headerStyle:n,headerBackgroundColor:(t==null?void 0:t.headerBackgroundColor)??r.background,headerTextColor:(t==null?void 0:t.headerTextColor)??r.color,headerWrapText:(t==null?void 0:t.headerWrapText)??Nd.headerWrapText,stripedRows:(t==null?void 0:t.stripedRows)??Nd.stripedRows,gridLines:n3e(t==null?void 0:t.gridLines),wrapText:(t==null?void 0:t.wrapText)??Nd.wrapText,totalsStyle:{enabled:(s==null?void 0:s.enabled)??ha.enabled,backgroundColor:(s==null?void 0:s.backgroundColor)??ha.backgroundColor,textColor:(s==null?void 0:s.textColor)??ha.textColor,fontWeight:r3e(s==null?void 0:s.fontWeight),borderTop:(s==null?void 0:s.borderTop)??ha.borderTop,borderTopStyle:s3e(s==null?void 0:s.borderTopStyle),borderTopColor:(s==null?void 0:s.borderTopColor)??ha.borderTopColor}}}function yre(e){switch(e){case"normal":return 400;case"medium":return 500;case"semibold":return 600;case"bold":return 700;default:return 500}}function o3e(e){return e==="double"?3:1}function i3e(e){switch(e){case"none":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"outer":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"inner":return"[&_tr]:border-b [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"vertical":return"[&_tr]:!border-b-0 [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"top":case"right":case"bottom":case"left":return"[&_tr]:!border-b-0 [&_th]:!border-b-0 [&_th]:!border-r-0 [&_td]:!border-r-0";case"full":return"[&_tr]:border-b [&_th]:border-r [&_td]:border-r [&_th:last-child]:!border-r-0 [&_td:last-child]:!border-r-0";case"horizontal":default:return"[&_tr]:border-b [&_th]:!border-r-0 [&_td]:!border-r-0"}}function a3e(e){if(!e)return"border border-border/60";switch(e){case"full":case"outer":return"border border-border/60";case"top":return"border-t border-border/60";case"right":return"border-r border-border/60";case"bottom":return"border-b border-border/60";case"left":return"border-l border-border/60";case"inner":case"horizontal":case"vertical":case"none":default:return"border-0"}}function l3e(e){return e?e==="full"||e==="inner"||e==="horizontal":!0}function c9(e){return e.mode==="clickFilter"}function c3e(e,t){if(!t||t.type==="metric")return e;if(t.type==="attribute"){const n=e.find(r=>r.field.id===t.field.id);return n?[n]:[]}return e}function u3e({children:e,className:t,scrollAreaRef:n,style:r,usePlainWrapper:s}){return s?l.jsx("div",{className:t,style:r,children:e}):l.jsxs(il,{ref:n,className:t,style:r,children:[e,l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-20"})]})}function d3e(e){var Ge,Pt,_t,Ft,Vt,Ht,Qn;const{card:t,isLoading:n,frameId:r,sheetId:s,onMultipleInteractions:o,onColumnReorder:i}=e,a=w.useRef(null),c=w.useRef(!1),u=w.useRef(!1),{columnSizing:d,onColumnSizingChange:f}=t3({card:t,columnSizing:e.columnSizing,onColumnSizingCommit:e.onColumnSizingChange,onResizeStateChange:e.onColumnResizeStateChange}),h=m.useDashboardStore(st=>st.isVisualEditing),{updatePageSize:p}=m.useEditorActions(),{displayPreferences:g,shouldShowElement:b}=sl(),x=s3({displayMode:g.mode,isVisualEditing:h}),y=x.showEditorControls&&!!i&&Yh(t),v=x.showEditorControls||e.showColumnResizeHandles,S=x.isPrint,N=Q_("table",(Pt=(Ge=t==null?void 0:t.preferences)==null?void 0:Ge.tablePrefs)==null?void 0:Pt.density,x.mode==="document-print"?"document":"appearance"),C=w.useMemo(()=>{var st;return o3((st=t==null?void 0:t.preferences)==null?void 0:st.tablePrefs)},[(_t=t==null?void 0:t.preferences)==null?void 0:_t.tablePrefs]),j=(Vt=(Ft=t==null?void 0:t.preferences)==null?void 0:Ft.tablePrefs)==null?void 0:Vt.tableStyle,_=!!(j!=null&&j.headerStyle||j!=null&&j.headerBackgroundColor||j!=null&&j.headerTextColor),k=(j==null?void 0:j.gridLines)!==void 0,I=(j==null?void 0:j.stripedRows)!==void 0,T=j==null?void 0:j.totals,E=!!(T!=null&&T.backgroundColor||T!=null&&T.textColor||T!=null&&T.fontWeight||(T==null?void 0:T.borderTop)!==void 0||T!=null&&T.borderTopStyle||T!=null&&T.borderTopColor),D=k?C.gridLines:void 0,M=_?{backgroundColor:C.headerBackgroundColor,color:C.headerTextColor}:void 0,A=E?{backgroundColor:C.totalsStyle.backgroundColor,color:C.totalsStyle.textColor,fontWeight:yre(C.totalsStyle.fontWeight),borderTopWidth:C.totalsStyle.borderTop?o3e(C.totalsStyle.borderTopStyle):0,borderTopStyle:C.totalsStyle.borderTopStyle,borderTopColor:C.totalsStyle.borderTopColor}:void 0,P=l3e(D),O=C.totalsStyle.enabled===!0,$=w.useMemo(()=>m.getInteractions(t.interactionConfig),[t.interactionConfig]),V=w.useMemo(()=>$.filter(c9),[$]),U=V.length>0,{table:R,columnSettingsToUse:q,getRowStyle:W,activeColumnId:F,activeColumnSettings:Z,activeColumnBaseStyle:K,handleColumnSettingsChange:Y,handleColumnBaseStyleChange:X,resetColumnSettings:z,resetAllColumnSettings:B,columnSettingsOpen:H,columns:L,setColumnSettingsOpen:G,totalColumns:J,totalRows:oe,paginationMode:Q,paginationMetadata:ae,contextTimezone:ie,browserTimezone:le,valueFormatPreferences:ue,resolveBoundCurrency:fe}=cre({...e,columnSizing:d,onColumnSizingChange:f,headerTextClassName:N.headerTextClassName,headerWrapText:C.headerWrapText,appearanceWrapText:N.isCellWrapping?!0:void 0,defaultSelectColumnVisible:U&&x.isInteractive}),pe=m.useResolvedCardConfig(t),{handlePointerInteraction:ge}=m.useEventEngine(t,r||"",s||"",o),de=w.useMemo(()=>$.some(st=>st.trigger!==void 0&&st.mode!=="clickFilter"),[$]),ye=w.useMemo(()=>n3(),[]),ce=w.useMemo(()=>typeof document<"u"&&"onscrollend"in document,[]),re=w.useMemo(()=>C.wrapText||Object.values(q??{}).some(st=>(st==null?void 0:st.textWrap)==="wrap"||(st==null?void 0:st.textWrap)==="preserve"),[q,C.wrapText]),ee=R.getRowModel().rows,se=R.getFilteredSelectedRowModel().rows,ne=se.length>0,he=R.getFilteredRowModel().rows,_e=w.useMemo(()=>e.totalsData?e.totalsData.map(st=>({original:st})):he,[he,e.totalsData]),Le=R.getVisibleLeafColumns(),[Ue,je]=w.useState(null),[Xe,Ze]=w.useState(null),at=()=>{const st=BPe({currentOrder:R.getAllLeafColumns().map(De=>De.id),draggingColId:Ue,dropTarget:Xe});if(st){if(!((i==null?void 0:i({draggingColumnId:Ue,targetColumnId:Xe.colId,side:Xe.side}))??!0)){je(null),Ze(null);return}R.setColumnOrder(st)}je(null),Ze(null)},Be=w.useMemo(()=>e.totalsByColumnId??(Q==="server"?{}:O?_te({rows:_e,columns:Le,columnSettings:q}):{}),[q,O,Q,e.totalsByColumnId,_e,Le]),lt=Object.keys(Be).length>0,Te=w.useMemo(()=>w5(t,Le.map(st=>st.id)),[t,Le]),nt=!S&&Yh(t),Oe=w.useMemo(()=>{var st,De;return ky((De=(st=t==null?void 0:t.preferences)==null?void 0:st.tablePrefs)==null?void 0:De.baseFormatting)},[(Qn=(Ht=t==null?void 0:t.preferences)==null?void 0:Ht.tablePrefs)==null?void 0:Qn.baseFormatting]),He=(st,De)=>{var Kt;const mt=q[st],Ct=x1e({textWrap:mt==null?void 0:mt.textWrap,appearanceWrapText:N.isCellWrapping});return EX({formatting:Oe,compatibility:{columnSettings:mt,tablePreferences:(Kt=t==null?void 0:t.preferences)==null?void 0:Kt.tablePrefs,...Ct},columnId:st,tablePart:De})},qe=(st,De,mt)=>{try{const Ct=jm(t,{columnId:st}),Kt=Jl({card:t,columnKey:st,metricId:Ct==null?void 0:Ct.id}),Bt=Kt?fe(Kt):void 0,Xt=kg({card:t,columnId:st,resolvedSettings:mt,metricId:Ct==null?void 0:Ct.id,valueFormatPreferences:ue,boundCurrency:Bt});return Xt?In.formatNumericCanonical(De,Xt):mt!=null&&mt.numberFormat?In.formatNumberWithColumnSettings(De,mt.numberFormat,mt.numberFormat.locale||"en-US"):De.toLocaleString()}catch{return De.toLocaleString()}},Qe=x.allowVirtualization&&ee.length>75,ct=N.isCellWrapping,It=Qe&&(!ye||re||ct),yt=X_({count:Qe?ee.length:0,getScrollElement:()=>a.current,estimateSize:()=>N.dataRowHeight??42,overscan:ye?5:10,useScrollendEvent:ye&&ce,isScrollingResetDelay:ye?240:150}),kt=Qe?yt.getVirtualItems():[],Mt=Qe&&kt.length>0?kt[0].start:0,vt=Qe&&kt.length>0?yt.getTotalSize()-kt[kt.length-1].end:0,St=Math.max(L.length,1),ke=m.useInteractionStore(st=>st.interactionStates[t.id]);w.useEffect(()=>{const st=(ke==null?void 0:ke.appliedClickFilters)||[],De=R.getFilteredSelectedRowModel().rows.length;st.length===0&&De>0&&R.resetRowSelection()},[ke==null?void 0:ke.appliedClickFilters,R]);const Ee=w.useRef(""),Pe=R.getState().rowSelection;w.useEffect(()=>{if(!U||!r||!s)return;const st=JSON.stringify(Pe);if(st===Ee.current)return;Ee.current=st;const De=se.map(mt=>{var Se;const Ct=i9({resolvedCardConfig:pe,card:t,row:mt});if(!Ct)return null;const Bt=m.findAllMatchingV2Interactions($,{conditions:Ct.conditions,metrics:Ct.metrics}).find(c9)??V[0];if(!Bt)return null;const Xt=c3e(Ct.conditions,Bt.trigger);return{interactionMode:"clickFilter",sourceCardId:t.id,filterGroups:[{filters:Xt}],metric:(Se=Ct.metrics)==null?void 0:Se[0],applyToCardIds:Bt.applyToCardIds,excludeCardIds:Bt.excludeCardIds}}).filter(mt=>!!mt);m.useInteractionStore.getState().setInteractionState(t.id,{...ke??m.createInitialInteractionState(),appliedClickFilters:De})},[t,t.id,V,se,r,U,ke,$,pe,Pe,s]);const Fe=(st,De)=>{if(st.stopPropagation(),!de||!r||!s)return;const mt=i9({resolvedCardConfig:pe,card:t,row:De});mt&&ge({context:mt,gesture:"leftClick",modifierKeys:{shift:st.shiftKey,ctrl:st.ctrlKey,meta:st.metaKey},position:{x:st.clientX,y:st.clientY}})};return l.jsx(m.TooltipProvider,{children:l.jsxs("div",{onMouseDown:st=>st.stopPropagation(),className:m.cn("flex w-full flex-col",!h&&"gap-2"),children:[l.jsx(u3e,{scrollAreaRef:a,style:N.containerStyle,usePlainWrapper:x.usePlainWrapper,className:m.cn("data-table-scroll-container relative h-full rounded-none bg-muted/20",a3e(D),S&&"border-gray-300 print:border-gray-400"),children:l.jsxs("table",{className:m.cn("w-full text-sm [border-spacing:0]",S&&"print:break-inside-avoid",D&&i3e(D)),"data-table-type":"data","data-total-rows":oe,"data-total-columns":J,children:[l.jsx(Pm,{style:{...N.headerStyle,...M},className:m.cn("[&_tr]:border-b-0",!S&&"bg-muted",S&&"bg-gray-50 text-foreground print:table-header-group print:bg-gray-100"),children:R.getHeaderGroups().map(st=>l.jsx(Or,{children:st.headers.map((De,mt)=>{const Ct=mt===st.headers.length-1,Kt=y&&De.column.id!=="select",Bt=Ue===De.column.id,Xt=(Xe==null?void 0:Xe.colId)===De.column.id,Yn=De.column.columnDef.meta,Se=GLe({tableAppearance:N,style:{width:De.getSize(),minWidth:De.getSize(),maxWidth:Ct?void 0:De.getSize(),position:S?"relative":void 0,transition:"none",...He(De.column.id,"header"),...M},className:m.cn("h-auto border-b border-transparent px-4 py-2 align-middle font-medium uppercase tracking-[0.08em] text-muted-foreground",!S&&"relative bg-muted/95",x.allowStickyHeader&&N.isHeaderSticky&&"sticky top-0 z-10 supports-[backdrop-filter]:bg-muted/80 supports-[backdrop-filter]:backdrop-blur-sm",S&&"text-foreground/90 print:bg-gray-100",Bt&&"opacity-40")});return l.jsxs(hs,{colSpan:De.colSpan,"data-column-id":De.id,draggable:Kt,onMouseDownCapture:Ne=>{var tt,At;const Ve=Ne.target;c.current=!!((tt=Ve.closest)!=null&&tt.call(Ve,"[data-resize-handle]")),u.current=!!((At=Ve.closest)!=null&&At.call(Ve,"[data-grip-handle]"))},onDragStart:Ne=>{if(Kt){if(c.current||!u.current){Ne.preventDefault();return}Ne.dataTransfer.effectAllowed="move",Ne.dataTransfer.setData("text/column-id",De.column.id),je(De.column.id)}},onDragOver:Ne=>{if(!y||!Ue||Ue===De.column.id||De.column.id==="select")return;Ne.preventDefault();const Ve=Ne.currentTarget.getBoundingClientRect(),tt=Ve.left+Ve.width/2,At={colId:De.column.id,side:Ne.clientX<tt?"before":"after"};Ze($t=>($t==null?void 0:$t.colId)===At.colId&&$t.side===At.side?$t:At)},onDrop:Ne=>{y&&(Ne.preventDefault(),at())},onDragEnd:()=>{je(null),Ze(null)},style:Se.style,className:m.cn(Se.className,(Yn==null?void 0:Yn.isNumeric)&&"numeric"),children:[!S&&P&&l.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 bottom-0 h-px bg-border",style:N.headerDividerStyle}),De.isPlaceholder?null:l.jsxs(l.Fragment,{children:[Xt&&(Xe==null?void 0:Xe.side)==="before"&&l.jsx("div",{className:"pointer-events-none absolute -left-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),Xt&&(Xe==null?void 0:Xe.side)==="after"&&l.jsx("div",{className:"pointer-events-none absolute -right-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),l.jsx("span",{className:"block",children:pi(De.column.columnDef.header,De.getContext())}),v&&l.jsx(Kf,{header:De,isResizing:De.column.getIsResizing(),inset:Ct})]})]},De.id)})},st.id))}),l.jsx($d,{children:ee.length?l.jsxs(l.Fragment,{children:[Qe&&Mt>0&&l.jsx(Or,{"aria-hidden":!0,className:"pointer-events-none border-none hover:bg-transparent",children:l.jsx(Wn,{colSpan:St,style:{height:Mt,padding:0,border:"none"}})}),(Qe?kt:ee).map((st,De)=>{const mt=Qe?st.index:De,Ct=Qe?ee[st.index]:st;if(!Ct)return null;const Kt=Ct.getIsSelected();return l.jsx(Or,{ref:It?yt.measureElement:void 0,onClick:x.isInteractive?Bt=>Fe(Bt,Ct):void 0,"data-index":Qe?mt:De,"data-state":Kt?"selected":void 0,style:{...N.getDataRowStyle(mt,{isSelected:Kt,suppressZebra:I}),...I&&C.stripedRows&&mt%2===1&&!Kt?N.stripedDataRowStyle:null,...W(Ct)},className:m.cn("border-border/40",(ye||N.hasHoverRowStyle)&&"!transition-none",!ye&&!N.hasHoverRowStyle&&"transition-colors duration-150",N.dataRowClassName,Kt?"bg-primary/12 border-primary/50 hover:bg-primary/15":ne?"opacity-55 hover:opacity-70":"hover:bg-muted/40",S&&"border-gray-300 print:break-inside-avoid print:border-gray-400",x.isInteractive&&de&&"cursor-pointer"),children:Ct.getVisibleCells().map((Bt,Xt,Yn)=>{var Fn,Re,rt,pt;const Se=Xt===Yn.length-1,Ne=Eh({tableAppearance:N,style:{width:Bt.column.getSize(),minWidth:Bt.column.getSize(),maxWidth:Se?void 0:Bt.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90",S&&"border-gray-300 print:border-gray-400")}),Ve=Bt.column.columnDef.meta,tt=(Fn=Ve==null?void 0:Ve.getConditionalFormatting)==null?void 0:Fn.call(Ve,Ct.original,Ct.index),At=((Re=tt==null?void 0:tt.overlay)==null?void 0:Re.kind)==="dataBar"?tt.overlay:void 0,$t=At?Math.max(0,Math.min(1,At.ratio)):0,Dn=((rt=tt==null?void 0:tt.cellStyle)==null?void 0:rt.color)??((pt=tt==null?void 0:tt.rowStyle)==null?void 0:pt.color);return l.jsxs(Wn,{"data-column-id":Bt.column.id,style:{...Ne.style,...At?{position:"relative",overflow:"hidden"}:null,...tt==null?void 0:tt.rowStyle,...tt==null?void 0:tt.cellStyle,...Dn?{"--document-table-cell-color":Dn}:null,...At?{textAlign:"left"}:null},className:m.cn(Ne.className,(Ve==null?void 0:Ve.isNumeric)&&"numeric"),children:[At?l.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-1 left-4 right-4 overflow-hidden rounded-[2px]",children:l.jsx("div",{"aria-hidden":"true",className:"h-full rounded-[2px]",style:{width:`${$t*100}%`,backgroundColor:At.color,opacity:.4}})}):null,(At==null?void 0:At.showValue)!==!1?l.jsx("div",{className:m.cn(Dh(N,"leading-5",{textFlow:"delegate"}),At&&"relative z-[1]"),children:pi(Bt.column.columnDef.cell,Bt.getContext())}):null]},Bt.id)})},Ct.id)}),Qe&&vt>0&&l.jsx(Or,{"aria-hidden":!0,className:"pointer-events-none border-none hover:bg-transparent",children:l.jsx(Wn,{colSpan:St,style:{height:vt,padding:0,border:"none"}})})]}):l.jsx(Or,{className:"border-b-0 hover:bg-transparent",children:l.jsx(Wn,{colSpan:L.length,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:n?null:"No results."})})}),lt&&ee.length>0&&l.jsx("tfoot",{"data-row-type":"grand-total",style:{...N.grandTotalRowStyle,...A},children:l.jsx("tr",{style:{...N.grandTotalRowStyle,...A},children:Le.map((st,De,mt)=>{const Ct=q==null?void 0:q[st.id],Kt=Be[st.id],Bt=st.id===Te,Xt=typeof Kt=="number"||(Ct==null?void 0:Ct.type)==="number"?ow(Kt):null,Yn=(Ct==null?void 0:Ct.type)==="number"||Xt!==null,Se=(Ct==null?void 0:Ct.textAlign)??(Yn?"right":"left"),Ne=De===mt.length-1;let Ve="";Kt!=null?Xt!==null?Ve=qe(st.id,Xt,Ct):Ve=String(Kt):Bt&&(Ve="Total");const tt=Vc({tableAppearance:N,style:{width:st.getSize(),minWidth:st.getSize(),maxWidth:Ne?void 0:st.getSize(),textAlign:Se,position:nt?"sticky":void 0,bottom:nt?0:void 0,zIndex:nt?20:void 0,...He(st.id,"grandTotal"),...A},className:m.cn(C.totalsStyle.borderTop?"border-t border-border/60":"border-t-0","bg-muted/95 px-4 font-medium text-foreground/90",Yn&&"numeric tabular-nums",S&&"border-gray-300 print:border-gray-400")}),At=!S&&typeof Kt=="string"&&Ve.trim().length>0;return l.jsx("td",{"data-column-id":st.id,style:tt.style,className:tt.className,children:At?l.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l.jsx("span",{children:Ve}),l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":"About totals",className:"inline-flex cursor-help text-muted-foreground/80",children:l.jsx(m.Info,{className:"h-3.5 w-3.5"})})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-[240px]",children:"Totals are calculated across the full filtered dataset, not just the rows currently visible."})]})]}):Ve},st.id)})})})]})}),(()=>{if(Object.entries(q).some(([De,mt])=>mt.type!=="date"||!mt.dateFormat?!1:(mt.dateFormat.timezone==="auto"||!mt.dateFormat.timezone?ie||le:mt.dateFormat.timezone)!==le)){const De=new Set;Object.entries(q).forEach(([Ct,Kt])=>{if(Kt.type==="date"&&Kt.dateFormat){const Bt=Kt.dateFormat.timezone==="auto"||!Kt.dateFormat.timezone?ie||le:Kt.dateFormat.timezone;Bt&&Bt!==le&&De.add(Bt)}});const mt=Array.from(De).map(Ct=>`${yN(Ct)} (${ur.getTimezoneAbbreviation(Ct)})`).join(", ");return l.jsx("div",{className:"flex items-center justify-center px-4 py-2 text-xs text-muted-foreground",children:l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(UM,{className:"h-3 w-3"}),"Date/time values displayed in: ",mt]})})}return null})(),x.allowPagination&&b("showPagination")&&(Q==="server"||R.getFilteredRowModel().rows.length>10)&&l.jsx(U_,{totalColumns:J,pageCount:Q==="server"&&ae?ae.pageCount:R.getPageCount(),pageIndex:R.getState().pagination.pageIndex,pageSize:R.getState().pagination.pageSize,rowCount:Q==="server"&&ae?ae.totalCount:R.getFilteredRowModel().rows.length,selectedRowCount:R.getFilteredSelectedRowModel().rows.length,setPageIndex:R.setPageIndex,setPageSize:R.setPageSize,canPreviousPage:Q==="server"&&ae?ae.hasPrevPage:R.getCanPreviousPage(),canNextPage:Q==="server"&&ae?ae.hasNextPage:R.getCanNextPage(),previousPage:R.previousPage,nextPage:R.nextPage,onPageSizePreferenceChange:x.showEditorControls?p:void 0,onClearSelection:()=>{R.resetRowSelection(),((ke==null?void 0:ke.appliedClickFilters)||[]).filter(mt=>mt.sourceCardId===t.id).forEach(mt=>{m.useInteractionStore.getState().toggleClickFilter(t.id,mt)})},paginationMode:Q,showExport:!1,card:t,frameId:r,exportData:e.data,appearance:N.pagination}),b("showColumnSettings")&&l.jsx(QL,{column:F?R.getColumn(F)??null:null,settings:Z,onSettingsChange:Y,baseStyle:K,onBaseStyleChange:X,onReset:z,onResetAll:B,open:H,onOpenChange:G,availableColumns:R.getAllColumns().filter(st=>st.id!=="select").map(st=>st.id),isSqlCard:!!(t!=null&&t.sql)})]})})}const uC=e=>e==null?void 0:e.toString().trim(),dC=e=>e==null?void 0:e.toLowerCase().replace(/\s+/g,""),f3e=e=>{if(e)return e.label||e.qualifiedFieldName||e.name},h3e=(e,t,n,r)=>{const s=uC(e),o=dC(e),i=a=>[uC(a.label),uC(a.qualifiedFieldName),uC(a.name),dC(a.label),dC(a.qualifiedFieldName),dC(a.name)].filter(Boolean).some(u=>u===s||u===o);return(t==null?void 0:t.find(i))||(n==null?void 0:n.find(i))||(r==null?void 0:r.find(i))};function vre(e){return e!=null&&e.length?e.map(t=>{const n=f3e(t);return n?{id:n,desc:t.direction==="desc"}:null}).filter(t=>t!==null):[]}function wre(e,t,n,r){return e!=null&&e.length?e.map(({id:s,desc:o})=>{if(!s)return null;const i=h3e(s,t,n,r);return i?{...i,id:wte("sortBy",i),role:"sortby",direction:o?"desc":"asc"}:null}).filter(s=>s!==null):[]}function m3e({data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,card:s,comparisonMetadata:o,onSortChange:i,sortState:a,paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,columnSizing:p,onColumnSizingChange:g,onColumnResizeStateChange:b,showColumnResizeHandles:x,frameId:y,sheetId:v,onMultipleInteractions:S}){var z,B,H,L,G,J,oe,Q,ae,ie,le,ue;const N=m.useDashboardStore(fe=>fe.isVisualEditing),C=((B=(z=s==null?void 0:s.preferences)==null?void 0:z.tablePrefs)==null?void 0:B.columnSettingsMap)??m.EMPTY_COLUMN_SETTINGS,j=w.useMemo(()=>ec(C),[C]),_=(L=(H=s==null?void 0:s.preferences)==null?void 0:H.tablePrefs)==null?void 0:L.columnVisibility,k=p??((J=(G=s==null?void 0:s.preferences)==null?void 0:G.tablePrefs)==null?void 0:J.columnSizing),I=(Q=(oe=s==null?void 0:s.preferences)==null?void 0:oe.tablePrefs)==null?void 0:Q.selectColumnVisible,T=((ae=s==null?void 0:s.paginationConfig)==null?void 0:ae.pageSize)||((le=(ie=s==null?void 0:s.preferences)==null?void 0:ie.tablePrefs)==null?void 0:le.pageSize),{updateColumnSettingsMap:E,updateTableBaseFormatting:D,updateColumnVisibility:M,updateColumnSizing:A,setCard:P,updateCardInFrame:O,showAllColumns:$,hideAllColumns:V,toggleSelectColumn:U}=m.useEditorStore(fe=>fe.actions),R=w.useMemo(()=>{var fe;return vre((fe=s.config)==null?void 0:fe.sortByColumns)},[(ue=s.config)==null?void 0:ue.sortByColumns]),q=a??R,W=fe=>{if(!Yh(s))return!0;const pe=Lje(s,fe);if(!pe)return!1;const ge={...s,config:pe};return P(ge),O(ge),!0},F=w.useCallback(fe=>{const pe=typeof fe=="function"?fe(k||{}):fe;if(g){g(pe);return}A(pe)},[k,g,A]),Z=w.useCallback((fe,pe,ge)=>{E(p5({persisted:C,columnId:fe,baseline:ge,next:pe}))},[C,E]),K=w.useCallback(fe=>{E(BX(C,fe))},[C,E]),Y={card:s,data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,comparisonMetadata:o,pageSize:T,columnSettings:j,onColumnSettingsChange:Z,onResetColumnSettings:K,onResetAllColumnSettings:()=>E({}),onBaseFormattingChange:D,columnVisibility:_,onColumnVisibilityChange:M,columnSizing:k,onColumnSizingChange:F,onColumnResizeStateChange:b,showColumnResizeHandles:x,onShowAllColumns:$,onHideAllColumns:V,defaultSelectColumnVisible:I,onSelectColumnVisibleChange:U,exportFileName:"export",paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,sortState:q,onSortChange:i,onColumnReorder:W,frameId:y,sheetId:v,onMultipleInteractions:S},X={card:s,data:e,totalsData:t,formattingFullRows:n,totalsByColumnId:r,comparisonMetadata:o,pageSize:T,columnSettings:j,columnSizing:k,onColumnSizingChange:g?F:void 0,onColumnResizeStateChange:b,showColumnResizeHandles:x,columnVisibility:_||m.EMPTY_COLUMN_VISIBILITY,defaultSelectColumnVisible:I,exportFileName:"export",paginationMetadata:c,onPaginationChange:u,isLoading:d,suppressSortControls:f,suppressCellHoverCards:h,sortState:q,onSortChange:i,frameId:y,sheetId:v,onMultipleInteractions:S};return l.jsx(d3e,{...N?Y:X})}function p3e(e,t){return e.card===t.card&&e.data===t.data&&e.totalsData===t.totalsData&&e.formattingFullRows===t.formattingFullRows&&e.totalsByColumnId===t.totalsByColumnId&&e.comparisonMetadata===t.comparisonMetadata&&e.paginationMetadata===t.paginationMetadata&&e.onPaginationChange===t.onPaginationChange&&e.isLoading===t.isLoading&&e.sortState===t.sortState&&e.onSortChange===t.onSortChange&&e.columnSizing===t.columnSizing&&e.onColumnSizingChange===t.onColumnSizingChange&&e.onColumnResizeStateChange===t.onColumnResizeStateChange&&e.showColumnResizeHandles===t.showColumnResizeHandles&&e.suppressSortControls===t.suppressSortControls&&e.suppressCellHoverCards===t.suppressCellHoverCards&&e.frameId===t.frameId&&e.sheetId===t.sheetId&&e.onMultipleInteractions===t.onMultipleInteractions}const Bd=w.memo(m3e,p3e),u9=36,lD=280,g3e=16,b3e=12,x3e=[],y3e=[],$R={left:0,width:lD,minWidth:lD,maxWidth:lD},i3=150,Sre=240;function v3e(e,t){return e===t-1?Sre:i3}function zR(e,t){const n=v3e(e,t);return{left:e*i3,width:n,minWidth:n,maxWidth:n}}function w3e(e){return Math.max(e-1,0)*i3+Sre}function J_({card:e,result:t,grid:n,payload:r,isLoading:s,expansionState:o,onExpansionChange:i,loadingRowPathKeys:a,onSortChange:c,onLoadMoreRows:u}){const d=Q_("pivotTable"),{preferences:f,resolveBoundCurrency:h}=ka(e),p=w.useMemo(()=>iX({card:e,result:t,presentation:{preferences:f,resolveBoundCurrency:h}}),[e,f,h,t]),g=w.useMemo(()=>n||(t?$te(t):void 0),[n,t]),[b,x]=w.useState(()=>g?qu(g):null);w.useEffect(()=>{x(g?qu(g):null)},[g]);const y=o||b||void 0,v=w.useMemo(()=>!g&&!t?null:Lte({grid:g,result:t,payload:r,expansionState:y}),[y,g,t,r]),S=v==null?void 0:v.rows,N=v==null?void 0:v.headerRows,C=w.useMemo(()=>_3e(t),[t]),j=w.useMemo(()=>I3e(S??x3e),[S]),_=w.useMemo(()=>S3e(N??y3e),[N]),k=w.useMemo(()=>C3e({result:t,grid:g}),[g,t]);if(s)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"Loading matrix"});if(!v)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"Matrix payload unavailable"});if(!v.rows.length)return l.jsx("div",{className:"flex h-full min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:"No matrix rows to display"});const I=v.headerRows.length,T=v.rowHeaderLevels,E=T.map(oe=>oe.label).join(" · ")||"Rows",D=v.allRows.some(oe=>oe.canExpand),M=!D&&T.length>1,A=M?T.length:1,P=v.allRows.filter(oe=>oe.canExpand),O=P.length>0&&P.every(oe=>oe.isExpanded),$=v.columns.length-1,V=v.columns.reduce((oe,Q)=>Math.max(oe,Q.columnPath.length),0),U=v.columns.map((oe,Q)=>j3e(oe,v.columns[Q-1])),R=(C==null?void 0:C.rowLevels.filter(oe=>j.has(oe.publicId)))??[],q=R.at(-1),W=_.length>0,F=I+(W?1:0),Z=W?u9:0,K=y||(g?qu(g):void 0),Y=_.length>0&&K!==void 0&&_.every(oe=>M_(K,oe)),X=oe=>{if(!g)return;const Q=y||qu(g),ae=fFe({state:Q,rowPath:oe.rowPath});o||x(ae.state),i==null||i(ae)},z=oe=>{const Q=Nre(oe);Q&&(u==null||u(Q))},B=oe=>{if(!g)return;const Q=y||qu(g),ae=hFe({state:Q,columnPath:oe});o||x(ae.state),i==null||i(ae)},H=()=>{if(!g)return;const oe=y||qu(g),Q={schemaVersion:1,expandedRowPaths:O?[]:P.map(ae=>ae.rowPath),expandedColumnPaths:oe.expandedColumnPaths};x(Q),i==null||i({state:Q,kind:"bulkRows",isExpanded:!O})},L=()=>{if(!g)return;const Q={schemaVersion:1,expandedRowPaths:(y||qu(g)).expandedRowPaths,expandedColumnPaths:Y?[]:_};o||x(Q),i==null||i({state:Q,kind:"bulkColumns",isExpanded:!Y})},G=(oe,Q,ae)=>{if(!C)return;const ie={axis:"row",targetId:oe.publicId,direction:Q,by:ae==="value"?{kind:"value",valueId:C.measurePublicId}:{kind:"label"},nulls:"last",scope:"withinParent"};c==null||c([ie])},J=(oe,Q)=>{if(!C||!oe.measureInstanceId||!q)return;const ae={axis:"row",targetId:q.publicId,direction:Q,by:{kind:"value",valueId:R0(oe.measureInstanceId,"measure"),columnPath:T3e(oe.columnPath,"column")},nulls:"last",scope:"withinParent"};c==null||c([ae])};return l.jsxs(il,{className:"data-table-scroll-container h-full min-h-0 w-full rounded-none border border-border/60 bg-background",viewportClassName:"overscroll-none",scrollBarClassName:"z-40",children:[l.jsxs(Kne,{containerClassName:"overflow-visible",className:"min-w-max border-separate border-spacing-0",style:d.containerStyle,"data-matrix-table":"true","aria-label":"Matrix table",role:"treegrid","aria-rowcount":v.allRows.length+F,"aria-colcount":A+v.columns.length,children:[l.jsxs(Pm,{children:[W?l.jsxs(Or,{className:"hover:bg-transparent",children:[M?T.map((oe,Q)=>l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:oe.label,style:{...zR(Q,A),top:0},className:m.cn("sticky top-0 z-30 overflow-hidden text-ellipsis whitespace-nowrap border-b border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",Q===A-1&&"border-r",d.headerTextClassName),children:oe.label},oe.id)):l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:E,style:{...$R,top:0},className:m.cn("group/row-header sticky left-0 top-0 z-30 overflow-hidden whitespace-nowrap border-b border-r border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[D&&P.length>0?l.jsx("button",{type:"button",onClick:H,"aria-label":O?"Collapse all rows":"Expand all rows","aria-expanded":O,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})}):null,l.jsx("span",{className:"truncate",children:E}),c&&C&&R.length?l.jsx(d9,{rowLevels:R,measureLabel:C.measureLabel,onSort:G}):null]})}),l.jsx(hs,{colSpan:v.columns.length,scope:"colgroup",style:{...d.headerCellStyle,top:0},className:m.cn("sticky top-0 z-20 h-9 whitespace-nowrap border-b border-l border-border/70 bg-muted text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:L,"aria-label":Y?"Collapse all columns":"Expand all columns","aria-expanded":Y,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",Y&&"rotate-90"),"aria-hidden":"true"})}),l.jsx("span",{className:"flex min-w-0 items-center gap-1.5 truncate font-medium leading-5 text-muted-foreground",children:k.map((oe,Q)=>l.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[Q>0?l.jsx(Ot.ChevronRight,{className:"size-3.5 shrink-0 text-muted-foreground/70","aria-hidden":"true"}):null,l.jsx("span",{className:"truncate",children:oe})]},`${oe}:${Q}`))})]})})]}):null,v.headerRows.map((oe,Q)=>l.jsxs(Or,{className:"hover:bg-transparent",children:[!W&&Q===0&&(M?T.map((ae,ie)=>l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:ae.label,style:{...zR(ie,A),top:0},className:m.cn("sticky top-0 z-30 overflow-hidden text-ellipsis whitespace-nowrap border-b border-border/60 bg-muted px-3 text-left align-bottom text-[13px] font-medium normal-case",ie===A-1&&"border-r",d.headerTextClassName),children:ae.label},ae.id)):l.jsx(hs,{rowSpan:Math.max(F,1),scope:"col",title:E,style:{...$R,top:0},className:m.cn("group/row-header sticky left-0 top-0 z-30 overflow-hidden whitespace-nowrap border-b border-r border-border/60 bg-muted px-3 text-left align-middle text-[13px] font-medium normal-case",d.headerTextClassName),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[D&&P.length>0?l.jsx("button",{type:"button",onClick:H,"aria-label":O?"Collapse all rows":"Expand all rows","aria-expanded":O,className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})}):null,l.jsx("span",{className:"truncate",children:E}),c&&C&&R.length?l.jsx(d9,{rowLevels:R,measureLabel:C.measureLabel,onSort:G}):null]})})),oe.cells.map((ae,ie)=>l.jsx(E3e,{cell:ae,top:Z+Q*u9,stickyRight:ie===oe.cells.length-1&&ae.role==="grandTotal",tableAppearance:d,onToggle:B,rowSortTargetLabel:q==null?void 0:q.label,maxColumnPathDepth:V,onValueSort:c?J:void 0},ae.id))]},oe.id))]}),l.jsx($d,{children:v.rows.map((oe,Q)=>l.jsxs(Or,{className:"hover:bg-muted/30",style:oe.isGrandTotal?d.grandTotalRowStyle:oe.isSubtotal?d.subtotalRowStyle:void 0,role:"row","aria-level":oe.ariaLevel,"aria-expanded":oe.canExpand?oe.isExpanded:void 0,children:[M?l.jsx(P3e,{row:oe,previousRow:v.rows[Q-1],rowHeaderCount:A}):l.jsx(A3e,{row:oe,isStickyBottom:oe.isGrandTotal,loadingRowPathKeys:a,onToggle:X,onLoadMore:z}),oe.cells.map((ae,ie)=>{var le;return l.jsx(O3e,{cell:ae,displayValue:aX({cell:{measureId:ae.measureInstanceId,value:ae.rawValue,presence:ae.presence},formatsByMeasureId:p}),divider:U[ie],isGrandTotalRow:oe.isGrandTotal,isStickyBottom:oe.isGrandTotal,isStickyRight:ie===$&&!!((le=v.columns[ie])!=null&&le.isGrandTotal),tableAppearance:d},ae.id)})]},oe.id))})]}),l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-40"})]})}function S3e(e){const t=new Map;for(const n of e)for(const r of n.cells)!r.isExpandable||!r.expansionPath||t.set(as(r.expansionPath),r.expansionPath);return Array.from(t.values())}function C3e(e){var n,r;const t=((n=e.result)==null?void 0:n.axes.columns.levels.map(s=>s.label).filter(Boolean))??[];if(!t.length){const s=new Map;for(const o of((r=e.grid)==null?void 0:r.columns)??[])for(const i of o.columnPath)s.has(i.instanceId)||s.set(i.instanceId,N3e(i.instanceId));t.push(...s.values())}return t.length?t:["Columns"]}function N3e(e){return e.replace(/^(row|column|measure):/,"").replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().split(/\s+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function j3e(e,t){if(e.isGrandTotal)return"grandTotal";if(e.isSubtotal)return"subtotal";if(!t)return"none";const n=ej(e.columnPath[0]),r=ej(t.columnPath[0]);return n!==r?"group":"none"}function k3e(e){switch(e){case"grandTotal":return"border-l-2 border-l-border";case"subtotal":return"border-l border-l-border/60";case"group":return"border-l border-l-border/40";default:return""}}function _3e(e){var r;const t=(e==null?void 0:e.axes.rows.levels.map(s=>({publicId:R0(s.instanceId,"row"),label:s.label})))??[],n=Object.values((e==null?void 0:e.measuresById)??{})[0];return!t.length||!n?null:{rowLevels:t,deepestRowLevelLabel:((r=t.at(-1))==null?void 0:r.label)??"Rows",measurePublicId:R0(n.instanceId,"measure"),measureLabel:n.label}}function I3e(e){const t=new Set;for(const n of e){const r=n.rowPath.at(-1);r&&t.add(R0(r.instanceId,"row"))}return t}function R0(e,t){const n=`${t}:`;return e.startsWith(n)?e.slice(n.length):e}function T3e(e,t){return e.map(n=>({levelId:R0(n.instanceId,t),value:n.value}))}function d9({rowLevels:e,measureLabel:t,onSort:n}){const[r,s]=w.useState(!1),o=(i,a,c)=>{n(i,a,c),s(!1),Cre()};return l.jsxs(Ys,{open:r,onOpenChange:s,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Sort row levels",title:"Sort row levels",className:"pointer-events-none ml-auto inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-opacity hover:bg-muted-foreground/10 hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/row-header:pointer-events-auto group-hover/row-header:opacity-100",children:l.jsx(Si,{className:"size-3.5","aria-hidden":"true"})})}),l.jsxs(Es,{align:"end",className:"w-64 p-1",children:[l.jsx($a,{children:"Sort row levels"}),e.map((i,a)=>l.jsxs("div",{children:[a>0?l.jsx(Sa,{}):null,l.jsx(BR,{label:i.label,onAscending:()=>o(i,"asc","label"),onDescending:()=>o(i,"desc","label"),ascendingLabel:`Sort ${i.label} A to Z`,descendingLabel:`Sort ${i.label} Z to A`}),l.jsx(BR,{label:t,onAscending:()=>o(i,"asc","value"),onDescending:()=>o(i,"desc","value"),ascendingLabel:`Sort ${i.label} by ${t} ascending`,descendingLabel:`Sort ${i.label} by ${t} descending`})]},i.publicId))]})]})}function BR({label:e,onAscending:t,onDescending:n,ascendingLabel:r,descendingLabel:s}){return l.jsxs("div",{className:"flex h-7 items-center justify-between gap-2 rounded-sm px-2",children:[l.jsx("span",{className:"min-w-0 truncate text-[13px] text-foreground",children:e}),l.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5",children:[l.jsx("button",{type:"button","aria-label":r,className:"inline-flex size-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:t,children:l.jsx(No,{className:"size-3.5","aria-hidden":"true"})}),l.jsx("button",{type:"button","aria-label":s,className:"inline-flex size-6 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:n,children:l.jsx(ro,{className:"size-3.5","aria-hidden":"true"})})]})]})}function E3e({cell:e,top:t,stickyRight:n,tableAppearance:r,onToggle:s,onValueSort:o,rowSortTargetLabel:i,maxColumnPathDepth:a}){const c=!!o&&e.colSpan===1&&!!e.measureInstanceId&&e.columnPath.length>0&&e.columnPath.length===a&&e.role!=="grandTotal"&&e.role!=="subtotal";return l.jsx(hs,{colSpan:e.colSpan,rowSpan:e.rowSpan,scope:"colgroup",style:{...r.headerCellStyle,top:t,...n?{right:0}:{}},className:m.cn("group/matrix-col-header sticky z-20 h-9 whitespace-nowrap border-b border-l border-border/40 bg-muted",e.isExpandable?"text-left":"text-right",e.role==="grandTotal"&&"border-l-2 border-l-border font-semibold",e.role==="subtotal"&&"border-l-border/60 font-semibold",n&&"z-30","text-[13px] font-medium normal-case",r.headerTextClassName),children:e.isExpandable&&e.expansionPath?l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-expanded":e.isExpanded,"aria-label":`${e.isExpanded?"Collapse":"Expand"} ${e.label}`,"data-spr-expand-id":`matrix-column:${e.id}`,onClick:()=>s(e.expansionPath),children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",e.isExpanded&&"rotate-90"),"aria-hidden":"true"})}),l.jsx("span",{children:e.label}),c&&i?l.jsx(f9,{columnLabel:e.label,rowSortTargetLabel:i,onSort:u=>o==null?void 0:o(e,u)}):null]}):l.jsxs("span",{className:"relative inline-flex w-full items-center justify-end overflow-hidden",children:[l.jsx("span",{className:m.cn("min-w-0 truncate text-right transition-transform duration-150 ease-out",c&&i&&"group-hover/matrix-col-header:-translate-x-6"),children:e.label}),c&&i?l.jsx(f9,{columnLabel:e.label,rowSortTargetLabel:i,onSort:u=>o==null?void 0:o(e,u)}):null]})})}function f9({columnLabel:e,rowSortTargetLabel:t,onSort:n}){const[r,s]=w.useState(!1),o=i=>{n(i),s(!1),Cre()};return l.jsxs(Ys,{open:r,onOpenChange:s,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Sort ${e} value column`,title:`Sort ${e}`,className:"pointer-events-none absolute right-0 top-1/2 inline-flex size-5 -translate-y-1/2 translate-x-1 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-all duration-150 ease-out hover:bg-muted-foreground/10 hover:text-foreground focus-visible:pointer-events-auto focus-visible:translate-x-0 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/matrix-col-header:pointer-events-auto group-hover/matrix-col-header:translate-x-0 group-hover/matrix-col-header:opacity-100",children:l.jsx(Si,{className:"size-3.5","aria-hidden":"true"})})}),l.jsxs(Es,{align:"end",className:"w-60 p-1",children:[l.jsx($a,{children:e}),l.jsx(BR,{label:t,onAscending:()=>o("asc"),onDescending:()=>o("desc"),ascendingLabel:`Sort ${t} by ${e} ascending`,descendingLabel:`Sort ${t} by ${e} descending`})]})]})}function Cre(){const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function D3e(e){if(e.rowPath.length===0)return{label:e.label,indent:0};const t=VR(e.rowPath[e.rowPath.length-1]);return e.hasParentRow?{label:t,indent:Math.max(e.depth,0)}:e.depth===0?{label:t,indent:0}:{label:e.rowPath.map(VR).join(" · "),indent:0}}function VR(e){return(e==null?void 0:e.label)??jre(e)}function M3e(e){var t;return((t=e.rowPath.at(-1))==null?void 0:t.instanceId)==="__matrix_remaining__"}function Nre(e){return!M3e(e)||e.rowPath.length<2?null:e.rowPath.slice(0,-1)}function A3e({row:e,isStickyBottom:t,loadingRowPathKeys:n,onToggle:r,onLoadMore:s}){const{label:o,indent:i}=D3e(e),a=b3e+i*g3e,c=n==null?void 0:n.has(h9(e.rowPath)),u=Nre(e),d=u?n==null?void 0:n.has(h9(u)):!1,f=R3e(e),h=e.visibleChildCount<e.childCount?`Showing ${e.visibleChildCount} of ${e.childCount} child rows`:`${e.childCount} child rows`;return l.jsx(Wn,{scope:"row",title:o,style:{...$R,paddingLeft:a},className:m.cn("sticky left-0 z-10 overflow-hidden whitespace-nowrap border-b border-r border-border/60 py-1.5 pr-3 text-left text-[13px]",t&&"bottom-0 z-20",!e.isSubtotal&&!e.isGrandTotal&&"bg-background",e.isSubtotal&&"bg-muted font-medium",e.isGrandTotal&&"bg-muted font-semibold",e.isGrandTotal&&"border-t-2 border-t-border"),children:l.jsxs("span",{className:"flex items-center gap-1.5",children:[e.canExpand?l.jsx("button",{type:"button",className:"inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`${e.isExpanded?"Collapse":"Expand"} ${o}`,"aria-expanded":e.isExpanded,"data-spr-expand-id":`matrix-row:${e.rowNodeId}`,onClick:()=>r(e),onKeyDown:p=>{(p.key==="ArrowRight"&&!e.isExpanded||p.key==="ArrowLeft"&&e.isExpanded)&&(p.preventDefault(),r(e))},children:l.jsx(Ot.ChevronRight,{className:m.cn("size-3.5 transition-transform",e.isExpanded&&"rotate-90"),"aria-hidden":"true"})}):l.jsx("span",{className:"inline-block size-4 shrink-0","aria-hidden":"true"}),l.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate",children:o}),e.canExpand&&f?l.jsx("span",{className:"shrink-0 text-[10px] font-normal tabular-nums text-muted-foreground",title:h,children:f}):null]}),c?l.jsx(m.LoaderCircle,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground","aria-label":"Loading row children"}):null,u&&s?l.jsx("button",{type:"button",className:"ml-auto inline-flex shrink-0 items-center gap-1 rounded-sm px-1.5 py-0.5 text-xs font-medium text-muted-foreground hover:bg-muted-foreground/10 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-70","aria-label":`Show hidden rows for ${o}`,disabled:d,onClick:()=>s(e),children:d?l.jsx(m.LoaderCircle,{className:"size-3.5 animate-spin","aria-label":"Loading hidden rows"}):"Show"}):null]})})}function R3e(e){return!e.canExpand||e.childCount<=0?null:e.visibleChildCount>0&&e.visibleChildCount<e.childCount?`${e.visibleChildCount}/${e.childCount}`:String(e.childCount)}function P3e({row:e,previousRow:t,rowHeaderCount:n}){const r=m.cn(!e.isSubtotal&&!e.isGrandTotal&&"bg-background",e.isSubtotal&&"bg-muted font-medium",e.isGrandTotal&&"bg-muted font-semibold");if(e.rowPath.length<n){const o=w3e(n);return l.jsx(Wn,{scope:"row",colSpan:n,style:{left:0,width:o,minWidth:o,maxWidth:o},className:m.cn("sticky left-0 z-10 overflow-hidden whitespace-nowrap border-b border-r border-border/60 px-3 py-1.5 text-left text-[13px]",e.isGrandTotal&&"bottom-0 z-20 border-t-2 border-t-border",r),children:e.label})}const s=F3e(e,t);return l.jsx(l.Fragment,{children:Array.from({length:n},(o,i)=>{const a=e.rowPath[i],c=i>=s,u=VR(a);return l.jsx(Wn,{scope:i===0?"row":void 0,title:c?u:void 0,style:zR(i,n),className:m.cn("sticky z-10 overflow-hidden whitespace-nowrap border-b border-border/60 py-1.5 pr-3 text-left text-[13px]",i===0?"pl-3":"pl-2",i===n-1&&"border-r",r),children:l.jsx("span",{className:"truncate",children:c?u:""})},`${e.id}:rh:${i}`)})})}function F3e(e,t){if(!t)return 0;const n=Math.max(e.rowPath.length,t.rowPath.length);for(let r=0;r<n;r+=1)if(ej(e.rowPath[r])!==ej(t.rowPath[r]))return r;return e.rowPath.length}function O3e({cell:e,displayValue:t,divider:n,isGrandTotalRow:r,isStickyRight:s,isStickyBottom:o,tableAppearance:i}){const a=m.cn("whitespace-nowrap border-b border-border/60 text-right tabular-nums",k3e(n),r&&"border-t-2 border-t-border",e.role==="rowSubtotal"&&"bg-muted/50 font-medium",e.role==="columnSubtotal"&&"bg-muted/50 font-medium",e.role==="subtotalIntersection"&&"bg-muted/70 font-medium",e.role==="rowGrandTotal"&&"bg-muted font-semibold",e.role==="columnGrandTotal"&&"bg-muted font-semibold",e.role==="matrixGrandTotal"&&"bg-muted font-semibold",e.isSparse&&"text-muted-foreground/55",s&&"sticky right-0 bg-muted",o&&"sticky bottom-0 bg-muted",s&&o?"z-20":s||o?"z-10":""),c=e.isGrandTotal?Vc({tableAppearance:i,className:a}):e.isSubtotal?hd({tableAppearance:i,className:a,divider:"row"}):Eh({tableAppearance:i,className:a,divider:"row"});return l.jsx(Wn,{...c,children:t})}function ej(e){if(e)return`${e.instanceId}:${jre(e)}`}function jre(e){const t=e==null?void 0:e.value;return t==null?"":t instanceof Date?t.toISOString():String(t)}function h9(e){return JSON.stringify(e.map(t=>({instanceId:t.instanceId,fieldKey:t.fieldKey,value:t.value instanceof Date?t.value.toISOString():t.value})))}function Vd({size:e="md",color:t="muted",className:n=""}){const r={xs:"w-0.5 h-0.5",sm:"w-1 h-1",md:"w-1.5 h-1.5",lg:"w-3 h-3"},s={muted:"bg-muted-foreground/70",primary:"bg-primary",secondary:"bg-secondary-foreground",accent:"bg-accent-foreground",destructive:"bg-destructive",gray:"bg-gray-400 dark:bg-gray-500",blue:"bg-blue-500 dark:bg-blue-400",green:"bg-green-500 dark:bg-green-400",red:"bg-red-500 dark:bg-red-400"},o=m.cn(r[e],s[t],"rounded-full animate-pulse");return l.jsxs("div",{className:m.cn("flex items-center gap-1",n),children:[l.jsx("div",{className:o,style:{animationDelay:"0ms",animationDuration:"1.4s"}}),l.jsx("div",{className:o,style:{animationDelay:"200ms",animationDuration:"1.4s"}}),l.jsx("div",{className:o,style:{animationDelay:"400ms",animationDuration:"1.4s"}})]})}function L3e(e,t){var C,j;const n=m.useDashboardStore(_=>_.isVisualEditing),{updateCurrentDashboardCard:r}=m.useDashboardActions(),s=m.useEditorStore(_=>{var k;return(k=_.actions)==null?void 0:k.updateColumnSettingsMap}),o=((j=(C=e==null?void 0:e.preferences)==null?void 0:C.tablePrefs)==null?void 0:j.columnSettingsMap)??m.EMPTY_COLUMN_SETTINGS,i=w.useMemo(()=>ec(o),[o]),[a,c]=w.useState(!1),[u,d]=w.useState(null),[f,h]=w.useState(ks()),[p,g]=w.useState(!1),b=w.useRef(ks()),x=w.useCallback(_=>{var M,A;d(_);let k=i[_];k||(k=t&&t.length>0?A0(_,t):ks());const I=t&&t.length>0?Object.keys(t[0]||{}):[],T=((A=(M=e.config)==null?void 0:M.groupByColumns)==null?void 0:A.length)||0,D=I.indexOf(_)-T;k=D>=0?Zh({card:e,columnId:_,metricIndex:D,groupByColumnCount:T,columnSettingsMap:i,preserveOmittedProperties:!0}):Vi({card:e,columnId:_,resolvedSettings:k,preserveOmittedProperties:!0})||k,b.current=k,h(k),g(!1),c(!0)},[e,i,t]),y=w.useCallback(()=>{var _;if(u&&f){const k=p5({persisted:o,columnId:u,baseline:b.current,next:f,reset:p});if(n&&s)s(k);else if(r){const I={...e,preferences:{...e.preferences,tablePrefs:{...(_=e.preferences)==null?void 0:_.tablePrefs,columnSettingsMap:k}}};r(I)}}c(!1)},[u,f,p,o,n,s,r,e]),v=w.useCallback(()=>{u&&(h(ks()),g(!0))},[u]),S=w.useCallback(_=>{g(!1),h(_)},[]),N=w.useCallback(()=>{var _;if(n&&s)s({});else if(r){const k={...e,preferences:{...e.preferences,tablePrefs:{...(_=e.preferences)==null?void 0:_.tablePrefs,columnSettingsMap:{}}}};r(k)}c(!1)},[n,s,r,e]);return{columnSettings:i,columnSettingsOpen:a,activeColumnId:u,tempColumnSettings:f,isVisualEditing:n,openColumnSettings:x,applyColumnSettings:y,resetColumnSettings:v,resetAllColumnSettings:N,setColumnSettingsOpen:c,setTempColumnSettings:S}}function P0(e,t,n,r=!1){if(e==null)return l.jsx(Ac,{className:"h-4 w-4 text-muted-foreground"});if(!n)return typeof e=="number"?e.toLocaleString():String(e);if(n.type==="badge")return $3e(e);if(n.type==="link"&&e)return z3e(e);if(n.type==="progress"&&typeof e=="number")return B3e(e);if(n.type==="number"){const s=QQ(e,n);if(s!==null){const o=q5(e);return o!==null?V3e(o,n):s}}return n.type==="date"&&e&&r?H3e(e,n):String(e)}function $3e(e){return l.jsx($s,{variant:"outline",className:"px-1.5 text-muted-foreground",children:String(e)})}function z3e(e){let t=String(e);return!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),l.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 underline hover:text-blue-700",onClick:n=>n.stopPropagation(),children:String(e)})}function B3e(e){const t=Math.min(Math.max(0,e),100);let n="#ef4444";return t>=70?n="#22c55e":t>=40&&(n="#eab308"),l.jsxs("div",{className:"relative flex h-5 w-full items-center",children:[l.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-gray-200",children:l.jsx("div",{className:"h-full transition-all duration-300",style:{width:`${t}%`,backgroundColor:n}})}),l.jsxs("span",{className:"absolute inset-0 flex items-center justify-center text-xs font-medium",children:[t,"%"]})]})}function V3e(e,t){const{numberFormat:n}=t;let r=e.toLocaleString();try{r=In.formatNumberWithColumnSettings(e,n,n.locale||"en-US")||e.toLocaleString()}catch{r=e.toLocaleString()}if(n.showDataBar){const s=n.dataBarMinValue??0,o=n.dataBarMaxValue??100,i=(e-s)/(o-s)*100,a=Math.min(Math.max(0,i),100),c=n.dataBarColor||"#3b82f6";return l.jsxs("div",{className:"relative flex items-center",children:[l.jsx("div",{className:"absolute inset-y-0 left-0 bg-opacity-20",style:{width:`${a}%`,backgroundColor:c}}),l.jsx("span",{className:"relative px-2",children:r})]})}if(t.colorRanges&&t.colorRanges.length>0){for(const s of t.colorRanges)if(e>=s.min&&e<=s.max){const i=z1e(s.color);return l.jsx("span",{style:{backgroundColor:s.color,color:i,padding:"2px 6px",borderRadius:"4px"},children:r})}}return r}function H3e(e,t){const n=t.dateFormat;if(n!=null&&n.useRelativeTime)return ur.formatRelativeTime(String(e),(n==null?void 0:n.sourceTimezone)||"auto");const r=n!=null&&n.useCustomFormat&&(n!=null&&n.customFormat)?n.customFormat:(n==null?void 0:n.format)||"MM/dd/yyyy";return ur.formatDate(String(e),r,n==null?void 0:n.timezone,(n==null?void 0:n.sourceTimezone)||"auto")}function U3e({columnId:e,label:t,isVisualEditing:n,isTablePrintDisplayMode:r,groupByColumns:s,card:o,isResizing:i=!1,onOpenColumnSettings:a,onAggregationChange:c}){var u,d;return l.jsxs("div",{className:m.cn("group/table-head relative flex items-center gap-1.5",n&&"transition-[padding] duration-150 hover:pl-4 focus-within:pl-4"),children:[n&&l.jsx("span",{"data-grip-handle":"",className:"pointer-events-none absolute left-0 top-1/2 inline-flex -translate-y-1/2 cursor-grab items-center opacity-0 transition-opacity duration-150 group-hover/table-head:pointer-events-auto group-hover/table-head:opacity-100 group-focus-within/table-head:pointer-events-auto group-focus-within/table-head:opacity-100 active:cursor-grabbing","aria-label":"Drag to reorder column",children:l.jsx(bu,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-600","aria-hidden":"true"})}),l.jsx("span",{className:m.cn("min-w-0 flex-1 truncate"),title:t,children:t}),!i&&(n||c&&!r)&&l.jsx(kre,{label:t,isVisualEditing:n,groupByColumns:s,currentAggregation:{rowAggregates:((u=o==null?void 0:o.config)==null?void 0:u.rowAggregates)||[],columnAggregates:((d=o==null?void 0:o.config)==null?void 0:d.columnAggregates)||[]},onOpenColumnSettings:()=>a(e),onAggregationChange:r?void 0:c})]})}function q3e({columnId:e,displayLabel:t,isVisualEditing:n,isResizing:r=!1,onOpenColumnSettings:s}){return l.jsxs("div",{className:m.cn("group/table-head relative flex items-center gap-1.5",n&&"transition-[padding] duration-150 hover:pl-4 focus-within:pl-4"),children:[n&&l.jsx("span",{"data-grip-handle":"",className:"pointer-events-none absolute left-0 top-1/2 inline-flex -translate-y-1/2 cursor-grab items-center opacity-0 transition-opacity duration-150 group-hover/table-head:pointer-events-auto group-hover/table-head:opacity-100 group-focus-within/table-head:pointer-events-auto group-focus-within/table-head:opacity-100 active:cursor-grabbing","aria-label":"Drag to reorder column",children:l.jsx(bu,{className:"h-3 w-3 text-zinc-400 dark:text-zinc-600","aria-hidden":"true"})}),l.jsx("span",{className:"min-w-0 flex-1 truncate",title:t,children:t}),n&&!r&&l.jsx(kre,{label:t,isVisualEditing:n,groupByColumns:[],onOpenColumnSettings:()=>s(e)})]})}function kre({label:e,isVisualEditing:t,groupByColumns:n,currentAggregation:r,onOpenColumnSettings:s,onAggregationChange:o}){const i=[{value:"SUM",label:"Sum"},{value:"MAX",label:"Max"},{value:"MIN",label:"Min"},{value:"AVG",label:"Avg"},{value:"MEDIAN",label:"Median"}],a=!!o,c=(u,d)=>{var h;const f=d==="all"?"ALL":d;return(h=r==null?void 0:r.rowAggregates)==null?void 0:h.some(p=>p.function===u&&p.groupLevel===f)};return l.jsxs(Ys,{modal:!1,children:[l.jsx(Zs,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Configure ${e} column`,className:"inline-flex shrink-0 items-center justify-center rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",onClick:u=>u.stopPropagation(),children:l.jsx(Si,{className:"h-3 w-3"})})}),l.jsxs(Es,{align:"end",className:"w-56",children:[t&&l.jsxs(Nn,{className:"gap-2 text-xs",onClick:u=>{u.stopPropagation(),s()},children:[l.jsx(m.SlidersHorizontal,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Format column"]}),t&&a&&l.jsx(Sa,{}),a&&l.jsxs(l.Fragment,{children:[l.jsx($a,{className:"text-xs font-normal text-muted-foreground",children:"AGGREGATE"}),i.map(u=>{var f;const d=((f=r==null?void 0:r.rowAggregates)==null?void 0:f.some(h=>h.function===u.value))||!1;return l.jsxs(WL,{children:[l.jsx(L_,{className:"text-xs",children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsx("span",{children:u.label}),d&&l.jsx("span",{className:"ml-2 rounded bg-blue-100 px-1 py-0.5 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:"R"})]})}),l.jsxs($_,{className:"w-48",children:[l.jsx($a,{className:"text-xs font-normal text-muted-foreground",children:"ROWS"}),l.jsx(Nn,{className:"text-xs",onClick:()=>o==null?void 0:o({function:u.value,rowLevel:"all"}),children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsx("span",{children:"of all rows"}),c(u.value,"all")&&l.jsx(m.Check,{className:"h-4 w-4"})]})}),n.map(h=>l.jsx(Nn,{className:"text-xs",onClick:()=>o==null?void 0:o({function:u.value,rowLevel:h.id}),children:l.jsxs("div",{className:"flex w-full items-center justify-between",children:[l.jsxs("span",{children:["within ",h.label||h.name]}),c(u.value,h.id)&&l.jsx(m.Check,{className:"h-4 w-4"})]})},h.id))]})]},`${u.value}-${u.label}`)})]})]})]})}function W3e({row:e,columnId:t,columnAlias:n,groupByColumns:r,card:s,settings:o,alignment:i,idx:a}){var h,p,g;const c=e,u=!!(s!=null&&s.sql);if(c.isGrandTotal)return l.jsx(l.Fragment,{children:a===0?"Grand Total":""});if(c.isSubtotal){if(c.subtotalContext){const x=c.subtotalLevel,y=r.findIndex(v=>v.alias===x);if(a===y){const v=c.aggregate||"SUM",S=(g=(p=(h=s==null?void 0:s.config)==null?void 0:h.rowAggregates)==null?void 0:p.find(N=>N.groupLevel===c.subtotalLevel&&N.function===v))==null?void 0:g.label;return l.jsx(l.Fragment,{children:eJ(c,n,v,S)})}else if(a<y){const v=c[n];if(v&&v!=="__TOTAL__"){const S=P0(v,t,o,u);return l.jsx("div",{className:m.cn(i==="right"?"text-right":i==="center"?"text-center":"text-left"),children:S})}}}return l.jsx(l.Fragment,{})}const d=c[n],f=P0(d,t,o,u);return l.jsx("div",{className:m.cn(i==="right"?"text-right":i==="center"?"text-center":"text-left",d==null?"flex items-center":"",d==null?i==="right"?"justify-end":i==="center"?"justify-center":"justify-start":""),children:f})}function _re(e,t,n="left"){const r=t[e]||ks(),s=(r==null?void 0:r.textAlign)||n,o=r!=null&&r.width&&typeof r.width=="number"?r.width:150,i=(r==null?void 0:r.minWidth)??50,a=(r==null?void 0:r.maxWidth)??500;return{settings:r,alignment:s,size:o,minSize:i,maxSize:a}}function G3e({groupByColumns:e,pivotSchema:t,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a,valueFormatPreferences:c,resolveBoundCurrency:u}){const d=[],f=K3e({groupByColumns:e,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a});d.push(...f);const h=Y3e({pivotSchema:t,columnSettings:n,card:r,isVisualEditing:s,isTablePrintDisplayMode:o,onOpenColumnSettings:i,onAggregationChange:a,groupByColumns:e,valueFormatPreferences:c,resolveBoundCurrency:u});return d.push(...h),d}function K3e({groupByColumns:e,columnSettings:t,card:n,isVisualEditing:r,isTablePrintDisplayMode:s,onOpenColumnSettings:o,onAggregationChange:i}){return e.map((a,c)=>{const u=a.alias||a.name,{settings:d,alignment:f,size:h,minSize:p,maxSize:g}=_re(u,t,"left");return{id:u,accessorFn:b=>b[u],size:h,minSize:p,maxSize:g,enableResizing:!0,header:({column:b})=>l.jsx(U3e,{columnId:u,label:a.label||a.name,alignment:f,isVisualEditing:r,isTablePrintDisplayMode:s,groupByColumns:e,card:n,idx:c,isResizing:b.getIsResizing(),onOpenColumnSettings:o,onAggregationChange:i}),cell:({row:b})=>l.jsx(W3e,{row:b.original,columnId:u,columnAlias:a.alias||a.name,groupByColumns:e,card:n,settings:d,alignment:f,idx:c})}})}function Y3e({pivotSchema:e,columnSettings:t,card:n,isVisualEditing:r,isTablePrintDisplayMode:s,onOpenColumnSettings:o,onAggregationChange:i,groupByColumns:a,valueFormatPreferences:c,resolveBoundCurrency:u}){const d=!!(n!=null&&n.sql);return e.filter(f=>f.isMetricColumn).map((f,h)=>{var C,j,_;const p=f.alias,{settings:g,size:b,minSize:x,maxSize:y}=_re(p,t,"right"),v=Jl({card:n,columnKey:p,metricId:(_=(j=(C=n.config)==null?void 0:C.metricColumns)==null?void 0:j[h])==null?void 0:_.id}),S=Zh({card:n,columnId:p,metricIndex:h,groupByColumnCount:a.length,columnSettingsMap:t,valueFormatPreferences:c,boundCurrency:v?u(v):void 0}),N="right";return{id:p,accessorFn:k=>k[p],size:b,minSize:x,maxSize:y,enableResizing:!0,header:({column:k})=>l.jsx(q3e,{columnId:p,metricName:f.metricName,displayLabel:f.displayLabel||f.metricLabel||f.metricName,alignment:N,isVisualEditing:r,isTablePrintDisplayMode:s,groupByColumns:a,card:n,isResizing:k.getIsResizing(),onOpenColumnSettings:o,onAggregationChange:i}),cell:({row:k})=>{const I=k.original[p],T=P0(I,p,S||g,d);return l.jsx("div",{className:m.cn("text-right",I==null?"flex items-center justify-end":""),children:T})}}})}function Z3e({table:e,columns:t,groupByColumns:n,columnSettings:r,isTablePrintDisplayMode:s,disableRowTransitions:o=!1,tableAppearance:i}){const a=e.getRowModel().rows;return a!=null&&a.length?l.jsx($d,{children:a.map((c,u)=>{const d=c.original,f=d.isSubtotal&&!d.isGrandTotal;return l.jsx(Or,{"data-row-type":f?"subtotal":"data","data-subtotal-level":f?d.subtotalLevel:void 0,style:f?i.subtotalRowStyle:i.getDataRowStyle(u),className:m.cn("border-border/40",(o||i.hasHoverRowStyle)&&"!transition-none",!o&&!i.hasHoverRowStyle&&"transition-colors duration-150",!f&&i.dataRowClassName,f&&!s&&"border-t border-t-border/50 bg-muted/70 font-medium",!f&&"hover:bg-muted/40",f&&s&&"print:bg-gray-150 border-t-2 border-gray-300 bg-gray-100 font-semibold text-foreground print:border-gray-400",s&&"border-gray-300 print:break-inside-avoid print:border-gray-400"),children:c.getVisibleCells().map((h,p)=>{const g=p<n.length;return f?l.jsx(X3e,{cell:h,cellIndex:p,originalRow:d,groupByColumns:n,columnSettings:r,isGroupByColumn:g,isTablePrintDisplayMode:s,tableAppearance:i},h.id):l.jsx(Q3e,{cell:h,cellIndex:p,visibleRowIndex:u,originalRow:d,rows:a,groupByColumns:n,columnSettings:r,isGroupByColumn:g,isTablePrintDisplayMode:s,tableAppearance:i},h.id)})},c.id)})}):l.jsx($d,{children:l.jsx(Or,{className:"border-b-0 hover:bg-transparent",children:l.jsx(Wn,{colSpan:t.length,className:"h-auto py-12 text-center text-[13px] text-muted-foreground",children:"No results."})})})}function X3e({cell:e,cellIndex:t,originalRow:n,groupByColumns:r,columnSettings:s,isGroupByColumn:o,isTablePrintDisplayMode:i,tableAppearance:a}){const c=r.findIndex(u=>u.alias===n.subtotalLevel);if(t===c){const u=r.length-c;return l.jsx(Wn,{colSpan:u,...hd({tableAppearance:a,className:m.cn("px-4 font-medium text-foreground/90",i&&"border-gray-300 font-semibold text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}else{if(t<c)return l.jsx(Wn,{...hd({tableAppearance:a,className:m.cn("px-4 font-medium text-foreground/90",i&&"border-gray-300 font-semibold text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id);if(o&&t>c)return null}if(!o){const u=e.column.id,d=s[u],f=(d==null?void 0:d.textAlign)||"right";return l.jsx(Wn,{...hd({tableAppearance:a,className:m.cn("px-4 font-semibold text-foreground/90",f==="right"?"text-right":f==="center"?"text-center":"text-left",i&&"border-gray-300 text-foreground print:border-gray-400")}),children:l.jsx("div",{className:Dh(a,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}return null}function Q3e({cell:e,cellIndex:t,visibleRowIndex:n,originalRow:r,rows:s,groupByColumns:o,columnSettings:i,isGroupByColumn:a,isTablePrintDisplayMode:c,tableAppearance:u}){const d=e.column.id,f=i[d],h=(f==null?void 0:f.textAlign)||(a?"left":"right");if(a){if(c)return l.jsx(Wn,{...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90","align-top",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id);let p=!0,g=1;if(n>0){const x=o.map(v=>v.alias||v.name),y=s[n-1].original;if(!y.isSubtotal&&!y.isGrandTotal){let v=!0;for(let S=0;S<=t;S++)if(r[x[S]]!==y[x[S]]){v=!1;break}v&&(p=!1)}}if(!p)return null;const b=o.map(x=>x.alias||x.name);for(let x=n+1;x<s.length;x++){const y=s[x].original;if(y.isSubtotal||y.isGrandTotal)break;let v=!0;for(let S=0;S<=t;S++)if(r[b[S]]!==y[b[S]]){v=!1;break}if(v)g++;else break}return l.jsx(Wn,{rowSpan:g,...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90","align-top",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}return l.jsx(Wn,{...Eh({tableAppearance:u,style:{width:e.column.getSize(),minWidth:e.column.getSize(),maxWidth:e.column.getSize(),transition:"none"},className:m.cn("px-4 text-foreground/90",h==="right"?"text-right":h==="center"?"text-center":"text-left",c&&"border-gray-300 print:border-gray-400")}),children:l.jsx("div",{className:Dh(u,"leading-5"),children:pi(e.column.columnDef.cell,e.getContext())})},e.id)}function m9({grandTotalRow:e,groupByColumns:t,pivotSchema:n,columnSettings:r,card:s,isTablePrintDisplayMode:o,tableAppearance:i,valueFormatPreferences:a,resolveBoundCurrency:c}){var g,b;if(!e)return null;const u=!!(s!=null&&s.sql),d=e.aggregate||"SUM",f=(b=(g=s==null?void 0:s.config)==null?void 0:g.rowAggregates)==null?void 0:b.find(x=>x.groupLevel==="ALL"),h=f==null?void 0:f.label,p=tJ(d,h);return o?l.jsxs(Or,{style:i.grandTotalRowStyle,className:m.cn("border-t-2 border-gray-300 bg-gray-100 font-semibold","print:break-inside-avoid print:border-gray-400 print:bg-gray-200"),children:[l.jsx(Wn,{colSpan:t.length,...Vc({tableAppearance:i,overflow:"visible",className:"border-r px-4 font-semibold border-gray-300 text-foreground print:border-gray-400"}),children:p}),n.filter(x=>x.isMetricColumn).map((x,y)=>{var _,k,I;const v=x.alias,S=e[v],N=Jl({card:s,columnKey:v,metricId:(I=(k=(_=s.config)==null?void 0:_.metricColumns)==null?void 0:k[y])==null?void 0:I.id}),C=Zh({card:s,columnId:v,metricIndex:y,groupByColumnCount:t.length,columnSettingsMap:r,valueFormatPreferences:a,boundCurrency:N?c(N):void 0}),j=P0(S,v,C,u);return l.jsx(Wn,{...Vc({tableAppearance:i,overflow:"visible",className:"border-r px-4 text-right font-semibold text-foreground last:border-r-0 border-gray-300 print:border-gray-400"}),children:j},v)})]}):l.jsx("tfoot",{className:"sticky bottom-0 z-10 border-t border-border/60 bg-muted/95",style:i.grandTotalRowStyle,children:l.jsxs(Or,{className:"border-b-0",style:i.grandTotalRowStyle,children:[l.jsx(Wn,{colSpan:t.length,...Vc({tableAppearance:i,className:"px-4 font-semibold text-foreground/90"}),children:p}),n.filter(x=>x.isMetricColumn).map((x,y)=>{var _,k,I;const v=x.alias,S=e[v],N=Jl({card:s,columnKey:v,metricId:(I=(k=(_=s.config)==null?void 0:_.metricColumns)==null?void 0:k[y])==null?void 0:I.id}),C=Zh({card:s,columnId:v,metricIndex:y,groupByColumnCount:t.length,columnSettingsMap:r,valueFormatPreferences:a,boundCurrency:N?c(N):void 0}),j=P0(S,v,C,u);return l.jsx(Wn,{...Vc({tableAppearance:i,className:"numeric px-4 text-right font-semibold tabular-nums text-foreground/90"}),children:j},v)})]})})}function J3e({children:e,className:t,style:n,usePlainWrapper:r}){return r?l.jsx("div",{style:n,className:t,onMouseDown:s=>s.stopPropagation(),children:e}):l.jsxs(il,{style:n,className:t,onMouseDown:s=>s.stopPropagation(),children:[e,l.jsx(m.ScrollBar,{orientation:"horizontal",className:"z-20"})]})}function eI({card:e,data:t,groupByColumns:n=[],pivotSchema:r=[],paginationMetadata:s,onPaginationChange:o,onAggregationChange:i,isLoading:a}){var ue,fe;const c=w.useMemo(()=>Object.keys(t[0]||{}),[t]),{preferences:u,resolveBoundCurrency:d}=ka(e,c),{displayPreferences:f,shouldShowElement:h}=sl(),p=w.useMemo(()=>n3(),[]),g=!!(e!=null&&e.sql),{setCard:b,updateCardInFrame:x,updatePageSize:y}=m.useEditorActions(),{columnSettings:v,columnSettingsOpen:S,activeColumnId:N,tempColumnSettings:C,isVisualEditing:j,openColumnSettings:_,applyColumnSettings:k,resetColumnSettings:I,resetAllColumnSettings:T,setColumnSettingsOpen:E,setTempColumnSettings:D}=L3e(e,t),M=s3({displayMode:f.mode,isVisualEditing:j}),A=M.isPrint,{columnSizing:P,onColumnSizingChange:O}=t3({card:e}),$=Q_("aggregateTable",(fe=(ue=e==null?void 0:e.preferences)==null?void 0:ue.tablePrefs)==null?void 0:fe.density,M.mode==="document-print"?"document":"appearance"),V=$.densitySpec,[U,R]=w.useState(null),[q,W]=w.useState(null),F=w.useRef(!1),Z=w.useRef(!1),K=w.useMemo(()=>h_(n,e.config),[e.config,n]),Y=w.useMemo(()=>m_(r,e.config),[e.config,r]),X=w.useMemo(()=>G5(t,K),[t,K]),z=w.useMemo(()=>K5(t),[t]),B=w.useMemo(()=>G3e({groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isVisualEditing:j,isTablePrintDisplayMode:A,onOpenColumnSettings:_,onAggregationChange:i,valueFormatPreferences:u,resolveBoundCurrency:d}),[K,Y,v,e,j,A,_,i,u,d]),[{pageIndex:H,pageSize:L},G]=w.useState({pageIndex:0,pageSize:M.allowPagination?50:Number.MAX_SAFE_INTEGER}),J=M.allowPagination?L:Number.MAX_SAFE_INTEGER,oe=!!s&&M.allowPagination,Q=H_({data:X,columns:B,getCoreRowModel:B_(),getPaginationRowModel:!oe&&M.allowPagination?V_():void 0,manualPagination:oe||!M.allowPagination,pageCount:oe?s.pageCount:void 0,enableColumnResizing:!0,columnResizeMode:"onChange",onColumnSizingChange:O,state:{pagination:oe?{pageIndex:(s.page||1)-1,pageSize:s.pageSize||50}:{pageIndex:H,pageSize:L},columnSizing:P},onPaginationChange:oe?void 0:G}),{setRowSelection:ae,paginationMode:ie}=cre({data:X,card:e,pageSize:J,paginationMetadata:s,onPaginationChange:o}),le=()=>{if(!U||!q||U===q.colId){R(null),W(null);return}const pe=SB(e,K,Y,{draggingColumnId:U,targetColumnId:q.colId,side:q.side});if(!pe){R(null),W(null);return}const ge=Q.getAllLeafColumns().map(se=>se.id),de=ge.indexOf(U),ye=ge.indexOf(q.colId);if(de===-1||ye===-1){R(null),W(null);return}const ce=[...ge];ce.splice(de,1);const re=q.side==="before"?ye>de?ye-1:ye:ye>de?ye:ye+1;ce.splice(re,0,U);const ee={...e,config:pe};b(ee),x(ee),Q.setColumnOrder(ce),R(null),W(null)};return!t||t.length===0?l.jsx("div",{className:"flex h-full w-full items-center justify-center",children:l.jsx(Vd,{size:"md",color:"muted","aria-label":"Loading data"})}):l.jsxs("div",{className:"flex h-full w-full flex-col gap-2",children:[l.jsxs(J3e,{style:$.containerStyle,usePlainWrapper:M.usePlainWrapper,className:m.cn("data-table-scroll-container relative h-full rounded-none border border-border/60 bg-muted/20",A&&"overflow-visible"),children:[a&&ie==="server"&&l.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/50",children:l.jsx(Vd,{size:"md",color:"muted","aria-label":"Loading data"})}),l.jsx("div",{className:m.cn("relative",A&&"border border-gray-300 print:border-gray-400"),children:l.jsxs("table",{className:m.cn("w-full text-sm [border-spacing:0]",A&&"print:break-inside-avoid"),onMouseDown:pe=>pe.stopPropagation(),"data-table-type":"aggregate","data-group-by-count":K.length,"data-has-grand-total":!!z,children:[l.jsx(Pm,{style:$.headerStyle,className:m.cn("[&_tr]:border-b-0",!A&&"bg-muted",A&&"bg-gray-50 text-foreground print:table-header-group print:bg-gray-100"),children:Q.getHeaderGroups().map(pe=>l.jsx(Or,{children:pe.headers.map((ge,de)=>{const ye=de===pe.headers.length-1,ce=M.showEditorControls,re=U===ge.column.id,ee=(q==null?void 0:q.colId)===ge.column.id;return l.jsxs(hs,{colSpan:ge.colSpan,draggable:ce,onMouseDownCapture:se=>{var he,_e;const ne=se.target;F.current=!!((he=ne.closest)!=null&&he.call(ne,"[data-resize-handle]")),Z.current=!!((_e=ne.closest)!=null&&_e.call(ne,"[data-grip-handle]"))},onDragStart:se=>{if(ce){if(F.current||!Z.current){se.preventDefault();return}se.dataTransfer.effectAllowed="move",se.dataTransfer.setData("text/column-id",ge.column.id),R(ge.column.id)}},onDragOver:se=>{if(!M.showEditorControls||!U||U===ge.column.id)return;se.preventDefault();const ne=se.currentTarget.getBoundingClientRect(),he=ne.left+ne.width/2,_e={colId:ge.column.id,side:se.clientX<he?"before":"after"};if(!SB(e,K,Y,{draggingColumnId:U,targetColumnId:_e.colId,side:_e.side})){W(null);return}W(_e)},onDrop:se=>{M.showEditorControls&&(se.preventDefault(),le())},onDragEnd:()=>{R(null),W(null)},style:{...$.headerCellStyle,width:ge.getSize(),minWidth:ge.getSize(),maxWidth:ye?void 0:ge.getSize(),position:A?"relative":void 0,transition:"none",overflow:"hidden"},className:m.cn("h-auto border-b border-transparent px-4 py-2 align-middle font-medium uppercase tracking-[0.08em] text-muted-foreground",V.header,$.headerTextClassName,!A&&"relative bg-muted/95",M.allowStickyHeader&&$.isHeaderSticky&&"sticky top-0 z-10 supports-[backdrop-filter]:bg-muted/80 supports-[backdrop-filter]:backdrop-blur-sm",A&&"border-gray-300 font-semibold text-foreground print:border-gray-400",re&&"opacity-40"),children:[!A&&l.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute inset-x-0 bottom-0 h-px bg-border",style:$.headerDividerStyle}),ge.isPlaceholder?null:l.jsxs(l.Fragment,{children:[ee&&(q==null?void 0:q.side)==="before"&&l.jsx("div",{className:"pointer-events-none absolute -left-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),ee&&(q==null?void 0:q.side)==="after"&&l.jsx("div",{className:"pointer-events-none absolute -right-0.5 bottom-0 top-0 z-20 w-0.5 bg-foreground"}),pi(ge.column.columnDef.header,ge.getContext()),M.showEditorControls&&l.jsx(Kf,{header:ge,isResizing:ge.column.getIsResizing(),inset:ye})]})]},ge.id)})},pe.id))}),l.jsx(Z3e,{table:Q,columns:B,groupByColumns:K,columnSettings:v,isTablePrintDisplayMode:A,disableRowTransitions:p,tableAppearance:$}),A&&l.jsx(m9,{grandTotalRow:z,groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isTablePrintDisplayMode:A,tableAppearance:$,valueFormatPreferences:u,resolveBoundCurrency:d}),!A&&z&&l.jsx(m9,{grandTotalRow:z,groupByColumns:K,pivotSchema:Y,columnSettings:v,card:e,isTablePrintDisplayMode:A,tableAppearance:$,valueFormatPreferences:u,resolveBoundCurrency:d})]})})]}),M.allowPagination&&h("showPagination")&&(ie==="server"||Q.getFilteredRowModel().rows.length>10)&&l.jsx(U_,{totalColumns:B.length,pageCount:ie==="server"&&s?s.pageCount||0:Q.getPageCount(),pageIndex:Q.getState().pagination.pageIndex,pageSize:Q.getState().pagination.pageSize,rowCount:ie==="server"&&s?s.totalCount||0:Q.getFilteredRowModel().rows.length,selectedRowCount:Q.getFilteredSelectedRowModel().rows.length,setPageIndex:Q.setPageIndex,setPageSize:Q.setPageSize,canPreviousPage:ie==="server"&&s?s.hasPrevPage??!1:Q.getCanPreviousPage(),canNextPage:ie==="server"&&s?s.hasNextPage??!1:Q.getCanNextPage(),previousPage:Q.previousPage,nextPage:Q.nextPage,onPageSizePreferenceChange:M.showEditorControls?y:void 0,onClearSelection:()=>ae({}),paginationMode:ie,appearance:$.pagination}),h("showColumnSettings")&&l.jsx(QL,{column:N?Q.getColumn(N)??null:null,settings:C,onSettingsChange:D,onApply:k,onReset:I,onResetAll:T,open:S,onOpenChange:E,tableType:"aggregate",isSqlCard:g})]})}const e$e=e=>{const t=window.getSelection();if(!t||t.rangeCount===0)return 0;const n=t.getRangeAt(0),r=n.cloneRange();return r.selectNodeContents(e),r.setEnd(n.endContainer,n.endOffset),r.toString().length},t$e=(e,t)=>{var i,a;const n=window.getSelection(),r=document.createRange();let s=0;const o=c=>{var u;if(c.nodeType===Node.TEXT_NODE){const d=((u=c.textContent)==null?void 0:u.length)||0;if(s+d>=t)return r.setStart(c,t-s),r.setEnd(c,t-s),!0;s+=d}else for(let d=0;d<c.childNodes.length;d++)if(o(c.childNodes[d]))return!0;return!1};if(!o(e)&&e.childNodes.length>0){const c=e.childNodes[e.childNodes.length-1];c.nodeType===Node.TEXT_NODE&&(r.setStart(c,((i=c.textContent)==null?void 0:i.length)||0),r.setEnd(c,((a=c.textContent)==null?void 0:a.length)||0))}n==null||n.removeAllRanges(),n==null||n.addRange(r)};function cD({value:e,onSave:t,placeholder:n="Click to add content...",className:r,disabled:s=!1,isDynamicText:o=!1}){const i=w.useRef(null),[a,c]=w.useState(!1),[u,d]=w.useState(!1),f=w.useRef(void 0),h=w.useRef(e),[p,g]=w.useState(e),b=w.useRef(!1),y=m.useDashboardStore(k=>k.isVisualEditing)&&!s&&!o;w.useEffect(()=>{!b.current&&i.current&&(i.current.innerHTML=e||"",b.current=!0)},[e]),w.useEffect(()=>{!a&&e!==p&&(g(e),i.current&&b.current&&(i.current.innerHTML=e||""),h.current=e)},[e,a,p]);const v=w.useCallback(()=>{if(!i.current||!y)return;d(!0);const k=i.current.innerHTML;g(k),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{var T;const I=((T=i.current)==null?void 0:T.innerHTML)||"";if(I!==h.current){const E=i.current?e$e(i.current):0;t(I),h.current=I,g(I),d(!1),setTimeout(()=>{i.current&&a&&(i.current.focus(),t$e(i.current,E))},0)}},500)},[y,t,a]),S=w.useCallback(k=>{k.preventDefault();const I=k.clipboardData.getData("text/plain"),T=k.clipboardData.getData("text/html");let E="";if(T&&!I){const P=document.createElement("div");P.innerHTML=T,P.querySelectorAll("script, style").forEach(O=>O.remove()),P.querySelectorAll("p, div, br").forEach(O=>{if(O.tagName==="BR")O.replaceWith(`
|
|
793
793
|
`);else{const $=O.textContent||"";$&&O.replaceWith($+`
|
|
794
794
|
`)}}),E=P.innerHTML.replace(/\n\n+/g,`
|
|
795
795
|
`).replace(/^\n+|\n+$/g,"").replace(/\n/g,"<br>")}else E=I.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g,"<br>");const D=window.getSelection();if(!(D!=null&&D.rangeCount))return;const M=D.getRangeAt(0);M.deleteContents();const A=document.createRange().createContextualFragment(E);M.insertNode(A),M.collapse(!1),D.removeAllRanges(),D.addRange(M),v()},[v]),N=w.useCallback(()=>{y&&c(!0)},[y]),C=w.useCallback(()=>{if(c(!1),f.current&&clearTimeout(f.current),u&&i.current){const k=i.current.innerHTML||"";k!==h.current&&(t(k),h.current=k,d(!1))}},[u,t]),j=w.useCallback(k=>{const I=window.getSelection();if(!I||I.rangeCount===0)return;const T=I.toString();T&&(k.clipboardData.setData("text/plain",T),k.clipboardData.setData("text/html",I.getRangeAt(0).cloneContents().textContent||""),k.preventDefault())},[]),_=w.useCallback(k=>{var I,T;if(y){if(k.key==="Escape"&&((I=i.current)==null||I.blur()),k.key==="Backspace"){const E=window.getSelection();if(!(E!=null&&E.rangeCount))return;const D=E.getRangeAt(0);if(D.collapsed&&D.startContainer.nodeType===Node.TEXT_NODE&&D.startOffset===1&&D.startContainer.textContent===""){k.preventDefault();const M=D.startContainer.previousSibling;if(M&&M.nodeName==="BR"){M.remove(),(T=D.startContainer.parentNode)==null||T.removeChild(D.startContainer);const A=document.createRange(),P=i.current;P.lastChild?(A.selectNodeContents(P.lastChild),A.collapse(!1)):(A.selectNodeContents(P),A.collapse(!1)),E.removeAllRanges(),E.addRange(A),v()}}}if(k.key==="Enter"){k.preventDefault();const E=window.getSelection();if(!(E!=null&&E.rangeCount))return;const D=E.getRangeAt(0);D.deleteContents();const M=document.createElement("br");D.insertNode(M),D.setStartAfter(M),D.setEndAfter(M);const A=document.createTextNode("");D.insertNode(A),D.selectNodeContents(A),E.removeAllRanges(),E.addRange(D),v()}k.key==="Tab"&&(k.preventDefault(),document.execCommand("insertHTML",!1," "),v())}},[y,v]);return w.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]),l.jsx("div",{ref:i,contentEditable:y,suppressContentEditableWarning:!0,onInput:v,onPaste:S,onCopy:j,onFocus:N,onBlur:C,onKeyDown:_,className:m.cn("min-h-full whitespace-pre-wrap break-words rounded-control","text-[13px] leading-[1.55] text-foreground","border border-transparent outline-none transition-colors",y?["cursor-text px-3 py-3","hover:bg-muted/40","focus:border-ring focus:bg-transparent",a&&"border-ring bg-transparent"]:"cursor-default p-0",r),"data-placeholder":y||o?n:void 0})}if(typeof document<"u"&&!document.getElementById("content-editable-text-styles")){const t=document.createElement("style");t.id="content-editable-text-styles",t.textContent=`
|
|
@@ -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-DjyNG67M.js"))),fjt=w.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-EwylNae5.js"))),hjt=w.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CiMI9PO-.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-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(`
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}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">
|