react-semaphor 0.1.399 → 0.1.401
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/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +1 -1
- package/dist/brand-studio/index.cjs +1 -1
- package/dist/brand-studio/index.js +2 -2
- package/dist/chunks/{analyze-result-contract-CUO5QmqV.js → analyze-result-contract-BUgK3759.js} +675 -639
- package/dist/chunks/analyze-result-contract-S8u7CcPL.js +1 -0
- package/dist/chunks/{calendar-preferences-dialog-9SvYDLp6.js → calendar-preferences-dialog-C5u8P3Aa.js} +3 -3
- package/dist/chunks/{calendar-preferences-dialog-B3fnFtJt.js → calendar-preferences-dialog-D619F0ag.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-D3R4R7ww.js → dashboard-briefing-launcher-B2SY8WLW.js} +2 -2
- package/dist/chunks/{dashboard-briefing-launcher-APVyc9al.js → dashboard-briefing-launcher-Dsg9gmkm.js} +20 -14
- package/dist/chunks/{dashboard-controls-CHDQlMZ9.js → dashboard-controls-BLWXaG2Q.js} +6 -6
- package/dist/chunks/{dashboard-controls-v7jslCXR.js → dashboard-controls-DsFznKZ0.js} +1 -1
- package/dist/chunks/{dashboard-json-L1Qo5xcX.js → dashboard-json-B7RYi1qg.js} +1 -1
- package/dist/chunks/{dashboard-json-DF_syvRu.js → dashboard-json-DouaaMpH.js} +3 -3
- package/dist/chunks/{date-formatter-CzcPZx39.js → date-formatter-BlhBftA9.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-DwfIWUe-.js → edit-dashboard-visual-BxON7Y6L.js} +4 -4
- package/dist/chunks/{edit-dashboard-visual-qdruQruO.js → edit-dashboard-visual-CAs6Lm2_.js} +1 -1
- package/dist/chunks/index-BG9NaVLs.js +1346 -0
- package/dist/chunks/{index-DFOb_6HB.js → index-CjzRe2su.js} +3 -3
- package/dist/chunks/{index-BdVymLVq.js → index-kFwHL6im.js} +33680 -33120
- package/dist/chunks/{switch-BiU6-YSY.js → switch-CXMExaSF.js} +2385 -2348
- package/dist/chunks/{switch-CYG3dY8r.js → switch-oim6Xl36.js} +26 -26
- package/dist/chunks/update-policy-BmtOqvbf.js +3 -0
- package/dist/chunks/update-policy-KImUg4Od.js +831 -0
- package/dist/chunks/{use-create-flow-overlay-state-qe7DHQKr.js → use-create-flow-overlay-state-BlxamUgq.js} +1 -1
- package/dist/chunks/{use-create-flow-overlay-state-CwUkhLBL.js → use-create-flow-overlay-state-Ze0cRQQC.js} +3 -3
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/dashboard-authoring/index.cjs +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/data-app-builder/index.cjs +1 -1
- package/dist/data-app-builder/index.js +2 -2
- package/dist/data-app-codegen/index.cjs +1 -0
- package/dist/data-app-codegen/index.js +22 -0
- package/dist/data-app-codegen-node/index.cjs +462 -0
- package/dist/data-app-codegen-node/index.js +1424 -0
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +1 -1
- package/dist/data-app-sdk-adapters/index.cjs +1 -1
- package/dist/data-app-sdk-adapters/index.js +1 -1
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +1 -1
- package/dist/format-utils/index.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +7 -7
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/dashboard-authoring.d.ts +10 -0
- package/dist/types/dashboard.d.ts +10 -0
- package/dist/types/data-app-codegen-node.d.ts +1165 -0
- package/dist/types/data-app-codegen.d.ts +1137 -0
- package/dist/types/main.d.ts +16 -2
- package/dist/types/shared.d.ts +10 -0
- package/dist/types/surfboard.d.ts +10 -0
- package/dist/types/types.d.ts +17 -7
- package/package.json +9 -1
- package/dist/chunks/analyze-result-contract-OqFtOCpZ.js +0 -1
- package/dist/chunks/index-DH7hOGQl.js +0 -1346
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),h=require("react"),i=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),h=require("react"),i=require("./index-BG9NaVLs.js"),o=require("./switch-oim6Xl36.js"),ss=require("./layout-grid-C0OI-MRn.js"),K=require("./x-B6ghREd2.js"),me=require("./use-create-flow-overlay-state-BlxamUgq.js");require("./analyze-result-contract-S8u7CcPL.js");const Ae=require("./search-DNCejM7Z.js"),Gs=require("./date-formatter-B4EBSe9C.js");require("./index-DRlMUglg.js");require("react-dom");/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const Xt=K.createLucideIcon("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);function ta(){return e.jsx("div",{className:"space-y-1.5 py-1",children:[...Array(5)].map((t,s)=>e.jsxs("div",{className:"flex animate-pulse items-start gap-3 rounded-xl border border-transparent px-2.5 py-2.5",children:[e.jsx("div",{className:"mt-0.5 h-4 w-4 flex-shrink-0 rounded bg-muted/60"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/5 rounded bg-muted/60"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted/40"})]})]},s))})}function sa({open:t,onOpenChange:s,onSubmit:n,isCreating:r}){const[a,l]=h.useState(""),[c,u]=h.useState("");h.useEffect(()=>{t||(l(""),u(""))},[t]);const d=()=>{a.trim()&&n({title:a,description:c})},m=x=>{s(x)};return e.jsx(i.Dialog,{open:t,onOpenChange:m,children:e.jsxs(i.DialogContent,{showCloseButton:!1,className:"flex max-w-lg grid-cols-none flex-col gap-0 overflow-hidden rounded-[6px] border-border/60 p-0 shadow-lg",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ss.LayoutGrid,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(i.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"New library visual"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Visual"})]})]}),e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>m(!1),"aria-label":"Close",disabled:r,children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-3 px-4 py-3",children:[e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create a saved visual that can be reused across dashboards."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(o.Label,{htmlFor:"visual-title",className:"text-[12px]",children:"Name"}),e.jsx(o.Input,{id:"visual-title",size:"sm",placeholder:"Untitled visual",value:a,onChange:x=>l(x.target.value),disabled:r,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(o.Label,{htmlFor:"visual-description",className:"text-[12px]",children:"Description"}),e.jsx(o.Input,{id:"visual-description",size:"sm",placeholder:"Optional",value:c,onChange:x=>u(x.target.value),disabled:r})]})]}),e.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t border-border/60 px-4 py-2.5",children:[e.jsx(o.Button,{size:"xs",variant:"outline",onClick:()=>m(!1),disabled:r,children:"Cancel"}),e.jsx(o.Button,{size:"xs",onClick:d,disabled:!a.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Creating..."]}):"Create library visual"})]})]})})}function wn(t){return t?new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Unknown"}function Cn(t,s){var r;const n=(r=t.ownership.createdBy)==null?void 0:r.type;return n==="tenant"||n==="organization"&&s}function rs(t,s){var n,r;return Cn(t,s)?((n=t.ownership.createdBy)==null?void 0:n.name)||((r=t.createdByTenantUserRel)==null?void 0:r.name)||t.lastModifiedBy||"Unknown":"Organization"}function na(t,s){return rs(t,s).split(/\s+/).filter(Boolean).slice(0,2).map(r=>r.charAt(0).toUpperCase()).join("")||"?"}function ra(t){const s=(t||"").toLowerCase();return s.includes("table")?o.Table2:s.includes("pie")||s.includes("donut")?i.ChartPie:s.includes("line")?i.ChartLine:s.includes("bar")?o.ChartColumn:ss.LayoutGrid}function aa({visual:t}){const s=t.ownership.status==="public"?"Public":t.ownership.status==="shared"||t.ownership.sharedCount>0?"Shared":"Private";return e.jsx("span",{className:"inline-flex items-center rounded-[4px] border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground",children:s})}function oa({open:t,onOpenChange:s}){const[n,r]=h.useState(""),[a,l]=h.useState(new Set),[c,u]=h.useState(!1),[d,m]=h.useState(null),[x,g]=h.useState(null),[f,b]=h.useState(!1),[A,S]=h.useState(null),[N,j]=h.useState(null),w=()=>{l(new Set),m(null),g(null),b(!1),S(null)},y=()=>{s(!1),w()},{selectVisual:C}=i.useManagementActions(),{handleAddLibraryVisual:T,handleEditLibraryVisual:V}=me.useVisualUtils(),{isConsoleMode:D}=i.useDashboardPreferences(),{resources:F,isLoading:U,isError:G,createResource:B,updateResource:_,deleteResourceAsync:$,duplicateResource:M,isCreating:Q,isDeleting:ee}=i.useVisualManagement(void 0,E=>{u(!1),E&&(C(E),V(E),y())}),{startUpdating:L,stopUpdating:W,isUpdating:k}=i.useResourceUpdateState(),oe=F,Y=h.useMemo(()=>{const E=n.trim().toLowerCase();return E?oe.filter(H=>{var te,we,Me;return((te=H.title)==null?void 0:te.toLowerCase().includes(E))||((we=H.description)==null?void 0:we.toLowerCase().includes(E))||((Me=H.kind)==null?void 0:Me.toLowerCase().includes(E))}):oe},[n,oe]),X=h.useMemo(()=>oe.filter(E=>a.has(E.id)),[a,oe]),he=X.filter(E=>E.permissions.canDelete),ye=X.filter(E=>E.permissions.canShare),ie=Y.length>0&&Y.every(E=>a.has(E.id)),z=Y.some(E=>a.has(E.id)),Pe=E=>{const H=new Set(a);E(H),l(H)},ve=E=>{Pe(H=>{H.has(E)?H.delete(E):H.add(E)})},ke=()=>{l(E=>{const H=new Set(E);return ie?Y.forEach(te=>H.delete(te.id)):Y.forEach(te=>H.add(te.id)),H})},Se=async E=>{(await T(E)).success&&y()},q=async()=>{const E=X;if(E.length===0)return;let H=!1;for(const te of E)if(!(await T(te)).success){H=!0;break}H||y()},Ne=E=>{V(E),y()},O=E=>{j(E),M(E,{onSettled:()=>j(null)})},ne=()=>{if(he.length===0){i.ue.error("Select a visual you can delete");return}S(null),b(!0)},qe=async()=>{const E=A?[A]:he;try{for(const H of E)await $(H.id);l(H=>{const te=new Set(H);return E.forEach(we=>te.delete(we.id)),te}),b(!1),S(null)}catch{}},Oe=()=>{if(X.length!==1){i.ue.error("Select one visual to share");return}const[E]=X;if(!E.permissions.canShare){i.ue.error("You do not have permission to share this visual");return}m(E)},I=({title:E,description:H})=>{if(!x)return;const te={};if(E!==x.title&&(te.title=E),(x.description||"")!==H&&(te.description=H),Object.keys(te).length===0){g(null);return}const we=Object.keys(te),Me=we.length===1?we[0]:void 0;L(x.id,Me),_({resourceId:x.id,data:te},{onSuccess:()=>{W(x.id,Me),g(null)},onError:()=>{W(x.id,Me)}})},P=E=>{s(E),E||w()},fe=A?1:he.length;return e.jsxs(e.Fragment,{children:[e.jsx(i.Dialog,{open:t,onOpenChange:P,children:e.jsxs(i.DialogContent,{showCloseButton:!1,className:"flex max-h-[80vh] w-[min(72rem,calc(100vw-2rem))] max-w-none grid-cols-none flex-col gap-0 overflow-hidden rounded-[6px] border-border/60 p-0 shadow-lg",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(o.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(i.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"Visuals library"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Add to dashboard"})]})]}),e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>P(!1),"aria-label":"Close visuals library",children:"×"})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 px-3 py-2",children:[e.jsxs("div",{className:"relative min-w-[12rem] flex-1 md:max-w-md",children:[e.jsx(Ae.Search,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{autoFocus:!0,value:n,onChange:E=>r(E.target.value),placeholder:"Search visuals...",className:"h-7 w-full rounded-control border border-input bg-background pl-7 pr-2 text-[12px] text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none","aria-label":"Search visuals"})]}),e.jsxs(o.Button,{size:"xs",variant:"outline",className:"ml-auto",onClick:()=>u(!0),children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"New library visual"]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:U?e.jsx("div",{className:"p-3",children:e.jsx(ta,{})}):G?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:e.jsx("p",{className:"text-[13px] text-destructive",children:"Failed to load visuals"})}):Y.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:[e.jsx(ss.LayoutGrid,{className:"h-5 w-5 text-muted-foreground/60"}),e.jsx("p",{className:"text-[13px] font-medium",children:n?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:n?"Try a different search.":"Create a saved visual to add it here."})]}):e.jsx(ia,{visuals:Y,selectedIds:a,allFilteredSelected:ie,someFilteredSelected:z,onSelectAll:ke,onToggleSelection:ve,onAddVisual:Se,onOpenVisual:Ne,onEditDetails:g,onShareVisual:m,onDeleteVisual:E=>{S(E),b(!0)},onDuplicateVisual:O,duplicatingId:N,isDeleting:ee,isConsoleMode:D})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border/60 px-3 py-2",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:a.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-[12px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium tabular-nums text-foreground",children:a.size})," ","selected"]}),e.jsx(o.Button,{size:"xs",variant:"ghost",onClick:()=>l(new Set),children:"Clear"}),e.jsxs(o.Button,{size:"xs",variant:"outline",onClick:Oe,disabled:X.length!==1||ye.length!==1,children:[e.jsx(i.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),e.jsxs(o.Button,{size:"xs",variant:"outline",className:"text-destructive hover:text-destructive",onClick:ne,disabled:he.length===0,children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete ",he.length||a.size]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(o.Button,{size:"xs",variant:"outline",onClick:()=>P(!1),children:"Close"}),e.jsxs(o.Button,{size:"xs",onClick:q,disabled:a.size===0,children:[e.jsx(o.Check,{className:"h-3.5 w-3.5"}),a.size===0?"Add to dashboard":`Add ${a.size} visual${a.size===1?"":"s"}`]})]})]})]})}),e.jsx(sa,{open:c,onOpenChange:u,onSubmit:B,isCreating:Q}),d&&e.jsx(i.ShareDialog,{resource:d,resourceType:i.ResourceType.VISUAL,onClose:()=>m(null)}),x&&e.jsx(i.ResourceEditDialog,{open:!!x,resourceLabel:"Visual",initialTitle:x.title||"",initialDescription:x.description||"",onClose:()=>g(null),onSave:I,isSaving:k(x.id)}),e.jsx(i.AlertDialog,{open:f,onOpenChange:E=>{!E&&ee||(b(E),E||S(null))},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsxs(i.AlertDialogTitle,{children:["Delete ",fe," visual",fe===1?"":"s","?"]}),e.jsx(i.AlertDialogDescription,{children:"This cannot be undone. Visuals already added to dashboards may need to be removed from those dashboards separately."})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{disabled:ee,children:"Cancel"}),e.jsxs(i.AlertDialogAction,{onClick:E=>{E.preventDefault(),qe()},disabled:ee||fe===0,children:[ee?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),ee?"Deleting...":"Delete"]})]})]})})]})}function ia({visuals:t,selectedIds:s,allFilteredSelected:n,someFilteredSelected:r,onSelectAll:a,onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:f,isDeleting:b,isConsoleMode:A}){return e.jsxs("div",{className:"min-w-[48rem]",children:[e.jsxs("div",{className:"grid h-9 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/60 px-3 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(i.Checkbox,{checked:n?!0:r?"indeterminate":!1,onCheckedChange:a,"aria-label":"Select all visuals"}),e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Created by"}),e.jsx("span",{children:"Updated"}),e.jsx("span",{children:"Visibility"}),e.jsx("span",{className:"text-right",children:"Shared"}),e.jsx("span",{className:"text-right",children:"Actions"})]}),t.map(S=>e.jsx(la,{visual:S,selected:s.has(S.id),onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:f,isDeleting:b,isConsoleMode:A},S.id))]})}function la({visual:t,selected:s,onToggleSelection:n,onAddVisual:r,onOpenVisual:a,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g}){var A;const f=ra(t.kind),b=()=>{r(t)};return e.jsxs("div",{className:o.cn("group grid min-h-12 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/50 px-3 text-[13px] hover:bg-muted/50",s&&"bg-muted/70"),children:[e.jsx("div",{children:e.jsx(i.Checkbox,{checked:s,onCheckedChange:()=>n(t.id),"aria-label":`Select ${t.title||"visual"}`})}),e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 rounded-[4px] text-left outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:b,"aria-label":`Add ${t.title||"visual"} to dashboard`,children:[e.jsx(f,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-foreground",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),((A=t.description)==null?void 0:A.trim())&&e.jsx("div",{className:"truncate text-[11px] text-muted-foreground",title:t.description,children:t.description})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.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:na(t,g)}),e.jsx("span",{className:"truncate text-muted-foreground",children:rs(t,g)})]}),e.jsx("span",{className:"text-muted-foreground",children:wn(t.updatedAt)}),e.jsx(aa,{visual:t}),e.jsx("span",{className:"text-right tabular-nums text-muted-foreground",children:t.ownership.sharedCount>0?t.ownership.sharedCount:"—"}),e.jsx(ca,{visual:t,onOpenVisual:a,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g})]})}function ca({visual:t,onOpenVisual:s,onEditDetails:n,onShareVisual:r,onDeleteVisual:a,onDuplicateVisual:l,duplicatingId:c,isDeleting:u,isConsoleMode:d}){return e.jsxs("div",{className:"flex items-center justify-end gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",onClick:m=>m.stopPropagation(),children:[e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0",onClick:()=>s(t),"aria-label":"Edit visual",children:e.jsx(i.PenLine,{className:"h-3.5 w-3.5"})}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0","aria-label":"More actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"z-[60] w-44 rounded-[6px] border-border/60 p-1 shadow-sm",children:[e.jsxs(i.DropdownMenuItem,{onClick:()=>s(t),children:[e.jsx(i.PenLine,{className:"h-3.5 w-3.5"}),"Edit visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>l(t.id),disabled:c===t.id,children:[c===t.id?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(i.Copy,{className:"h-3.5 w-3.5"}),c===t.id?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsxs(i.DropdownMenuItem,{onClick:()=>n(t),children:[e.jsx(i.PenLine,{className:"h-3.5 w-3.5"}),"Edit details"]}),t.permissions.canShare&&e.jsxs(i.DropdownMenuItem,{onClick:()=>r(t),children:[e.jsx(i.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(i.DropdownMenuSeparator,{}),e.jsxs(i.DropdownMenuItem,{className:"text-destructive focus:bg-destructive/10 focus:text-destructive",onClick:()=>a(t),disabled:u,children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),u?"Deleting...":"Delete"]})]}),e.jsx(i.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-1.5 text-[11px] text-muted-foreground",children:[Cn(t,d)&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(i.User,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:rs(t,d)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(i.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:wn(t.updatedAt)})]})]})]})]})]})}function da({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:a=!1,destinationMode:l="both",onConfirm:c}){const[u,d]=h.useState(n&&r?`Copy of ${r}`:r||""),[m,x]=h.useState("");h.useEffect(()=>{t&&(d(n&&r?`Copy of ${r}`:r||""),x(""))},[t,n,r]);const g=!!u.trim(),f=l==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:l==="library"?{saveToLibrary:!0,saveToCurrentDashboard:!1,badgeType:"library",description:"Creates a reusable visual in Visual Library.",actionLabel:"Save as Library Visual"}:{saveToLibrary:!0,saveToCurrentDashboard:!0,badgeType:"linked",description:"Creates a new library visual and adds a linked copy to this dashboard.",actionLabel:"Save Copy as Linked Visual"},b=()=>{!g||a||c({name:u.trim(),description:m.trim()||void 0,saveToLibrary:f.saveToLibrary,saveToCurrentDashboard:f.saveToCurrentDashboard})};return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(i.DialogHeader,{children:[e.jsxs(i.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),f.badgeType!=="local"&&e.jsx(me.VisualBadge,{type:f.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(i.DialogDescription,{children:f.description})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(o.Label,{htmlFor:"name",children:"Name"}),e.jsx(o.Input,{id:"name",value:u,onChange:A=>d(A.target.value),placeholder:"Enter visual name",disabled:a})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(i.Textarea,{id:"description",value:m,onChange:A=>x(A.target.value),placeholder:"Enter visual description",rows:3,disabled:a})]})]}),e.jsxs(i.DialogFooter,{children:[e.jsx(o.Button,{variant:"outline",onClick:()=>s(!1),disabled:a,children:"Cancel"}),e.jsxs(o.Button,{onClick:b,disabled:!g||a,children:[a&&e.jsx(o.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f.actionLabel]})]})]})})}function ua(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[a,l]=h.useState(null),[c,u]=h.useState(null),d=o.useEditorStore(D=>D.frame),m=o.useEditorStore(D=>D.card),x=i.useSelectedVisual(),g=o.useDashboardStore(D=>D.selectedSheetId),f=o.useDashboardStore(D=>D.dashboard),{getUpdatedFrame:b}=me.useVisualUtils(),{selectVisual:A}=i.useManagementActions(),{addFrame:S,setSelectedFrameId:N,setIsVisualEditing:j}=o.useDashboardActions(),w=i.useResolveExistingFrameSemanticExecutionPayload(),y=!!(d!=null&&d.visualId),C=(()=>{var D,F;return((D=d==null?void 0:d.cards)==null?void 0:D.length)===1&&((F=d.cards[0])!=null&&F.title)?d.cards[0].title:x!=null&&x.title?x.title:(m==null?void 0:m.title)||"Untitled Visual"})(),T=i.useCreateVisualWithFrame(D=>{D!=null&&D.id&&(A(D),n&&a&&c&&g&&(async()=>{try{const F={...a,id:o.v4(),visualId:D.id};S(g,F,{position:"end",semanticExecutionPayload:c}),N(F.id),r(!1),l(null),u(null),j(!1)}catch(F){console.error("Failed to promote semantic metadata for saved visual:",F),i.ue.error(F instanceof Error?F.message:"Failed to prepare semantic metadata for the saved visual")}})(),s(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:s,handleSaveAs:async D=>{if(!g){i.ue.error("No sheet selected");return}const F=b(),U=o.getDynamicFrameSaveIssue(F);if(U){i.ue.error(U);return}const B=F.cards.length===1?{...F,cards:F.cards.map(_=>({..._,title:D.name}))}:F;if(D.saveToLibrary){let _=null;if(D.saveToCurrentDashboard)try{_=await w(B,{previousFrame:i.findDashboardFrameById(f,B.id)})}catch(M){console.error("Failed to prepare semantic metadata before saving visual:",M),i.ue.error(M instanceof Error?M.message:"Failed to prepare semantic metadata for the saved visual");return}r(D.saveToCurrentDashboard),l(B),u(_);const $={title:D.name,description:D.description,frameObject:B,isPrivate:!1};T.mutate($)}else if(D.saveToCurrentDashboard){const _={...B,id:o.v4(),visualId:void 0};try{const $=await w(B,{previousFrame:i.findDashboardFrameById(f,B.id)});S(g,_,{position:"end",semanticExecutionPayload:$}),N(_.id),i.ue.success("Visual saved to dashboard"),s(!1),j(!1)}catch($){console.error("Failed to save visual to dashboard:",$),i.ue.error($ instanceof Error?$.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:y,currentVisualName:C,isSaving:T.isPending}}function ma(t={}){const s=o.useEditorStore(B=>B.frame),n=o.useEditorStore(B=>B.editorContext),r=i.useManagementStore(B=>B.selectedVisual),a=o.useDashboardStore(B=>B.selectedFrameId),l=o.useDashboardStore(B=>B.selectedSheetId),c=o.useDashboardStore(B=>B.dashboard),{setIsVisualEditing:u,updateFrame:d}=o.useDashboardActions(),[m,x]=h.useState(!1),[g,f]=h.useState("both"),b=i.useResolveExistingFrameSemanticExecutionPayload(),A=(n==null?void 0:n.type)==="documentSection",S=!!(s!=null&&s.visualId||r!=null&&r.id),N=!!(s!=null&&s.visualId&&a),j=S&&!N,{saveAsDialogOpen:w,setSaveAsDialogOpen:y,handleSaveAs:C,isLibraryVisual:T,currentVisualName:V,isSaving:D}=ua(),{getUpdatedFrame:F}=me.useVisualUtils();if(A)return e.jsxs(e.Fragment,{children:[e.jsx(me.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(me.EditorCancelButton,{})]});const U=async()=>{if(!l){i.ue.error("No sheet selected");return}if(m)return;x(!0);const B=F(),_=o.getDynamicFrameSaveIssue(B);if(_){x(!1),i.ue.error(_);return}const $={...B,visualId:void 0},M=i.findDashboardFrameById(c,$.id);try{const Q=await b($,{previousFrame:M});d(l,$,{semanticExecutionPayload:Q})}catch(Q){console.error("Failed to apply local semantic metadata:",Q),x(!1),i.ue.error(Q instanceof Error?Q.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{x(!1),i.ue.success("Changes applied. Visual is now local to this dashboard"),u(!1)},300)},G=B=>{f(B),y(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(me.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&j&&e.jsx(me.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&N&&e.jsx(me.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(o.Button,{variant:"default",size:"xs",className:"w-7 !rounded-none border-l border-primary-foreground/20 px-0","aria-label":"Open visual save options",disabled:D||m,children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[N&&e.jsxs(e.Fragment,{children:[e.jsxs(i.DropdownMenuItem,{onClick:U,disabled:m,children:[e.jsx(o.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(i.DropdownMenuSeparator,{})]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("local"),disabled:D,children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("library"),disabled:D,children:[e.jsx(me.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("both"),disabled:D,children:[e.jsx(me.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(me.EditorCancelButton,{}),e.jsx(da,{open:w,onOpenChange:B=>{D||y(B)},isLibraryVisual:T,currentVisualName:V,isSaving:D,destinationMode:g,onConfirm:C})]})}function ha({className:t}){const s=o.useEditorStore(m=>m.isDevMode),n=o.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=o.useEditorActions(),{config:a}=h.useContext(i.SemaphorContext).tokenProps,l=(a==null?void 0:a.showAdvancedMode)!==!1;if(!n||!l)return null;const c=s?o.SlidersHorizontal:i.CodeXml,u=s?"Drag & drop":"SQL",d=s?"Switch to drag-and-drop mode":"Switch to SQL mode";return e.jsxs("button",{type:"button","aria-label":d,title:d,onClick:()=>r(!s),className:o.cn("inline-flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 text-[12px] font-medium text-foreground transition-colors hover:bg-muted/40 focus-visible:border-ring focus-visible:outline-none",t),children:[e.jsx(c,{className:"h-3 w-3 text-muted-foreground"}),u]})}function xa({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:a,title:l="Unsaved changes",description:c="You have unsaved changes to this dashboard. What would you like to do?",cancelLabel:u="Cancel",discardLabel:d="Discard",saveLabel:m="Save"}){const x=g=>{!g&&a||s(g)};return e.jsx(i.AlertDialog,{open:t,onOpenChange:x,children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:l}),e.jsx(i.AlertDialogDescription,{children:c})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(o.Button,{type:"button",size:"xs",onClick:r,disabled:a,variant:"ghost",className:"mr-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",children:d}),e.jsx(i.AlertDialogCancel,{disabled:a,children:u}),e.jsx(o.Button,{type:"button",size:"xs",onClick:n,disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(o.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):m})]})]})})}const pa=1e4,fa=15e3,ga=3e4,ba=3e4,ja=12e4,Xs=2*60*60*1e3;function ya(t){const s=Date.now()-t.getTime();return s<ba?pa:s<ja?fa:ga}function va(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(f=>f.activeExports),[r,a]=h.useState(typeof document<"u"?!document.hidden:!0),l=h.useRef(null),c=h.useRef(!1),u=h.useRef(void 0),d=s==null?void 0:s.apiServiceUrl,m=t==null?void 0:t.accessToken,x=h.useCallback(()=>{const f=i.useExportStore.getState().activeExports;return Array.from(f.values()).filter(b=>i.isExportInProgress(b.status))},[]);h.useEffect(()=>{if(typeof document>"u")return;const f=()=>{a(!document.hidden)};return document.addEventListener("visibilitychange",f),()=>{document.removeEventListener("visibilitychange",f)}},[]);const g=h.useCallback(async()=>{if(!d||!m){c.current=!1;return}const f=x();if(f.length===0){c.current=!1;return}const b=Date.now(),A=f.filter(y=>b-y.startedAt.getTime()>Xs);if(A.length>0){const{updateExport:y}=i.useExportStore.getState().actions;for(const C of A)y(C.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const S=f.filter(y=>b-y.startedAt.getTime()<=Xs);if(S.length===0){c.current=!1;return}const N=await Promise.allSettled(S.map(async y=>{try{const C=await i.getExportStatus(d,m,y.id);let T;if(C.status==="completed")try{T=await i.getDownloadUrl(d,m,y.id)}catch(V){console.error(`[useExportPolling] Failed to get download URL for ${y.id}:`,V)}return{id:y.id,status:C.status,progress:C.progress,completedChunks:C.completedChunks,completedAt:C.completedAt?new Date(C.completedAt):void 0,lastUpdatedAt:new Date,fileSize:C.fileSize,error:C.error,downloadUrl:T}}catch(C){return console.error(`[useExportPolling] Failed to poll export ${y.id}:`,C),null}})),{updateExport:j}=i.useExportStore.getState().actions;for(const y of N)y.status==="fulfilled"&&y.value&&j(y.value.id,y.value);const w=x();if(w.length>0&&!document.hidden){const y=w.reduce((T,V)=>V.startedAt<T?V.startedAt:T,w[0].startedAt),C=ya(y);l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{var T;(T=u.current)==null||T.call(u)},C)}else c.current=!1},[d,m,x]);return h.useEffect(()=>{u.current=g},[g]),h.useEffect(()=>{var b;x().length>0&&r&&!c.current&&(c.current=!0,(b=u.current)==null||b.call(u))},[n,r,x]),h.useEffect(()=>{var b;const f=x();r&&f.length>0&&!c.current&&(c.current=!0,(b=u.current)==null||b.call(u))},[r,x]),h.useEffect(()=>{!r&&l.current&&(clearTimeout(l.current),l.current=null,c.current=!1)},[r]),h.useEffect(()=>()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),{isPolling:c.current,isTabVisible:r,inProgressCount:x().length}}function Na(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(u=>u.activeExports),{addExport:r}=i.useExportActions(),a=h.useRef(!1),l=s==null?void 0:s.apiServiceUrl,c=t==null?void 0:t.accessToken;h.useEffect(()=>{if(a.current||!l||!c)return;(async()=>{try{const{exports:d}=await i.getExports(l,c,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const m of d){if(n.has(m.id))continue;const x=m.totalChunks?Math.round(m.completedChunks/m.totalChunks*100):0;let g;if(m.status==="completed")try{g=await i.getDownloadUrl(l,c,m.id)}catch(b){console.error(`[useExportRecovery] Failed to get download URL for ${m.id}:`,b)}const f={id:m.id,status:m.status,progress:x,title:wa(m),totalRows:m.totalRows,totalChunks:m.totalChunks,completedChunks:m.completedChunks,startedAt:new Date(m.createdAt),lastUpdatedAt:new Date,completedAt:m.completedAt?new Date(m.completedAt):void 0,fileSize:m.fileSize,error:m.error,expiresAt:new Date(m.expiresAt),downloadUrl:g};r(f)}a.current=!0}catch(d){console.error("[useExportRecovery] Failed to recover exports:",d),a.current=!0}})()},[l,c,r,n])}function wa(t){return t.title?t.title:i.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function Sn({export:t,onRemove:s}){const n=()=>{t.downloadUrl&&window.open(t.downloadUrl,"_blank")},r=u=>{u.stopPropagation(),s==null||s(t.id)},a=()=>{switch(t.status){case"completed":return e.jsx(i.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(Jr,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"});default:return e.jsx(o.LoaderCircle,{className:"text-foreground-muted mt-0.5 h-5 w-5 shrink-0 animate-spin"})}},l=i.isExportInProgress(t.status),c=(()=>{switch(t.status){case"pending":return"Queued...";case"processing":return"Processing...";case"chunking":return"Processing...";case"compacting":return"Finalizing...";default:return"Processing..."}})();return e.jsxs("div",{className:"group p-4 transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[a(),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h4",{className:"mb-1 truncate text-sm font-medium",children:t.title}),t.status==="completed"&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[t.totalRows.toLocaleString()," rows"]}),t.fileSize&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:i.formatFileSize(t.fileSize)})]})]}),l&&e.jsx("div",{className:"text-xs text-muted-foreground",children:c}),t.status==="failed"&&e.jsx("div",{className:"line-clamp-2 text-xs text-destructive",children:t.error||"Export failed"})]})]}),e.jsx(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:r,"aria-label":"Remove notification",children:e.jsx(K.X,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"ml-8",children:[t.status==="completed"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs.formatDistanceToNow(t.startedAt,{addSuffix:!0})}),t.downloadUrl&&e.jsxs(o.Button,{size:"sm",variant:"outline",className:"h-8 bg-transparent",onClick:n,children:[e.jsx(i.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),l&&e.jsxs("div",{children:[e.jsx(i.Progress,{value:t.progress,className:"h-1.5"}),e.jsxs("span",{className:"mt-1 block text-xs text-muted-foreground",children:[t.progress,"% complete"]})]}),t.status==="failed"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function kn(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(S=>S.activeExports),{clearCompleted:r,removeExport:a,updateExport:l}=i.useExportActions(),[c,u]=h.useState(!1),[d,m]=h.useState(!1),x=Array.from(n.values()).sort((S,N)=>N.startedAt.getTime()-S.startedAt.getTime()),g=x.some(S=>S.status==="completed"||S.status==="failed"),f=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!(!S||!N)){u(!0);try{const j=Array.from(n.values());await Promise.all(j.map(async w=>{try{const y=await i.getExportStatus(S,N,w.id);let C;if(y.status==="completed")try{C=await i.getDownloadUrl(S,N,w.id)}catch(T){console.error(`Failed to get download URL for ${w.id}:`,T)}l(w.id,{status:y.status,progress:y.progress,completedChunks:y.completedChunks,completedAt:y.completedAt?new Date(y.completedAt):void 0,lastUpdatedAt:new Date,fileSize:y.fileSize,error:y.error,downloadUrl:C})}catch(y){console.error(`Failed to refresh export ${w.id}:`,y)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,l]),b=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!S||!N){r();return}m(!0);try{const j=x.filter(y=>y.status==="completed"||y.status==="failed"),w=await Promise.allSettled(j.map(async y=>(await i.cancelExport(S,N,y.id),y.id)));for(const y of w)y.status==="fulfilled"?a(y.value):console.error("Failed to delete export:",y.reason)}finally{m(!1)}},[x,s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,r,a]),A=h.useCallback(async S=>{const N=s==null?void 0:s.apiServiceUrl,j=t==null?void 0:t.accessToken;if(N&&j)try{await i.cancelExport(N,j,S),a(S);return}catch(w){console.error(`Failed to cancel export ${S}:`,w)}a(S)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,a]);return x.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Ws,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active exports"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Large exports will appear here"})]}):e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h4",{className:"font-semibold",children:"Exports"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:f,disabled:c,title:"Refresh status",children:e.jsx(i.RefreshCw,{className:`h-4 w-4 ${c?"animate-spin":""}`})}),g&&e.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-sm",onClick:b,disabled:d,children:d?"Clearing...":"Clear all"})]})]}),e.jsx("div",{className:"max-h-[350px] overflow-y-auto",children:e.jsx("div",{className:"divide-y",children:x.map(S=>e.jsx(Sn,{export:S,onRemove:A},S.id))})})]})}function Ca({variant:t}){const s=i.useExportStore(d=>d.activeExports),n=i.useInProgressExportsCount(),r=s.size>0,a=Array.from(s.values()).some(d=>d.status==="completed"||d.status==="failed"),c=n>0?n>9?"9+":String(n):null,u=r;return e.jsxs(o.Popover,{children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs(o.Button,{variant:t??"ghost",size:"xs",className:"relative w-7 px-0 text-muted-foreground hover:text-foreground","aria-label":"Export notifications",children:[e.jsx(i.Bell,{className:"h-3.5 w-3.5"}),u&&e.jsx("span",{className:`absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground ${c?"-right-0.5 -top-0.5 h-3.5 min-w-3.5 px-0.5 text-[9px] font-semibold":"right-1 top-1 h-1.5 w-1.5"}`,children:c})]})}),e.jsx(o.PopoverContent,{className:"w-80 p-0",align:"end",sideOffset:8,children:e.jsx(kn,{})})]})}function Sa(t){if(t)return{renamed:t.type==="rename"?{oldId:t.oldId,newId:t.newId}:void 0,removedControlId:t.type==="remove"?t.controlId:void 0,cardBindingsById:t.type==="add"||t.type==="update"?t.cardBindingsById:void 0,affectedBindingControlIds:t.type==="add"||t.type==="update"?t.affectedBindingControlIds:void 0}}function Dn({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:a="manage"}){const l=a==="create",{forceClose:c,handleOpenChange:u,isCreateFlowActive:d,preventPassiveDismissDuringCreate:m,resolvedOpen:x,setIsCreateFlowActive:g}=me.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:a==="create",dismissMode:r?"passive":"explicit-only"}),f=o.useDashboardStore(F=>F.dashboard),{setDashboardControlsModel:b}=o.useDashboardActions(),{participants:A}=i.useDashboardStructuralParticipants(o.getDashboardCards(f)),S=Array.from(new Map(A.flatMap(F=>F.fieldChoices.map(U=>{var G;return[U.value,{option:U,target:(G=F.fieldTargetMap)==null?void 0:G[U.value]}]}))).values()),N=Array.from(new Map(A.flatMap(F=>F.metricChoices.map(U=>{var G;return[U.value,{option:U,target:(G=F.metricTargetMap)==null?void 0:G[U.value]}]}))).values()),j=o.collectDashboardControlIds({...f||{},controls:[]}),w=i.buildDashboardStructuralParticipantIdsByControlId(f),y=(F,U,G)=>{b(F,U,Sa(G))},C=h.useCallback(()=>{if(l){c();return}g(!1)},[l,c,g]),T=e.jsx(me.ControlDefinitionListEditor,{scope:"dashboard",controls:f.controls||[],reservedControlIds:j,defaultValues:f.defaultControlValues||{},usageByControlId:i.buildDashboardControlUsageById(f),availableFieldChoices:S,availableMetricChoices:N,structuralParticipants:A,structuralParticipantIdsByControlId:w,initialCreateFlow:a==="create",onCreateFlowActiveChange:g,onCreateFlowComplete:C,onChange:y,emptyMessage:"No dashboard controls yet."}),V=d?"Add dashboard control":"Dashboard Controls",D=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Dashboard Controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),T]});return r?e.jsxs(o.Popover,{open:x,onOpenChange:u,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:n||e.jsxs(o.Button,{variant:"outline",className:"h-7 px-2",size:"sm",children:[e.jsx(o.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Controls"]})}),e.jsx(o.PopoverContent,{className:"w-[620px] max-w-[95vw] space-y-4",align:"end",onEscapeKeyDown:m,onPointerDownOutside:m,children:D})]}):e.jsx(i.Dialog,{open:x,onOpenChange:u,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:m,onPointerDownOutside:m,children:[e.jsxs(i.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(i.DialogDescription,{className:d?"sr-only":"text-[13px]",children:d?"Configure and add a shared dashboard control.":"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:T})]})})}const ka=["enum","multi_enum","text","number","boolean","date"];function En({open:t,onOpenChange:s,initialMode:n="manage"}){var D;const r=n==="create",{forceClose:a,handleOpenChange:l,isCreateFlowActive:c,preventPassiveDismissDuringCreate:u,resolvedOpen:d,setIsCreateFlowActive:m}=me.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),x=o.useDashboardStore(F=>F.dashboard),g=o.useDashboardStore(F=>F.selectedSheetId),{setDashboardInputs:f}=o.useDashboardActions(),b=(D=x.sheets)==null?void 0:D.find(F=>F.id===g),A=(b==null?void 0:b.kind)==="document"&&!!b.document,S=h.useMemo(()=>A&&(b!=null&&b.document)?i.getDocumentSheetDashboardInputs(x,b.id):[],[x,A,b==null?void 0:b.document,b==null?void 0:b.id]),N=h.useMemo(()=>S.filter(F=>F.kind==="control"),[S]),j=h.useMemo(()=>N.map(F=>F.control),[N]),w=h.useMemo(()=>Ea(j),[j]),y=h.useMemo(()=>Da(x),[x]),C=h.useCallback(()=>{if(r){a();return}m(!1)},[r,a,m]),T=h.useCallback((F,U,G)=>{!A||!(b!=null&&b.document)||f(Ia({allInputs:x.inputs||[],documentSheetId:b.id,currentDocumentInputs:S,nextControls:F,nextDefaultValues:U,change:G}))},[x.inputs,S,A,b,f]);if(!A||!(b!=null&&b.document))return null;const V=c?"Add document control":"Document Controls";return e.jsx(i.Dialog,{open:d,onOpenChange:l,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs(i.DialogHeader,{className:c?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(i.DialogDescription,{className:c?"sr-only":"text-[13px]",children:c?"Configure and add a document-local control input.":"Add document-local control inputs. They are stored on this document sheet and are not dashboard controls."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:e.jsx(me.ControlDefinitionListEditor,{scope:"dashboard",controls:j,reservedControlIds:y,defaultValues:w,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:ka,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:C,onChange:T,emptyMessage:"No document controls yet."})})]})})}function Da(t){return(t.controls||[]).map(s=>s.id)}function Ea(t){const s={};for(const n of t)n.defaultValue!==void 0&&(s[n.id]=n.defaultValue);return s}function Aa(t,s){return s?Object.prototype.hasOwnProperty.call(s,t.id)?{...t,defaultValue:s[t.id]}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}}function Ia({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:a,change:l}){const c=new Map(r.map(f=>[f.id,Aa(f,a)])),u=(l==null?void 0:l.type)==="rename"?{oldId:l.oldId,newId:l.newId}:null,d=new Set,m=[];for(const f of n){if(f.kind!=="control"){m.push(f);continue}const b=c.get(f.control.id)||((u==null?void 0:u.oldId)===f.control.id?c.get(u.newId):void 0);if(!b)continue;d.add(b.id);const A=i.createUniqueDashboardInputVariableNameFromName(b.id,[...t,...m].filter(N=>N.id!==f.id)),S=b.id===A?b:{...b,id:A};m.push({...f,label:S.label,variableName:A,requiredAtExecution:S.requiredAtExecution,control:S})}for(const f of c.values())d.has(f.id)||m.push(i.createDashboardControlInputFromControl({control:f,existingInputs:[...t,...m],sheetId:s}));const x=new Set(n.map(f=>f.id));return[...t.filter(f=>!x.has(f.id)),...m]}function An({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:a="default",className:l,primaryButtonClassName:c,secondaryButtonClassName:u,pickerContentClassName:d,settingsContentClassName:m}){const x=a==="toolbar",[g,f]=h.useState(!1),b=i.useSurfaceAppearance("interactive");return e.jsxs("div",{className:o.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",x?"h-8":"h-7",l),children:[e.jsxs(o.Popover,{open:t,onOpenChange:s,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs(o.Button,{variant:"ghost",size:"xs",className:o.cn("h-full rounded-none border-0 bg-transparent pl-2.5 pr-2 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",c),children:[t?e.jsx(Yr,{className:"h-3.5 w-3.5"}):e.jsx(i.Filter,{className:"h-3.5 w-3.5"}),"Filter"]})}),e.jsx(o.PopoverContent,{align:"end",sideOffset:6,className:o.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",d),style:b.contentStyle,children:n})]}),e.jsxs(o.Popover,{open:g,onOpenChange:f,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsx(o.Button,{variant:"ghost",size:"xs",className:o.cn("h-full w-7 rounded-none border-0 border-l border-border/60 bg-transparent px-0 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",u),"aria-label":"Filter and control actions",children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsx(o.PopoverContent,{align:"end",sideOffset:6,className:o.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",m),style:b.contentStyle,children:r(()=>f(!1))})]})]})}function Ta(){me.useSyncLegacyEditorState();const t=o.useDashboardStore(d=>d.selectedSheetId),s=o.useDashboardStore(d=>d.selectedFrameId),n=o.useDashboardStore(d=>d.dashboard),r=o.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:a}=o.useDashboardActions(),{setCard:l}=o.useEditorActions(),c=o.useEditorStore(d=>d.card.dataSource);return h.useEffect(()=>{var m,x;let d=r();if(!d){const g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(b=>b.id===t),f=(x=g==null?void 0:g.frames)==null?void 0:x[0];f&&(a(f.id),d=f)}if(d){const g=d.cards.find(f=>f.id===d.activeCardId);g&&l(g)}},[r,t,s,n,a,l]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function La(){const t=o.useDashboardStore(d=>d.dashboard),s=o.useDashboardStore(d=>d.semanticExecutionPayload),n=o.useDashboardStore(d=>d.actions.addFilter),{hasEntities:r}=Ta(),{isLoading:a}=i.useFilterableFields(),l=h.useMemo(()=>i.getGlobalDateFilterCoverage(t,s),[t,s]),u=!i.getGlobalDateFilter(t.filters)&&l.hasEligibleCards&&!a;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[u&&e.jsx("div",{className:"border-b border-border/60 p-2",children:e.jsxs("button",{type:"button",onClick:()=>n(i.createDefaultGlobalDateFilter()),title:`Applies to ${l.eligibleCardCount} of ${l.totalCardCount} date-aware cards`,className:"flex w-full items-start gap-2 rounded-[4px] px-2 py-1.5 text-left outline-none transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-border",children:[e.jsx(i.CalendarRange,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"text-[12px] font-medium text-foreground",children:"Add global date filter"}),e.jsx("span",{className:"text-[11px] leading-[1.4] text-muted-foreground",children:"One date range across all date-aware cards."})]})]})}),!r&&e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(i.Database,{className:"mb-3 h-10 w-10 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-1 text-[13px] font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Configure a data source for this card to enable filtering."})]}),r&&e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx(i.FilterableFieldsPanel,{context:"filter"})})]})}const Qs=!1;function Fa({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const a=o.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:l}=o.useDashboardActions();a!=null&&a.displayMode;const c=(a==null?void 0:a.toolbarWrap)??!1;return a==null||a.showDownloadButton,e.jsxs("div",{className:"w-[300px]",children:[e.jsxs("div",{className:"p-1",children:[e.jsx(Vt,{icon:i.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(Vt,{icon:o.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(Vt,{icon:i.Pencil,label:"Manage controls",onClick:()=>{n(),r()}})]}),e.jsx("div",{className:"border-t border-border/60"}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Display"}),Qs,e.jsx(Ra,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:c,onCheckedChange:u=>l({toolbarWrap:u===!0})}),Qs]})]})}function Vt({icon:t,label:s,onClick:n}){return e.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left text-[13px] text-foreground transition-colors hover:bg-muted/40",children:[e.jsx(t,{className:"h-3.5 w-3.5 text-muted-foreground"}),s]})}function Ra({id:t,label:s,checked:n,onCheckedChange:r}){return e.jsxs("div",{className:"flex items-center gap-2 rounded-[4px] px-1 py-1 transition-colors hover:bg-muted/40",children:[e.jsx(i.Checkbox,{id:t,checked:n,onCheckedChange:r}),e.jsx(o.Label,{htmlFor:t,className:"cursor-pointer text-[12px] font-normal leading-[1.3]",children:s})]})}function Pa({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:a,settingsContentClassName:l}){var V;const[c,u]=h.useState(null),d=o.useDashboardStore(D=>D.dashboard),m=o.useDashboardStore(D=>D.selectedSheetId),x=o.useDashboardStore(D=>D.showFilters),g=i.useAssistantLayoutStore(D=>D.setPanelOpen),f=o.useDashboardStore(D=>D.actions),{setDocumentInspectorTab:b,setShowFilters:A}=f,S=(V=d.sheets)==null?void 0:V.find(D=>D.id===m),N=o.isDocumentSheet(S),j=h.useCallback(D=>{window.setTimeout(()=>{u(D)},0)},[]),w=h.useCallback(D=>{if(N&&m){D&&b(m,"inputs");return}D&&g("dashboard",!1),A(D)},[N,m,b,g,A]),y=h.useCallback(()=>{w(!0)},[w]),C=h.useCallback(()=>{j("create")},[j]),T=h.useCallback(()=>{j("manage")},[j]);return e.jsxs(e.Fragment,{children:[e.jsx(An,{showFilters:N?!1:x,onShowFiltersChange:w,pickerContent:e.jsx(La,{}),settingsContent:D=>e.jsx(Fa,{onAddFilter:y,onAddControl:C,onManageControls:T,onDismiss:D}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:a,settingsContentClassName:l}),c?N?e.jsx(En,{open:!0,onOpenChange:D=>{D||u(null)},initialMode:c}):e.jsx(Dn,{open:!0,onOpenChange:D=>{D||u(null)},showTrigger:!1,initialMode:c}):null]})}class xt extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function In(t,s){return`${t.replace(/\/$/,"")}${s}`}function xe(t){return encodeURIComponent(t)}function pt(t){const s=new URLSearchParams;Object.entries(t).forEach(([r,a])=>{a!==void 0&&a!==""&&s.set(r,String(a))});const n=s.toString();return n?`?${n}`:""}async function Ma(t){if((t.headers.get("content-type")??"").includes("application/json"))return t.json().catch(()=>({}));const n=await t.text().catch(()=>"");return n?{error:n}:{}}function Tn(t){if(!t||typeof t!="object")return null;const s=t;return typeof s.error=="string"?s.error:null}async function pe(t,s,n,r){const a=await fetch(In(t,n),{cache:(r==null?void 0:r.cache)??"no-store",...r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,...(r==null?void 0:r.headers)||{}}}),l=await a.json().catch(()=>({}));if(!a.ok)throw new xt(Tn(l)||"Briefings API request failed",a.status,l);return l}async function Ln(t,s,n,r){const a=await fetch(In(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!a.ok){const l=await Ma(a);throw new xt(Tn(l)||"Briefing artifact request failed",a.status,l)}return{kind:r,content:await a.text(),contentType:a.headers.get("content-type")??"text/plain",filename:Ba(a.headers.get("content-disposition"))}}function Ba(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function Fn(t,s,n){return pe(t,s,`/v1/briefings${pt({scope:n==null?void 0:n.scope,tenantId:n==null?void 0:n.tenantId,tenantUserId:n==null?void 0:n.tenantUserId,status:n==null?void 0:n.status,page:n==null?void 0:n.page,pageSize:n==null?void 0:n.pageSize,search:n==null?void 0:n.search})}`)}async function Va(t,s,n){return pe(t,s,`/v1/briefings/tenant-summaries${pt({status:n==null?void 0:n.status})}`)}async function as(t,s,n){return pe(t,s,`/v1/briefings/${xe(n)}`)}async function Rn(t,s,n){return pe(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function ft(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function os(t,s,n){return ft(t,s,n,{status:"PAUSED"})}async function is(t,s,n){return ft(t,s,n,{status:"ACTIVE"})}async function ls(t,s,n){return pe(t,s,`/v1/briefings/${xe(n)}`,{method:"DELETE"})}async function cs(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs`,{method:"POST",body:JSON.stringify(r)})}async function Pn(t,s,n){return pe(t,s,"/v1/briefings/preview-plan",{method:"POST",body:JSON.stringify({draft:n})})}async function Mn(t,s,n){return pe(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function Bn(t,s,n){return(await pe(t,s,`/v1/briefings/preview-runs/${xe(n)}`)).previewRun}async function Vn(t,s,n){return pe(t,s,`/v1/briefings/preview-runs/${xe(n)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Oa(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs${pt({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function ds(t,s,n,r){return(await pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`)).run}async function On(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Un(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`,{method:"DELETE"})}async function Ua(t,s,n,r,a){return Ln(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}/artifact${pt({kind:a})}`,a)}async function $a(t,s,n,r){return Ln(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}/evidence`,"evidence")}async function $n(t,s,n){var a;const r=await pe(t,s,"/v1/ai/generate",{method:"POST",body:JSON.stringify({type:"polish-text",context:{text:n}})});if(!r.success||!((a=r.result)!=null&&a.polished))throw new xt(r.error||"Polish returned no result",502,r);return r.result.polished}const _a={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},za={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function Ie(t){return ae(t)}function Js(t){switch(t.type){case"dashboard":return`${t.type}:${t.dashboardId}`;case"dashboard_sheet":case"document_sheet":return`${t.type}:${t.dashboardId}:${t.sheetId}`;case"visual":return`${t.type}:${t.dashboardId}:${t.visualId}`;case"card":return`${t.type}:${t.dashboardId}:${t.cardId}`}}function us(t){var s;if((s=t.title)!=null&&s.trim())return t.title.trim();switch(t.type){case"dashboard":return"Dashboard PDF";case"dashboard_sheet":return"Dashboard sheet PDF";case"document_sheet":return"Paginated report PDF";case"visual":return"Saved visual";case"card":return"Dashboard card"}}function qa(t){var s;switch(t.type){case"dashboard":return((s=t.settings)==null?void 0:s.sheetSelection)==="current"?"Current dashboard sheet":"All dashboard sheets";case"dashboard_sheet":return"Dashboard sheet";case"document_sheet":return"Paginated report";case"visual":return"Saved visual";case"card":return t.format==="csv"?"Card data CSV":"Card render"}}function _n(t){var s;switch(t.type){case"dashboard":case"dashboard_sheet":case"document_sheet":return["pdf"];case"visual":return["pdf","png"];case"card":{const n=(s=t.settings)==null?void 0:s.cardType;return Kn(n)}}}function Ha(t,s){return _n(t).includes(s)?{...Ie(t),format:s,settings:Hn(t.settings,s)}:Ie(t)}function Ka(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...Ie(t),settings:n}}function zn(t){var c,u;if(t.source.type!=="dashboard")return[];const s=t.source.dashboardId,n=t.dashboard,r=[{key:`dashboard:${s}:all`,kind:"dashboard",title:"Full dashboard PDF",detail:"All dashboard sheets",dashboardId:s,formats:["pdf"],defaultFormat:"pdf"}];if(!n)return r;const a=o.getDashboardSheets(n.sheets),l=a.find(d=>d.id===t.selectedSheetId)??a[0];l&&r.push({key:`dashboard_sheet:${s}:${l.id}`,kind:"dashboard_sheet",title:`${Ut(l)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:l.id,formats:["pdf"],defaultFormat:"pdf"});for(const d of n.sheets||[])o.isDocumentSheet(d)&&r.push({key:`document_sheet:${s}:${d.id}`,kind:"document_sheet",title:`${Ut(d)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:d.id,formats:["pdf"],defaultFormat:"pdf"});if(l)for(const d of Gn(l)){if(d.card.type==="text")continue;const m=Kn(d.card.type);r.push({key:`card:${s}:${d.card.id}`,kind:"card",title:d.card.title||"Untitled card",detail:`${Ut(l)} · ${d.card.type}`,dashboardId:s,sheetId:l.id,cardId:d.card.id,cardType:d.card.type,frameId:(c=d.frame)==null?void 0:c.id,cardControlDefinitions:d.card.controls,controlBindings:d.card.controlBindings,tablePreferences:(u=d.card.preferences)==null?void 0:u.tablePrefs,formats:m,defaultFormat:i.getDefaultExportFormat(d.card.type)})}return r}function Qt(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Ga({option:s,format:n,runtime:t.runtime});switch(s.kind){case"dashboard":return{type:"dashboard",dashboardId:s.dashboardId,format:"pdf",title:s.title,settings:r};case"dashboard_sheet":return{type:"dashboard_sheet",dashboardId:s.dashboardId,sheetId:Ot(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:Ot(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:Ot(s.cardId),format:n,title:s.title,settings:r}}}function Ys(t){const s=zn(t),n=s.find(l=>l.kind==="dashboard_sheet"),a=s.find(l=>l.kind==="dashboard")??n;return a?[Qt({option:a,runtime:t.runtime})]:[]}function Ga(t){const s={...Hn(void 0,t.format)},n=t.runtime;return n!=null&&n.theme&&(s.theme=n.theme),t.option.kind==="dashboard"&&(s.sheetSelection="all"),t.option.kind==="dashboard_sheet"&&(s.sheetSelection="current",s.currentSheetId=t.option.sheetId,s.currentSheetName=t.option.title.replace(/\sPDF$/,"")),t.option.kind==="document_sheet"&&(s.currentSheetId=t.option.sheetId,s.currentSheetName=t.option.title.replace(/\sPDF$/,"")),t.option.kind==="card"&&(s.selectedSheetId=t.option.sheetId,s.cardType=t.option.cardType,t.option.cardControlDefinitions&&(s.cardControlDefinitions=ae(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=ae(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=ae(t.option.tablePreferences))),Wa({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Za(s.filterValues)),s}function Wa(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Xa({settings:s,option:n,runtime:r});return}const a=n.kind==="dashboard"?"all":"current",l=n.kind==="dashboard"?r.selectedSheetId:n.sheetId,c=i.buildDashboardExecutionSnapshot({dashboard:r.dashboard||void 0,filterValues:r.filterValues,selectedSheetId:l,sheetSelection:a,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});s.sheetFilterValues=ae(c.filterValues),s.filterValues=ae(c.filterValues),s.controlValues=ae(c.controlValues),r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions));const u=Qa({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&a==="all"?void 0:l,sheetSelection:a});u&&(s.dashboardInputExecutionSnapshot=ae(u))}function Xa(t){var m,x,g;const{settings:s,option:n,runtime:r}=t,a=n.cardId,l=i.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=ae(l),!a){s.filterValues=ae(l),s.controlValues=ae(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions));return}const c=((m=r.inlineFilterValuesMap)==null?void 0:m[a])||[];c.length>0&&(s.inlineFilterValues=ae(c));const u=i.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:a,interactionStates:r.interactionStates||{},currentDashboardId:(x=r.dashboard)==null?void 0:x.id,semanticExecutionPayload:r.semanticExecutionPayload,filters:r.filters,filterValues:r.filterValues,inlineFilterValuesMap:{...r.inlineFilterValuesMap||{},[a]:c},dashboardControls:r.dashboardControls||r.controlDefinitions,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});u?(s.filterValues=ae(u.queryContext.cardFilterValues),s.controlValues=ae(u.queryContext.controlValues),s.controlDefinitions=ae(u.queryContext.controlDefinitions),s.cardControlDefinitions=ae(u.queryContext.cardControlDefinitions),s.controlBindings=ae(u.queryContext.controlBindings)):(s.filterValues=ae(l),s.controlValues={...r.controlValues||{},...((g=r.cardControlValuesMap)==null?void 0:g[a])||{}},r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions)));const d=Ja({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:c,controlValues:s.controlValues});d&&(s.dashboardInputExecutionSnapshot=ae(d))}function Qa(t){var u;const{option:s,runtime:n}=t,r=n.dashboard;if(!((u=r==null?void 0:r.inputs)!=null&&u.length))return;const a=new Date().toISOString(),l=qn();if(s.kind==="document_sheet"&&s.sheetId)return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:s.sheetId,sheetKind:"document",mode:"document",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:a,timezone:l}).snapshot;const c=t.sheetSelection==="all"?o.getDashboardSheets(r.sheets).map(d=>d.id):t.selectedSheetId?[t.selectedSheetId]:[];if(c.length!==0)return i.buildDashboardSheetsInputExecutionSnapshot({dashboard:r,sheetIds:c,sheetKind:"dashboard",mode:"dashboard",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:a,timezone:l}).snapshot}function Ja(t){var u;const{option:s,runtime:n}=t,r=n.dashboard;if(!((u=r==null?void 0:r.inputs)!=null&&u.length)||!s.cardId)return;const a=Ya(r,s.sheetId,s.cardId),l=t.inlineFilterValues!==void 0?{...n.inlineFilterValuesMap||{},[s.cardId]:t.inlineFilterValues}:n.inlineFilterValuesMap,c=t.filterValues!==void 0?i.applyFilterOverridesToDashboardInputSlots({dashboardInputValues:n.dashboardInputValues,dashboard:r,filterValues:t.filterValues,sheetId:(a==null?void 0:a.sheet.id)||s.sheetId,cardId:s.cardId,sheetKind:"dashboard"}):n.dashboardInputValues;return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:(a==null?void 0:a.sheet.id)||s.sheetId,card:(a==null?void 0:a.card)||null,sheetKind:"dashboard",mode:"visual",runtimeValues:{dashboardInputValues:c,filterValues:t.filterValues??n.filterValues,controlValues:t.controlValues??n.controlValues,inlineFilterValuesMap:l,cardControlValuesMap:n.cardControlValuesMap},generatedAt:new Date().toISOString(),timezone:qn()}).snapshot}function Ya(t,s,n){const r=t.sheets||[],a=s?r.filter(l=>l.id===s):r;for(const l of a)for(const c of Gn(l))if(c.card.id===n)return{sheet:l,card:c.card}}function qn(){return typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Za(t){if(!Array.isArray(t))return"";const s=t.filter(n=>!!n&&typeof n=="object"&&typeof n.name=="string");return i.formatFilterLine(s)}function Hn(t,s){return s==="csv"?{...za,...t}:{..._a,...t}}function Kn(t){return t?i.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function Gn(t){const s=[],n=new Set,r=(a,l)=>{!(a!=null&&a.id)||n.has(a.id)||(n.add(a.id),s.push({card:a,frame:l}))};for(const a of t.cards||[])r(a);for(const a of t.frames||[])for(const l of a.cards||[])r(l,a);return s}function Ot(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function Ut(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function ae(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Wn=["markdown"],eo={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Wn],includeEvidence:!0,includeSql:!0},schedule:{enabled:!1,scheduleExpr:"",timezone:"UTC",status:"ACTIVE"},delivery:{enabled:!1,recipients:[],channels:[],subject:"",message:""},limits:{}};function Xn(t){const s=t.trim();return s.length>0?s:void 0}function to(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ie),output:{...t.output,artifactFormats:[...t.output.artifactFormats]},schedule:{...t.schedule},delivery:{...t.delivery,recipients:t.delivery.recipients.map(s=>({...s})),channels:[...t.delivery.channels],channelConfigs:t.delivery.channelConfigs?{...t.delivery.channelConfigs}:void 0},limits:{...t.limits}}}function so(t){return t.type==="generated_analysis"?t.instruction:t.type==="custom_message"?t.message:""}function Qn(t,s){return t.type==="custom_message"?{type:"custom_message",message:s}:t.type==="none"?{type:"none"}:{type:"generated_analysis",instruction:s}}function ms(t){return Qn(t.body,t.instruction.trim())}function Jn(t){return{artifactFormats:[...t.artifactFormats],includeEvidence:t.includeEvidence,includeSql:t.includeSql,...t.audience?{audience:t.audience}:{},...t.tone?{tone:t.tone}:{},...t.format?{format:t.format}:{}}}function Yn(t){const s={};return t.maxToolCalls!==void 0&&(s.maxToolCalls=t.maxToolCalls),t.maxRows!==void 0&&(s.maxRows=t.maxRows),t.timeoutMs!==void 0&&(s.timeoutMs=t.timeoutMs),Object.keys(s).length>0?s:void 0}function Zn(t,s){if(!t)return;const n=s.reduce((r,a)=>(t[a]!==void 0&&(r[a]=t[a]),r),{});return Object.keys(n).length>0?n:void 0}function er(t){return t.recipients.length===0&&t.channels.length===0?null:{recipients:t.recipients.map(s=>({...s})),channels:[...t.channels],channelConfigs:Zn(t.channelConfigs,t.channels)}}function no(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Wn],includeEvidence:(t==null?void 0:t.includeEvidence)??!0,includeSql:(t==null?void 0:t.includeSql)??!0,audience:t==null?void 0:t.audience,tone:t==null?void 0:t.tone,format:t==null?void 0:t.format}}function ro(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function ao(t){return{enabled:!0,recipients:(t==null?void 0:t.recipients.map(s=>({...s})))??[],channels:t!=null&&t.channels?[...t.channels]:[],subject:"",message:"",channelConfigs:Zn(t==null?void 0:t.channelConfigs,(t==null?void 0:t.channels)??[])}}function oo(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function io(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function $t(t,s,n,r,a){oo(n,r,a)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${a}`})}function tr(t){return lt(eo,t??{})}function lt(t,s){var c,u,d,m;const n=s.instruction??(s.body?so(s.body):t.instruction),r=Qn(s.body?{...s.body}:{...t.body},n),a=(c=s.delivery)!=null&&c.channels?[...s.delivery.channels]:[...t.delivery.channels],l=((u=s.delivery)==null?void 0:u.channelConfigs)??t.delivery.channelConfigs;return{...to(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(Ie):t.attachments.map(Ie),output:{...t.output,...s.output,artifactFormats:(d=s.output)!=null&&d.artifactFormats?[...s.output.artifactFormats]:[...t.output.artifactFormats]},schedule:{...t.schedule,...s.schedule},delivery:{...t.delivery,...s.delivery,recipients:(m=s.delivery)!=null&&m.recipients?s.delivery.recipients.map(x=>({...x})):t.delivery.recipients.map(x=>({...x})),channels:a,channelConfigs:l},limits:{...t.limits,...s.limits}}}function He(t){return{name:t.name,description:t.description??"",instruction:ro(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ie),output:no(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:ao(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function Jt(t){return{name:t.name.trim(),description:Xn(t.description)??null,status:t.schedule.status,scheduleExpr:t.schedule.enabled?t.schedule.scheduleExpr.trim():null,timezone:t.schedule.timezone.trim()||"UTC",source:{...t.source},body:ms(t),attachments:t.attachments.map(Ie),presentation:Jn(t.output),limits:Yn(t.limits),deliveryConfig:er(t.delivery)}}function sr(t){return{name:t.name.trim(),description:Xn(t.description)??null,status:t.schedule.status,scheduleExpr:t.schedule.enabled?t.schedule.scheduleExpr.trim():null,timezone:t.schedule.timezone.trim()||"UTC",source:{...t.source},body:ms(t),attachments:t.attachments.map(Ie),presentation:Jn(t.output),limits:Yn(t.limits),deliveryConfig:er(t.delivery)}}function Yt(t){var r,a,l,c,u;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=ms(t);if(n.type!=="none"&&!t.instruction.trim()&&s.push({field:"instruction",message:"Instruction is required"}),n.type==="none"&&t.attachments.length===0&&s.push({field:"body",message:"Add briefing instructions, a custom message, or at least one attachment."}),t.source.type==="dashboard"&&!t.source.dashboardId.trim()&&s.push({field:"source.dashboardId",message:"Dashboard source requires a dashboard id"}),t.output.artifactFormats.length===0&&s.push({field:"output.artifactFormats",message:"Choose at least one output format"}),t.schedule.timezone.trim()||s.push({field:"schedule.timezone",message:"Timezone is required"}),t.schedule.enabled&&!t.schedule.scheduleExpr.trim()&&s.push({field:"schedule.scheduleExpr",message:"Schedule expression is required when scheduling is enabled"}),t.delivery.recipients.length>0||t.delivery.channels.length>0){if((t.delivery.channels.length===0||t.delivery.channels.some(m=>m!=="SLACK"))&&t.delivery.recipients.length===0&&s.push({field:"delivery.recipients",message:"Add at least one recipient or remove delivery channels"}),t.delivery.channels.length===0&&s.push({field:"delivery.channels",message:"Choose at least one delivery channel or remove recipients"}),t.delivery.recipients.forEach((m,x)=>{m.type==="email"&&!io(m.address)&&s.push({field:`delivery.recipients.${x}.address`,message:"Email recipient address is invalid"})}),t.delivery.channels.includes("WEBHOOK")){const m=(r=t.delivery.channelConfigs)==null?void 0:r.WEBHOOK;(l=(a=m==null?void 0:m.webhookConfig)==null?void 0:a.url)!=null&&l.trim()||s.push({field:"delivery.channelConfigs.WEBHOOK.webhookConfig.url",message:"Webhook URL is required for webhook delivery"})}if(t.delivery.channels.includes("SLACK")){const m=(u=(c=t.delivery.channelConfigs)==null?void 0:c.SLACK)==null?void 0:u.slackConfig;((m==null?void 0:m.destination.type)!=="channel"||!m.destination.channelId.trim())&&s.push({field:"delivery.channelConfigs.SLACK.slackConfig.destination.channelId",message:"Choose a Slack channel"})}}return $t(s,"maxToolCalls",t.limits.maxToolCalls,1,100),$t(s,"maxRows",t.limits.maxRows,1,1e5),$t(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const tt="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function lo({attachment:t,open:s,onOpenChange:n,onChange:r,children:a}){const l=_n(t),c=t.settings||{},u=t.format==="csv",d=m=>{r(Ka(t,m))};return e.jsxs(o.Popover,{open:s,onOpenChange:n,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:a}),e.jsxs(o.PopoverContent,{align:"start",className:"z-[60] w-[320px] space-y-3 p-3",onOpenAutoFocus:m=>m.preventDefault(),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:o.cn(tt,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:us(t)})]}),l.length>1?e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Format"}),e.jsxs(o.Select,{value:t.format,onValueChange:m=>r(Ha(t,m)),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsx(o.SelectContent,{children:l.map(m=>e.jsx(o.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(uo,{settings:c,onChange:d}):e.jsx(co,{settings:c,onChange:d})]})]})}function co({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Page size"}),e.jsxs(o.Select,{value:t.pageSize||"letter",onValueChange:n=>s({pageSize:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:"letter",children:"Letter"}),e.jsx(o.SelectItem,{value:"legal",children:"Legal"}),e.jsx(o.SelectItem,{value:"a4",children:"A4"}),e.jsx(o.SelectItem,{value:"a3",children:"A3"}),e.jsx(o.SelectItem,{value:"tabloid",children:"Tabloid"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Orientation"}),e.jsxs(o.Select,{value:t.orientation||"portrait",onValueChange:n=>s({orientation:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:"portrait",children:"Portrait"}),e.jsx(o.SelectItem,{value:"landscape",children:"Landscape"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(ct,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(ct,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function uo({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Delimiter"}),e.jsxs(o.Select,{value:t.delimiter||",",onValueChange:n=>s({delimiter:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:",",children:"Comma"}),e.jsx(o.SelectItem,{value:";",children:"Semicolon"}),e.jsx(o.SelectItem,{value:" ",children:"Tab"})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(ct,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(ct,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function ct({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-foreground/80",children:[e.jsx(i.Checkbox,{checked:s,onCheckedChange:r=>n(r===!0)}),e.jsx("span",{children:t})]})}function mo({attachments:t,onChange:s,onAdd:n,disabled:r}){const a=t.length===0;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{type:"button",disabled:r,onClick:n,"aria-label":a?"Attach files":"Add another attachment",className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Paperclip,{className:"h-3 w-3"}),a?"Attach":null]}),t.map((l,c)=>e.jsx(ho,{attachment:l,disabled:r,onUpdate:u=>{const d=[...t];d[c]=u,s(d)},onRemove:()=>s(t.filter((u,d)=>d!==c))},`${l.type}:${c}:${us(l)}`)),a?null:e.jsxs("button",{type:"button",disabled:r,onClick:n,className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"Add"]})]})}function ho({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[a,l]=h.useState(!1),c=us(t),u=qa(t),d=t.format.toUpperCase();return e.jsxs("span",{className:o.cn("group inline-flex h-6 items-center gap-1 rounded-control border border-border bg-background pl-1.5 pr-0.5 text-[11px] text-foreground/80",a&&"border-ring "),title:u?`${c} · ${u}`:c,children:[e.jsx(lo,{attachment:t,open:a,onOpenChange:l,onChange:n,children:e.jsxs("button",{type:"button",disabled:s,className:"inline-flex max-w-[180px] items-center gap-1 disabled:opacity-50",children:[e.jsx(xo,{format:t.format,className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate font-medium text-foreground",children:c}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground/70",children:d})]})}),e.jsx("button",{type:"button",disabled:s,onClick:r,className:"inline-flex h-4 w-4 items-center justify-center rounded-control text-muted-foreground/70 hover:bg-muted hover:text-foreground/80 disabled:opacity-50","aria-label":`Remove ${c}`,children:e.jsx(K.X,{className:"h-2.5 w-2.5"})})]})}function xo({format:t,className:s}){const n=t==="csv"?i.FileSpreadsheet:i.FileText;return e.jsx(n,{className:o.cn(s)})}const po="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function fo({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:a,runtime:l,selectedAttachments:c,onSubmit:u}){const d=h.useMemo(()=>zn({source:n,dashboard:r,selectedSheetId:a}),[n,r,a]),[m,x]=h.useState([]);h.useEffect(()=>{if(!t)return;const T=[];for(const V of c){const D=Js(V),F=d.find(U=>U.formats.some(G=>{const B=Qt({option:U,format:G,runtime:l});return Js(B)===D}));F&&T.push({optionKey:F.key,format:V.format??F.defaultFormat})}x(T)},[t,d,c,l]);const g=h.useMemo(()=>new Set(m.map(T=>T.optionKey)),[m]),f=h.useMemo(()=>{const T={};for(const V of m)T[V.optionKey]=V.format;return T},[m]),b=(T,V)=>{x(D=>D.some(U=>U.optionKey===T)?D.filter(U=>U.optionKey!==T):[...D,{optionKey:T,format:V}])},A=(T,V)=>{x(D=>D.map(F=>F.optionKey===T?{...F,format:V}:F))},S=()=>{const T=[];for(const V of m){const D=d.find(F=>F.key===V.optionKey);D&&T.push(Qt({option:D,format:V.format,runtime:l}))}u(T),s(!1)},N=()=>s(!1),j=h.useMemo(()=>d.filter(T=>T.kind==="dashboard"||T.kind==="dashboard_sheet"),[d]),w=h.useMemo(()=>d.filter(T=>T.kind==="document_sheet"),[d]),y=h.useMemo(()=>d.filter(T=>T.kind==="card"),[d]),C=m.length;return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"flex max-h-[80vh] w-[min(560px,calc(100vw-32px))] max-w-none flex-col gap-0 rounded-card p-0",showCloseButton:!0,children:[e.jsxs(i.DialogHeader,{className:"border-b border-border px-4 py-3 text-left",children:[e.jsx(i.DialogTitle,{className:"text-[14px] font-semibold leading-5",children:"Add attachments"}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Choose what gets sent with this briefing."})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:n.type!=="dashboard"?e.jsx("div",{className:"rounded-card border border-dashed border-border px-3 py-3 text-[12px] leading-[1.55] text-muted-foreground",children:"Attachments are available when authoring from a dashboard."}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{label:"Dashboard",options:j,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A}),e.jsx(_t,{label:"Paginated reports",options:w,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A,emptyText:"No paginated report sheets are available."}),e.jsx(_t,{label:"Current sheet cards",options:y,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A,emptyText:"No exportable cards are available on the current dashboard sheet."})]})}),e.jsxs(i.DialogFooter,{className:"flex flex-row items-center justify-between gap-2 border-t border-border px-4 py-3 sm:justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:C===0?"Nothing selected":`${C} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(o.Button,{type:"button",variant:"outline",size:"xs",onClick:N,children:"Cancel"}),e.jsx(o.Button,{type:"button",size:"xs",onClick:S,disabled:n.type!=="dashboard",children:C>0?`Add ${C} ${C===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function _t({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:a,onFormatChange:l,emptyText:c}){return e.jsxs("section",{children:[e.jsx("div",{className:o.cn(po,"mb-2"),children:t}),s.length===0?e.jsx("div",{className:"rounded-card border border-dashed border-border px-3 py-2 text-[12px] text-muted-foreground",children:c||"Nothing available."}):e.jsx("div",{className:"divide-y divide-border rounded-card border border-border",children:s.map(u=>{const d=n.has(u.key),m=r[u.key]??u.defaultFormat;return e.jsxs("div",{className:o.cn("flex w-full items-start gap-2 px-3 py-2 transition-colors hover:bg-muted "),children:[e.jsxs("button",{type:"button",role:"checkbox","aria-checked":d,onClick:()=>a(u.key,u.defaultFormat),className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[e.jsx(go,{selected:d}),e.jsx(bo,{kind:u.kind,format:m,cardType:u.cardType,className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:u.title}),e.jsx("span",{className:"mt-0.5 block truncate text-[11px] text-muted-foreground",children:u.detail})]})]}),e.jsx("div",{className:"shrink-0",children:u.formats.length>1?e.jsxs(o.Select,{value:m,onValueChange:x=>l(u.key,x),children:[e.jsx(o.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:x=>x.stopPropagation(),children:e.jsx(o.SelectValue,{})}),e.jsx(o.SelectContent,{children:u.formats.map(x=>e.jsx(o.SelectItem,{value:x,children:x.toUpperCase()},x))})]}):e.jsx("span",{className:"inline-flex h-6 items-center text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:m})})]},u.key)})})]})}function go({selected:t}){return e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-0.5 flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control border transition-colors",t?"border-primary bg-primary":"border-border "),children:t?e.jsx(o.Check,{className:"h-2.5 w-2.5 text-primary-foreground",strokeWidth:3}):null})}function bo({kind:t,format:s,cardType:n,className:r}){const a=s==="csv"?i.FileSpreadsheet:t==="dashboard"?i.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?me.Rows3:o.ChartColumn:i.FileText;return e.jsx(a,{className:r})}const jo=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,yo=250;function Ye(t){switch(t.type){case"email":return`email:${t.address.toLowerCase()}`;case"user":return`user:${t.userId}`;case"tenant_user":return`tenant_user:${t.tenantUserId}`;case"group":return`group:${t.groupId}`}}function vo(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function No(t){return t.type==="group"?t.groupId:null}function Ze(t){return(t==null?void 0:t.trim().toLowerCase())||null}function Zs(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function en(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function tn({value:t,onChange:s,className:n,disabled:r=!1,prefix:a,placeholder:l}){const c=h.useRef(null),[u,d]=h.useState(!1),[m,x]=h.useState(""),[g,f]=h.useState(0),[b,A]=h.useState(()=>new Map),[S,N]=h.useState(()=>new Map),[j,w]=h.useState("people"),y=i.useDebounce(m,yo),{currentUser:C}=i.useCurrentUserInfo(),T=(C==null?void 0:C.type)==="tenant",{users:V,isLoading:D}=i.useUnifiedUsers({search:y,active:!0,type:T?"tenant":"all",tenantId:T?C.tenantId:void 0,limit:25}),{groups:F,isLoading:U}=i.useGroups({search:y,type:T?"TENANT_GROUP":"all",tenantId:T?C.tenantId:void 0,limit:25}),G=h.useMemo(()=>new Set(t.map(Ye)),[t]),B=h.useMemo(()=>new Set(t.map(vo).filter(I=>!!I)),[t]),_=h.useMemo(()=>new Set(t.map(No).filter(I=>!!I)),[t]),$=h.useMemo(()=>{const I=new Map(b);return V.forEach(P=>{I.set(P.id,Zs(P))}),C!=null&&C.id&&I.set(C.id,{kind:"user",id:C.id,name:C.name||C.email||"User",email:C.email||"",type:C.type}),I},[b,V,C]),M=h.useMemo(()=>{const I=new Set;return t.forEach(P=>{var H;if(P.type==="email"){const te=Ze(P.address);te&&I.add(te);return}if(P.type==="group")return;const fe=P.type==="tenant_user"?P.tenantUserId:P.userId,E=Ze((H=$.get(fe))==null?void 0:H.email);E&&I.add(E)}),I},[$,t]),Q=h.useMemo(()=>{const I=new Map(S);return F.forEach(P=>{I.set(P.id,en(P))}),I},[S,F]),ee=h.useMemo(()=>V.filter(I=>{if(B.has(I.id))return!1;const P=Ze(I.email);return P&&M.has(P)?!1:T?I.type==="tenant"&&I.tenantId===(C==null?void 0:C.tenantId):!0}).map(Zs),[V,B,M,T,C==null?void 0:C.tenantId]),L=h.useMemo(()=>ee.filter(I=>I.type==="organization"),[ee]),W=h.useMemo(()=>ee.filter(I=>I.type==="tenant"),[ee]),k=h.useMemo(()=>F.filter(I=>_.has(I.id)?!1:(C==null?void 0:C.type)==="tenant"?I.type==="TENANT_GROUP"&&I.tenantId===C.tenantId:!0).map(en),[F,_,C==null?void 0:C.type,C==null?void 0:C.tenantId]),oe=h.useMemo(()=>T?[{key:"people",label:"People",count:W.length},{key:"groups",label:"Groups",count:k.length}]:[{key:"people",label:"People",count:L.length},{key:"tenant_users",label:"Tenant users",count:W.length},{key:"groups",label:"Groups",count:k.length}],[k.length,T,L.length,W.length]),Y=h.useMemo(()=>j==="groups"?[]:j==="tenant_users"||T?W:L,[j,T,L,W]),X=h.useMemo(()=>j==="groups"?k:[],[j,k]),he=h.useMemo(()=>[...Y,...X],[Y,X]),ye=he.length===0?0:Math.min(g,he.length-1),ie=m.trim(),z=jo.test(ie),Pe=Ze(ie),ve=Pe?M.has(Pe):!1,ke=D||U,Se=I=>{G.has(Ye(I))||(s([...t,I]),x(""),f(0))},q=I=>{s(t.filter(P=>Ye(P)!==I))},Ne=()=>{!z||ve||Se({type:"email",address:ie})},O=I=>{const P=Ze(I.email);P&&M.has(P)||(A(fe=>{const E=new Map(fe);return E.set(I.id,I),E}),Se(I.type==="tenant"?{type:"tenant_user",tenantUserId:I.id}:{type:"user",userId:I.id}))},ne=I=>{N(P=>{const fe=new Map(P);return fe.set(I.id,I),fe}),Se({type:"group",groupId:I.id})},qe=I=>{if(I.key==="Enter"){if(I.preventDefault(),z&&!ve){Ne();return}const P=he[ye];if((P==null?void 0:P.kind)==="user"){O(P);return}if((P==null?void 0:P.kind)==="group"){ne(P);return}}else if(I.key==="ArrowDown")I.preventDefault(),f(P=>Math.min(P+1,Math.max(he.length-1,0)));else if(I.key==="ArrowUp")I.preventDefault(),f(P=>Math.max(P-1,0));else if(I.key==="Escape")d(!1);else if(I.key==="Backspace"&&m.length===0){const P=t[t.length-1];P&&q(Ye(P))}},Oe=t.map(I=>{const P=Ye(I);if(I.type==="email")return{key:P,label:I.name||I.address,icon:e.jsx(i.AtSign,{className:"h-3 w-3"}),onRemove:()=>q(P)};if(I.type==="group"){const H=Q.get(I.groupId);return{key:P,label:(H==null?void 0:H.name)||"Group",icon:e.jsx(ns,{className:"h-3 w-3"}),onRemove:()=>q(P)}}const fe=I.type==="tenant_user"?I.tenantUserId:I.userId,E=$.get(fe);return{key:P,label:(E==null?void 0:E.name)||(E==null?void 0:E.email)||"User",icon:e.jsx(i.User,{className:"h-3 w-3"}),onRemove:()=>q(P)}});return e.jsx("div",{className:o.cn("relative",n),children:e.jsxs(o.Popover,{open:u&&!r,onOpenChange:d,children:[e.jsx(o.Anchor2,{asChild:!0,children:e.jsxs("div",{className:o.cn("flex min-h-9 cursor-text flex-wrap items-center gap-1.5 rounded-control border bg-background px-2 py-1.5 transition-colors",u?"border-ring ring-2 ring-ring/10":"border-border hover:border-border",r&&"cursor-not-allowed opacity-60"),onClick:()=>{var I;r||((I=c.current)==null||I.focus(),d(!0))},children:[a?e.jsx("span",{className:"inline-flex shrink-0 items-center text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:a}):null,Oe.map(I=>e.jsx(wo,{icon:I.icon,label:I.label,onRemove:I.onRemove},I.key)),e.jsx("input",{ref:c,className:"h-6 min-w-[160px] flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground/70 disabled:cursor-not-allowed",value:m,disabled:r,placeholder:l??(t.length>0?"Add more...":"Add people, emails, or groups"),onChange:I=>{x(I.target.value),f(0),d(!0)},onFocus:()=>d(!0),onKeyDown:qe})]})}),e.jsx(o.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:I=>I.preventDefault(),className:o.cn("z-[60] w-[var(--radix-popover-trigger-width)] min-w-[360px] rounded-card border border-border bg-background p-0 text-foreground shadow-md outline-none","max-h-[min(320px,var(--radix-popover-content-available-height))] overflow-y-auto"),children:e.jsx(Co,{activeIndex:ye,activeFilter:j,emailAlreadyAdded:ve,filters:oe,groupSuggestions:X,loading:ke,onAddEmail:Ne,onFilterChange:I=>{w(I),f(0)},onGroupClick:ne,onUserClick:O,orderedSuggestions:he,query:ie,queryIsEmail:z,userSuggestions:Y,viewerType:C==null?void 0:C.type})})]})})}function wo({icon:t,label:s,onRemove:n}){return e.jsxs("span",{className:"inline-flex h-6 max-w-full items-center gap-1.5 rounded-control border border-border bg-muted pl-1.5 pr-1 text-[12px]",children:[e.jsx("span",{className:"shrink-0 text-muted-foreground",children:t}),e.jsx("span",{className:"min-w-0 truncate text-foreground",children:s}),e.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),n()},className:"rounded-control p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Remove ${s}`,children:e.jsx(K.X,{className:"h-2.5 w-2.5"})})]})}function Co({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:a,loading:l,onAddEmail:c,onFilterChange:u,onGroupClick:d,onUserClick:m,orderedSuggestions:x,query:g,queryIsEmail:f,userSuggestions:b,viewerType:A}){const S=!l&&x.length===0&&!(f&&!n);return e.jsxs("div",{className:"py-1 text-[13px]",children:[e.jsx("div",{className:"flex items-center gap-1 border-b border-border/60 px-2 pb-1",children:r.map(N=>e.jsxs("button",{type:"button",onClick:()=>u(N.key),className:o.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===N.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:N.label}),e.jsx("span",{className:o.cn("tabular-nums",s===N.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:N.count})]},N.key))}),l?e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-[12px] text-muted-foreground",children:[e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Searching"]}):null,b.length>0?e.jsx(sn,{heading:"People",children:b.map(N=>{var w;const j=x.indexOf(N);return e.jsx(nn,{active:j===t,avatar:e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground/80",children:(w=(N.name||N.email||"?")[0])==null?void 0:w.toUpperCase()}),detail:N.name?N.email:void 0,tag:N.type==="organization"?"Org user":"Tenant user",viewerType:A,title:N.name||N.email,onClick:()=>m(N)},N.id)})}):null,a.length>0?e.jsx(sn,{heading:"Groups",children:a.map(N=>{const j=x.indexOf(N);return e.jsx(nn,{active:j===t,avatar:e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-control border border-border bg-muted text-muted-foreground",children:e.jsx(ns,{className:"h-3 w-3"})}),detail:N.memberCount!==void 0?`${N.memberCount} member${N.memberCount===1?"":"s"}`:N.description??void 0,tag:N.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:A,title:N.name,onClick:()=>d(N)},N.id)})}):null,f&&!n?e.jsx("div",{className:"border-t border-border px-1.5 py-1.5",children:e.jsxs("button",{type:"button",onClick:c,className:"flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left hover:bg-muted",children:[e.jsx(yn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13px] text-foreground",children:["Send to ",e.jsx("span",{className:"font-medium",children:g})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Add as external email"})]}),e.jsx("span",{className:"ml-auto shrink-0 rounded-control border border-border bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"Enter"})]})}):null,S?e.jsx("div",{className:"px-2.5 py-6 text-center text-[12px] text-muted-foreground",children:g?"No people or groups match. Enter a valid email to add an external recipient.":"Pick a category above or type to search people, groups, or external emails."}):null]})}function sn({heading:t,children:s}){return e.jsxs("div",{className:"px-1.5 pb-1",children:[e.jsx("div",{className:"px-1.5 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t}),s]})}function nn({active:t,avatar:s,detail:n,onClick:r,tag:a,title:l,viewerType:c}){return e.jsxs("button",{type:"button",onClick:r,className:o.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left",t?"bg-muted ":"hover:bg-muted "),children:[s,e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[13px] text-foreground",children:l}),n?e.jsx("span",{className:"block truncate text-[11px] text-muted-foreground",children:n}):null]}),c==="organization"?e.jsx("span",{className:"shrink-0 rounded-control border border-border bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground",children:a}):null]})}function dt(t){return t==="SUCCESS"||t==="FAILED"}function ut(t){return t==="QUEUED"||t==="RUNNING"}function Zt({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}){const[m,x]=h.useState(null),[g,f]=h.useState("idle"),b=h.useRef(null),A=h.useRef({fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d});h.useEffect(()=>{A.current={fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}},[a,u,l,c,d]);const S=h.useCallback(()=>{x(null),f("idle")},[]),N=h.useCallback(()=>{b.current=null},[]),j=h.useCallback(y=>{var C,T;if(A.current.onRun(y),dt(y.status)){b.current=y.id,x(null),f("terminal"),(T=(C=A.current).onTerminalRun)==null||T.call(C,y);return}if(ut(y.status)){b.current=null,x(y.id),f("polling");return}x(null),f("idle")},[]),w=h.useCallback(y=>{b.current!==y&&(x(y),f("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(b.current===m){x(null),f("terminal");return}let y=!1,C=!1,T=null;const V=Date.now(),D=async()=>{var F,U,G,B,_,$;if(!(y||C)){if(Date.now()-V>r){x(M=>M===m?null:M),f("timed_out"),(U=(F=A.current).onTimeout)==null||U.call(F,m);return}C=!0;try{const M=await A.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(y)return;if(A.current.onRun(M),dt(M.status)){b.current=M.id,x(Q=>Q===M.id?null:Q),f("terminal"),(B=(G=A.current).onTerminalRun)==null||B.call(G,M);return}if(!ut(M.status)){x(Q=>Q===M.id?null:Q),f("idle");return}T=window.setTimeout(D,n)}catch(M){y||(f("error"),($=(_=A.current).onError)==null||$.call(_,M))}finally{C=!1}}};return f("polling"),D(),()=>{y=!0,T&&window.clearTimeout(T)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&g==="polling",resetTerminalRun:N,startRun:j,startRunId:w,status:g,stop:S}}function rn({label:t,description:s,checked:n,onSelect:r,name:a}){return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[e.jsx("input",{type:"radio",name:a,checked:n,onChange:r,className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-0.5 inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border",n?"border-primary":"border-border"),children:n?e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}):null}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] text-foreground",children:t}),e.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:s})]})]})}function So({includeEvidence:t,includeSql:s,includeHtml:n,onChange:r}){const a=[t,s,n].filter(Boolean).length;return e.jsxs(o.Popover,{children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Output options",children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"Output options",e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",a,"/3"]}),e.jsx(K.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(o.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-[320px] rounded-card border-border bg-popover p-0 text-popover-foreground",children:[e.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output options"}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:"Choose what gets included in the rendered briefing."})]}),e.jsxs("div",{className:"space-y-2.5 px-3 py-2.5",children:[e.jsx(zt,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:l=>r("evidence",l)}),e.jsx(zt,{label:"Include SQL in evidence",description:"Show the SQL the briefing ran. Useful for debugging or for a technical audience.",checked:s,onChange:l=>r("sql",l)}),e.jsx(zt,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:l=>r("html",l)})]})]})]})}function zt({label:t,description:s,checked:n,onChange:r}){return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:a=>r(a.target.checked),className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-[2px] flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control border",n?"border-primary bg-primary":"border-border"),children:n?e.jsx(o.Check,{className:"h-2 w-2 text-primary-foreground",strokeWidth:3.5}):null}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:t}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:s})]})]})}const es=`Tell me what changed in the business and what is driving it.
|
|
61
|
+
*/const Xt=K.createLucideIcon("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);function ta(){return e.jsx("div",{className:"space-y-1.5 py-1",children:[...Array(5)].map((t,s)=>e.jsxs("div",{className:"flex animate-pulse items-start gap-3 rounded-xl border border-transparent px-2.5 py-2.5",children:[e.jsx("div",{className:"mt-0.5 h-4 w-4 flex-shrink-0 rounded bg-muted/60"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/5 rounded bg-muted/60"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted/40"})]})]},s))})}function sa({open:t,onOpenChange:s,onSubmit:n,isCreating:r}){const[a,l]=h.useState(""),[c,u]=h.useState("");h.useEffect(()=>{t||(l(""),u(""))},[t]);const d=()=>{a.trim()&&n({title:a,description:c})},m=x=>{s(x)};return e.jsx(i.Dialog,{open:t,onOpenChange:m,children:e.jsxs(i.DialogContent,{showCloseButton:!1,className:"flex max-w-lg grid-cols-none flex-col gap-0 overflow-hidden rounded-[6px] border-border/60 p-0 shadow-lg",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ss.LayoutGrid,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(i.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"New library visual"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Visual"})]})]}),e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>m(!1),"aria-label":"Close",disabled:r,children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-3 px-4 py-3",children:[e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create a saved visual that can be reused across dashboards."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(o.Label,{htmlFor:"visual-title",className:"text-[12px]",children:"Name"}),e.jsx(o.Input,{id:"visual-title",size:"sm",placeholder:"Untitled visual",value:a,onChange:x=>l(x.target.value),disabled:r,onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),d())}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(o.Label,{htmlFor:"visual-description",className:"text-[12px]",children:"Description"}),e.jsx(o.Input,{id:"visual-description",size:"sm",placeholder:"Optional",value:c,onChange:x=>u(x.target.value),disabled:r})]})]}),e.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t border-border/60 px-4 py-2.5",children:[e.jsx(o.Button,{size:"xs",variant:"outline",onClick:()=>m(!1),disabled:r,children:"Cancel"}),e.jsx(o.Button,{size:"xs",onClick:d,disabled:!a.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Creating..."]}):"Create library visual"})]})]})})}function wn(t){return t?new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Unknown"}function Cn(t,s){var r;const n=(r=t.ownership.createdBy)==null?void 0:r.type;return n==="tenant"||n==="organization"&&s}function rs(t,s){var n,r;return Cn(t,s)?((n=t.ownership.createdBy)==null?void 0:n.name)||((r=t.createdByTenantUserRel)==null?void 0:r.name)||t.lastModifiedBy||"Unknown":"Organization"}function na(t,s){return rs(t,s).split(/\s+/).filter(Boolean).slice(0,2).map(r=>r.charAt(0).toUpperCase()).join("")||"?"}function ra(t){const s=(t||"").toLowerCase();return s.includes("table")?o.Table2:s.includes("pie")||s.includes("donut")?i.ChartPie:s.includes("line")?i.ChartLine:s.includes("bar")?o.ChartColumn:ss.LayoutGrid}function aa({visual:t}){const s=t.ownership.status==="public"?"Public":t.ownership.status==="shared"||t.ownership.sharedCount>0?"Shared":"Private";return e.jsx("span",{className:"inline-flex items-center rounded-[4px] border border-border/60 px-1.5 py-px text-[11px] text-muted-foreground",children:s})}function oa({open:t,onOpenChange:s}){const[n,r]=h.useState(""),[a,l]=h.useState(new Set),[c,u]=h.useState(!1),[d,m]=h.useState(null),[x,g]=h.useState(null),[f,b]=h.useState(!1),[A,S]=h.useState(null),[N,j]=h.useState(null),w=()=>{l(new Set),m(null),g(null),b(!1),S(null)},y=()=>{s(!1),w()},{selectVisual:C}=i.useManagementActions(),{handleAddLibraryVisual:T,handleEditLibraryVisual:V}=me.useVisualUtils(),{isConsoleMode:D}=i.useDashboardPreferences(),{resources:F,isLoading:U,isError:G,createResource:B,updateResource:_,deleteResourceAsync:$,duplicateResource:M,isCreating:Q,isDeleting:ee}=i.useVisualManagement(void 0,E=>{u(!1),E&&(C(E),V(E),y())}),{startUpdating:L,stopUpdating:W,isUpdating:k}=i.useResourceUpdateState(),oe=F,Y=h.useMemo(()=>{const E=n.trim().toLowerCase();return E?oe.filter(H=>{var te,we,Me;return((te=H.title)==null?void 0:te.toLowerCase().includes(E))||((we=H.description)==null?void 0:we.toLowerCase().includes(E))||((Me=H.kind)==null?void 0:Me.toLowerCase().includes(E))}):oe},[n,oe]),X=h.useMemo(()=>oe.filter(E=>a.has(E.id)),[a,oe]),he=X.filter(E=>E.permissions.canDelete),ye=X.filter(E=>E.permissions.canShare),ie=Y.length>0&&Y.every(E=>a.has(E.id)),z=Y.some(E=>a.has(E.id)),Pe=E=>{const H=new Set(a);E(H),l(H)},ve=E=>{Pe(H=>{H.has(E)?H.delete(E):H.add(E)})},ke=()=>{l(E=>{const H=new Set(E);return ie?Y.forEach(te=>H.delete(te.id)):Y.forEach(te=>H.add(te.id)),H})},Se=async E=>{(await T(E)).success&&y()},q=async()=>{const E=X;if(E.length===0)return;let H=!1;for(const te of E)if(!(await T(te)).success){H=!0;break}H||y()},Ne=E=>{V(E),y()},O=E=>{j(E),M(E,{onSettled:()=>j(null)})},ne=()=>{if(he.length===0){i.ue.error("Select a visual you can delete");return}S(null),b(!0)},qe=async()=>{const E=A?[A]:he;try{for(const H of E)await $(H.id);l(H=>{const te=new Set(H);return E.forEach(we=>te.delete(we.id)),te}),b(!1),S(null)}catch{}},Oe=()=>{if(X.length!==1){i.ue.error("Select one visual to share");return}const[E]=X;if(!E.permissions.canShare){i.ue.error("You do not have permission to share this visual");return}m(E)},I=({title:E,description:H})=>{if(!x)return;const te={};if(E!==x.title&&(te.title=E),(x.description||"")!==H&&(te.description=H),Object.keys(te).length===0){g(null);return}const we=Object.keys(te),Me=we.length===1?we[0]:void 0;L(x.id,Me),_({resourceId:x.id,data:te},{onSuccess:()=>{W(x.id,Me),g(null)},onError:()=>{W(x.id,Me)}})},P=E=>{s(E),E||w()},fe=A?1:he.length;return e.jsxs(e.Fragment,{children:[e.jsx(i.Dialog,{open:t,onOpenChange:P,children:e.jsxs(i.DialogContent,{showCloseButton:!1,className:"flex max-h-[80vh] w-[min(72rem,calc(100vw-2rem))] max-w-none grid-cols-none flex-col gap-0 overflow-hidden rounded-[6px] border-border/60 p-0 shadow-lg",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(o.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx(i.DialogTitle,{className:"truncate text-[13px] font-medium leading-none tracking-normal",children:"Visuals library"}),e.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase leading-none tracking-[0.08em] text-muted-foreground",children:"Add to dashboard"})]})]}),e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>P(!1),"aria-label":"Close visuals library",children:"×"})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 px-3 py-2",children:[e.jsxs("div",{className:"relative min-w-[12rem] flex-1 md:max-w-md",children:[e.jsx(Ae.Search,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{autoFocus:!0,value:n,onChange:E=>r(E.target.value),placeholder:"Search visuals...",className:"h-7 w-full rounded-control border border-input bg-background pl-7 pr-2 text-[12px] text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none","aria-label":"Search visuals"})]}),e.jsxs(o.Button,{size:"xs",variant:"outline",className:"ml-auto",onClick:()=>u(!0),children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"New library visual"]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:U?e.jsx("div",{className:"p-3",children:e.jsx(ta,{})}):G?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:e.jsx("p",{className:"text-[13px] text-destructive",children:"Failed to load visuals"})}):Y.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:[e.jsx(ss.LayoutGrid,{className:"h-5 w-5 text-muted-foreground/60"}),e.jsx("p",{className:"text-[13px] font-medium",children:n?"No visuals found":"No visuals yet"}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:n?"Try a different search.":"Create a saved visual to add it here."})]}):e.jsx(ia,{visuals:Y,selectedIds:a,allFilteredSelected:ie,someFilteredSelected:z,onSelectAll:ke,onToggleSelection:ve,onAddVisual:Se,onOpenVisual:Ne,onEditDetails:g,onShareVisual:m,onDeleteVisual:E=>{S(E),b(!0)},onDuplicateVisual:O,duplicatingId:N,isDeleting:ee,isConsoleMode:D})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border/60 px-3 py-2",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:a.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-[12px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium tabular-nums text-foreground",children:a.size})," ","selected"]}),e.jsx(o.Button,{size:"xs",variant:"ghost",onClick:()=>l(new Set),children:"Clear"}),e.jsxs(o.Button,{size:"xs",variant:"outline",onClick:Oe,disabled:X.length!==1||ye.length!==1,children:[e.jsx(i.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),e.jsxs(o.Button,{size:"xs",variant:"outline",className:"text-destructive hover:text-destructive",onClick:ne,disabled:he.length===0,children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete ",he.length||a.size]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(o.Button,{size:"xs",variant:"outline",onClick:()=>P(!1),children:"Close"}),e.jsxs(o.Button,{size:"xs",onClick:q,disabled:a.size===0,children:[e.jsx(o.Check,{className:"h-3.5 w-3.5"}),a.size===0?"Add to dashboard":`Add ${a.size} visual${a.size===1?"":"s"}`]})]})]})]})}),e.jsx(sa,{open:c,onOpenChange:u,onSubmit:B,isCreating:Q}),d&&e.jsx(i.ShareDialog,{resource:d,resourceType:i.ResourceType.VISUAL,onClose:()=>m(null)}),x&&e.jsx(i.ResourceEditDialog,{open:!!x,resourceLabel:"Visual",initialTitle:x.title||"",initialDescription:x.description||"",onClose:()=>g(null),onSave:I,isSaving:k(x.id)}),e.jsx(i.AlertDialog,{open:f,onOpenChange:E=>{!E&&ee||(b(E),E||S(null))},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsxs(i.AlertDialogTitle,{children:["Delete ",fe," visual",fe===1?"":"s","?"]}),e.jsx(i.AlertDialogDescription,{children:"This cannot be undone. Visuals already added to dashboards may need to be removed from those dashboards separately."})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{disabled:ee,children:"Cancel"}),e.jsxs(i.AlertDialogAction,{onClick:E=>{E.preventDefault(),qe()},disabled:ee||fe===0,children:[ee?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),ee?"Deleting...":"Delete"]})]})]})})]})}function ia({visuals:t,selectedIds:s,allFilteredSelected:n,someFilteredSelected:r,onSelectAll:a,onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:f,isDeleting:b,isConsoleMode:A}){return e.jsxs("div",{className:"min-w-[48rem]",children:[e.jsxs("div",{className:"grid h-9 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/60 px-3 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(i.Checkbox,{checked:n?!0:r?"indeterminate":!1,onCheckedChange:a,"aria-label":"Select all visuals"}),e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Created by"}),e.jsx("span",{children:"Updated"}),e.jsx("span",{children:"Visibility"}),e.jsx("span",{className:"text-right",children:"Shared"}),e.jsx("span",{className:"text-right",children:"Actions"})]}),t.map(S=>e.jsx(la,{visual:S,selected:s.has(S.id),onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:f,isDeleting:b,isConsoleMode:A},S.id))]})}function la({visual:t,selected:s,onToggleSelection:n,onAddVisual:r,onOpenVisual:a,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g}){var A;const f=ra(t.kind),b=()=>{r(t)};return e.jsxs("div",{className:o.cn("group grid min-h-12 grid-cols-[2.5rem_minmax(14rem,1.8fr)_minmax(10rem,1fr)_8rem_7rem_5rem_5.5rem] items-center border-b border-border/50 px-3 text-[13px] hover:bg-muted/50",s&&"bg-muted/70"),children:[e.jsx("div",{children:e.jsx(i.Checkbox,{checked:s,onCheckedChange:()=>n(t.id),"aria-label":`Select ${t.title||"visual"}`})}),e.jsxs("button",{type:"button",className:"flex min-w-0 items-center gap-2 rounded-[4px] text-left outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:b,"aria-label":`Add ${t.title||"visual"} to dashboard`,children:[e.jsx(f,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-foreground",title:t.title||"Untitled Visual",children:t.title||"Untitled Visual"}),((A=t.description)==null?void 0:A.trim())&&e.jsx("div",{className:"truncate text-[11px] text-muted-foreground",title:t.description,children:t.description})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.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:na(t,g)}),e.jsx("span",{className:"truncate text-muted-foreground",children:rs(t,g)})]}),e.jsx("span",{className:"text-muted-foreground",children:wn(t.updatedAt)}),e.jsx(aa,{visual:t}),e.jsx("span",{className:"text-right tabular-nums text-muted-foreground",children:t.ownership.sharedCount>0?t.ownership.sharedCount:"—"}),e.jsx(ca,{visual:t,onOpenVisual:a,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g})]})}function ca({visual:t,onOpenVisual:s,onEditDetails:n,onShareVisual:r,onDeleteVisual:a,onDuplicateVisual:l,duplicatingId:c,isDeleting:u,isConsoleMode:d}){return e.jsxs("div",{className:"flex items-center justify-end gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",onClick:m=>m.stopPropagation(),children:[e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0",onClick:()=>s(t),"aria-label":"Edit visual",children:e.jsx(i.PenLine,{className:"h-3.5 w-3.5"})}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(o.Button,{size:"xs",variant:"ghost",className:"w-7 px-0","aria-label":"More actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"z-[60] w-44 rounded-[6px] border-border/60 p-1 shadow-sm",children:[e.jsxs(i.DropdownMenuItem,{onClick:()=>s(t),children:[e.jsx(i.PenLine,{className:"h-3.5 w-3.5"}),"Edit visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>l(t.id),disabled:c===t.id,children:[c===t.id?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(i.Copy,{className:"h-3.5 w-3.5"}),c===t.id?"Duplicating...":"Duplicate"]}),t.permissions.canEdit&&e.jsxs(i.DropdownMenuItem,{onClick:()=>n(t),children:[e.jsx(i.PenLine,{className:"h-3.5 w-3.5"}),"Edit details"]}),t.permissions.canShare&&e.jsxs(i.DropdownMenuItem,{onClick:()=>r(t),children:[e.jsx(i.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),t.permissions.canDelete&&e.jsxs(e.Fragment,{children:[e.jsx(i.DropdownMenuSeparator,{}),e.jsxs(i.DropdownMenuItem,{className:"text-destructive focus:bg-destructive/10 focus:text-destructive",onClick:()=>a(t),disabled:u,children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),u?"Deleting...":"Delete"]})]}),e.jsx(i.DropdownMenuSeparator,{}),e.jsxs("div",{className:"space-y-1 px-2 py-1.5 text-[11px] text-muted-foreground",children:[Cn(t,d)&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(i.User,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:rs(t,d)})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(i.Calendar,{className:"h-3 w-3"}),e.jsx("span",{children:wn(t.updatedAt)})]})]})]})]})]})}function da({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:a=!1,destinationMode:l="both",onConfirm:c}){const[u,d]=h.useState(n&&r?`Copy of ${r}`:r||""),[m,x]=h.useState("");h.useEffect(()=>{t&&(d(n&&r?`Copy of ${r}`:r||""),x(""))},[t,n,r]);const g=!!u.trim(),f=l==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:l==="library"?{saveToLibrary:!0,saveToCurrentDashboard:!1,badgeType:"library",description:"Creates a reusable visual in Visual Library.",actionLabel:"Save as Library Visual"}:{saveToLibrary:!0,saveToCurrentDashboard:!0,badgeType:"linked",description:"Creates a new library visual and adds a linked copy to this dashboard.",actionLabel:"Save Copy as Linked Visual"},b=()=>{!g||a||c({name:u.trim(),description:m.trim()||void 0,saveToLibrary:f.saveToLibrary,saveToCurrentDashboard:f.saveToCurrentDashboard})};return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(i.DialogHeader,{children:[e.jsxs(i.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),f.badgeType!=="local"&&e.jsx(me.VisualBadge,{type:f.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(i.DialogDescription,{children:f.description})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(o.Label,{htmlFor:"name",children:"Name"}),e.jsx(o.Input,{id:"name",value:u,onChange:A=>d(A.target.value),placeholder:"Enter visual name",disabled:a})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(i.Textarea,{id:"description",value:m,onChange:A=>x(A.target.value),placeholder:"Enter visual description",rows:3,disabled:a})]})]}),e.jsxs(i.DialogFooter,{children:[e.jsx(o.Button,{variant:"outline",onClick:()=>s(!1),disabled:a,children:"Cancel"}),e.jsxs(o.Button,{onClick:b,disabled:!g||a,children:[a&&e.jsx(o.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),f.actionLabel]})]})]})})}function ua(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[a,l]=h.useState(null),[c,u]=h.useState(null),d=o.useEditorStore(D=>D.frame),m=o.useEditorStore(D=>D.card),x=i.useSelectedVisual(),g=o.useDashboardStore(D=>D.selectedSheetId),f=o.useDashboardStore(D=>D.dashboard),{getUpdatedFrame:b}=me.useVisualUtils(),{selectVisual:A}=i.useManagementActions(),{addFrame:S,setSelectedFrameId:N,setIsVisualEditing:j}=o.useDashboardActions(),w=i.useResolveExistingFrameSemanticExecutionPayload(),y=!!(d!=null&&d.visualId),C=(()=>{var D,F;return((D=d==null?void 0:d.cards)==null?void 0:D.length)===1&&((F=d.cards[0])!=null&&F.title)?d.cards[0].title:x!=null&&x.title?x.title:(m==null?void 0:m.title)||"Untitled Visual"})(),T=i.useCreateVisualWithFrame(D=>{D!=null&&D.id&&(A(D),n&&a&&c&&g&&(async()=>{try{const F={...a,id:o.v4(),visualId:D.id};S(g,F,{position:"end",semanticExecutionPayload:c}),N(F.id),r(!1),l(null),u(null),j(!1)}catch(F){console.error("Failed to promote semantic metadata for saved visual:",F),i.ue.error(F instanceof Error?F.message:"Failed to prepare semantic metadata for the saved visual")}})(),s(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:s,handleSaveAs:async D=>{if(!g){i.ue.error("No sheet selected");return}const F=b(),U=o.getDynamicFrameSaveIssue(F);if(U){i.ue.error(U);return}const B=F.cards.length===1?{...F,cards:F.cards.map(_=>({..._,title:D.name}))}:F;if(D.saveToLibrary){let _=null;if(D.saveToCurrentDashboard)try{_=await w(B,{previousFrame:i.findDashboardFrameById(f,B.id)})}catch(M){console.error("Failed to prepare semantic metadata before saving visual:",M),i.ue.error(M instanceof Error?M.message:"Failed to prepare semantic metadata for the saved visual");return}r(D.saveToCurrentDashboard),l(B),u(_);const $={title:D.name,description:D.description,frameObject:B,isPrivate:!1};T.mutate($)}else if(D.saveToCurrentDashboard){const _={...B,id:o.v4(),visualId:void 0};try{const $=await w(B,{previousFrame:i.findDashboardFrameById(f,B.id)});S(g,_,{position:"end",semanticExecutionPayload:$}),N(_.id),i.ue.success("Visual saved to dashboard"),s(!1),j(!1)}catch($){console.error("Failed to save visual to dashboard:",$),i.ue.error($ instanceof Error?$.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:y,currentVisualName:C,isSaving:T.isPending}}function ma(t={}){const s=o.useEditorStore(B=>B.frame),n=o.useEditorStore(B=>B.editorContext),r=i.useManagementStore(B=>B.selectedVisual),a=o.useDashboardStore(B=>B.selectedFrameId),l=o.useDashboardStore(B=>B.selectedSheetId),c=o.useDashboardStore(B=>B.dashboard),{setIsVisualEditing:u,updateFrame:d}=o.useDashboardActions(),[m,x]=h.useState(!1),[g,f]=h.useState("both"),b=i.useResolveExistingFrameSemanticExecutionPayload(),A=(n==null?void 0:n.type)==="documentSection",S=!!(s!=null&&s.visualId||r!=null&&r.id),N=!!(s!=null&&s.visualId&&a),j=S&&!N,{saveAsDialogOpen:w,setSaveAsDialogOpen:y,handleSaveAs:C,isLibraryVisual:T,currentVisualName:V,isSaving:D}=ua(),{getUpdatedFrame:F}=me.useVisualUtils();if(A)return e.jsxs(e.Fragment,{children:[e.jsx(me.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(me.EditorCancelButton,{})]});const U=async()=>{if(!l){i.ue.error("No sheet selected");return}if(m)return;x(!0);const B=F(),_=o.getDynamicFrameSaveIssue(B);if(_){x(!1),i.ue.error(_);return}const $={...B,visualId:void 0},M=i.findDashboardFrameById(c,$.id);try{const Q=await b($,{previousFrame:M});d(l,$,{semanticExecutionPayload:Q})}catch(Q){console.error("Failed to apply local semantic metadata:",Q),x(!1),i.ue.error(Q instanceof Error?Q.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{x(!1),i.ue.success("Changes applied. Visual is now local to this dashboard"),u(!1)},300)},G=B=>{f(B),y(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(me.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&j&&e.jsx(me.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&N&&e.jsx(me.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(o.Button,{variant:"default",size:"xs",className:"w-7 !rounded-none border-l border-primary-foreground/20 px-0","aria-label":"Open visual save options",disabled:D||m,children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[N&&e.jsxs(e.Fragment,{children:[e.jsxs(i.DropdownMenuItem,{onClick:U,disabled:m,children:[e.jsx(o.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(i.DropdownMenuSeparator,{})]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("local"),disabled:D,children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("library"),disabled:D,children:[e.jsx(me.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>G("both"),disabled:D,children:[e.jsx(me.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(me.EditorCancelButton,{}),e.jsx(da,{open:w,onOpenChange:B=>{D||y(B)},isLibraryVisual:T,currentVisualName:V,isSaving:D,destinationMode:g,onConfirm:C})]})}function ha({className:t}){const s=o.useEditorStore(m=>m.isDevMode),n=o.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=o.useEditorActions(),{config:a}=h.useContext(i.SemaphorContext).tokenProps,l=(a==null?void 0:a.showAdvancedMode)!==!1;if(!n||!l)return null;const c=s?o.SlidersHorizontal:i.CodeXml,u=s?"Drag & drop":"SQL",d=s?"Switch to drag-and-drop mode":"Switch to SQL mode";return e.jsxs("button",{type:"button","aria-label":d,title:d,onClick:()=>r(!s),className:o.cn("inline-flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 text-[12px] font-medium text-foreground transition-colors hover:bg-muted/40 focus-visible:border-ring focus-visible:outline-none",t),children:[e.jsx(c,{className:"h-3 w-3 text-muted-foreground"}),u]})}function xa({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:a,title:l="Unsaved changes",description:c="You have unsaved changes to this dashboard. What would you like to do?",cancelLabel:u="Cancel",discardLabel:d="Discard",saveLabel:m="Save"}){const x=g=>{!g&&a||s(g)};return e.jsx(i.AlertDialog,{open:t,onOpenChange:x,children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:l}),e.jsx(i.AlertDialogDescription,{children:c})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(o.Button,{type:"button",size:"xs",onClick:r,disabled:a,variant:"ghost",className:"mr-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",children:d}),e.jsx(i.AlertDialogCancel,{disabled:a,children:u}),e.jsx(o.Button,{type:"button",size:"xs",onClick:n,disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(o.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):m})]})]})})}const pa=1e4,fa=15e3,ga=3e4,ba=3e4,ja=12e4,Xs=2*60*60*1e3;function ya(t){const s=Date.now()-t.getTime();return s<ba?pa:s<ja?fa:ga}function va(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(f=>f.activeExports),[r,a]=h.useState(typeof document<"u"?!document.hidden:!0),l=h.useRef(null),c=h.useRef(!1),u=h.useRef(void 0),d=s==null?void 0:s.apiServiceUrl,m=t==null?void 0:t.accessToken,x=h.useCallback(()=>{const f=i.useExportStore.getState().activeExports;return Array.from(f.values()).filter(b=>i.isExportInProgress(b.status))},[]);h.useEffect(()=>{if(typeof document>"u")return;const f=()=>{a(!document.hidden)};return document.addEventListener("visibilitychange",f),()=>{document.removeEventListener("visibilitychange",f)}},[]);const g=h.useCallback(async()=>{if(!d||!m){c.current=!1;return}const f=x();if(f.length===0){c.current=!1;return}const b=Date.now(),A=f.filter(y=>b-y.startedAt.getTime()>Xs);if(A.length>0){const{updateExport:y}=i.useExportStore.getState().actions;for(const C of A)y(C.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const S=f.filter(y=>b-y.startedAt.getTime()<=Xs);if(S.length===0){c.current=!1;return}const N=await Promise.allSettled(S.map(async y=>{try{const C=await i.getExportStatus(d,m,y.id);let T;if(C.status==="completed")try{T=await i.getDownloadUrl(d,m,y.id)}catch(V){console.error(`[useExportPolling] Failed to get download URL for ${y.id}:`,V)}return{id:y.id,status:C.status,progress:C.progress,completedChunks:C.completedChunks,completedAt:C.completedAt?new Date(C.completedAt):void 0,lastUpdatedAt:new Date,fileSize:C.fileSize,error:C.error,downloadUrl:T}}catch(C){return console.error(`[useExportPolling] Failed to poll export ${y.id}:`,C),null}})),{updateExport:j}=i.useExportStore.getState().actions;for(const y of N)y.status==="fulfilled"&&y.value&&j(y.value.id,y.value);const w=x();if(w.length>0&&!document.hidden){const y=w.reduce((T,V)=>V.startedAt<T?V.startedAt:T,w[0].startedAt),C=ya(y);l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{var T;(T=u.current)==null||T.call(u)},C)}else c.current=!1},[d,m,x]);return h.useEffect(()=>{u.current=g},[g]),h.useEffect(()=>{var b;x().length>0&&r&&!c.current&&(c.current=!0,(b=u.current)==null||b.call(u))},[n,r,x]),h.useEffect(()=>{var b;const f=x();r&&f.length>0&&!c.current&&(c.current=!0,(b=u.current)==null||b.call(u))},[r,x]),h.useEffect(()=>{!r&&l.current&&(clearTimeout(l.current),l.current=null,c.current=!1)},[r]),h.useEffect(()=>()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),{isPolling:c.current,isTabVisible:r,inProgressCount:x().length}}function Na(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(u=>u.activeExports),{addExport:r}=i.useExportActions(),a=h.useRef(!1),l=s==null?void 0:s.apiServiceUrl,c=t==null?void 0:t.accessToken;h.useEffect(()=>{if(a.current||!l||!c)return;(async()=>{try{const{exports:d}=await i.getExports(l,c,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const m of d){if(n.has(m.id))continue;const x=m.totalChunks?Math.round(m.completedChunks/m.totalChunks*100):0;let g;if(m.status==="completed")try{g=await i.getDownloadUrl(l,c,m.id)}catch(b){console.error(`[useExportRecovery] Failed to get download URL for ${m.id}:`,b)}const f={id:m.id,status:m.status,progress:x,title:wa(m),totalRows:m.totalRows,totalChunks:m.totalChunks,completedChunks:m.completedChunks,startedAt:new Date(m.createdAt),lastUpdatedAt:new Date,completedAt:m.completedAt?new Date(m.completedAt):void 0,fileSize:m.fileSize,error:m.error,expiresAt:new Date(m.expiresAt),downloadUrl:g};r(f)}a.current=!0}catch(d){console.error("[useExportRecovery] Failed to recover exports:",d),a.current=!0}})()},[l,c,r,n])}function wa(t){return t.title?t.title:i.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function Sn({export:t,onRemove:s}){const n=()=>{t.downloadUrl&&window.open(t.downloadUrl,"_blank")},r=u=>{u.stopPropagation(),s==null||s(t.id)},a=()=>{switch(t.status){case"completed":return e.jsx(i.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(Jr,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"});default:return e.jsx(o.LoaderCircle,{className:"text-foreground-muted mt-0.5 h-5 w-5 shrink-0 animate-spin"})}},l=i.isExportInProgress(t.status),c=(()=>{switch(t.status){case"pending":return"Queued...";case"processing":return"Processing...";case"chunking":return"Processing...";case"compacting":return"Finalizing...";default:return"Processing..."}})();return e.jsxs("div",{className:"group p-4 transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[a(),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h4",{className:"mb-1 truncate text-sm font-medium",children:t.title}),t.status==="completed"&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[t.totalRows.toLocaleString()," rows"]}),t.fileSize&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:i.formatFileSize(t.fileSize)})]})]}),l&&e.jsx("div",{className:"text-xs text-muted-foreground",children:c}),t.status==="failed"&&e.jsx("div",{className:"line-clamp-2 text-xs text-destructive",children:t.error||"Export failed"})]})]}),e.jsx(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:r,"aria-label":"Remove notification",children:e.jsx(K.X,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"ml-8",children:[t.status==="completed"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs.formatDistanceToNow(t.startedAt,{addSuffix:!0})}),t.downloadUrl&&e.jsxs(o.Button,{size:"sm",variant:"outline",className:"h-8 bg-transparent",onClick:n,children:[e.jsx(i.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),l&&e.jsxs("div",{children:[e.jsx(i.Progress,{value:t.progress,className:"h-1.5"}),e.jsxs("span",{className:"mt-1 block text-xs text-muted-foreground",children:[t.progress,"% complete"]})]}),t.status==="failed"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function kn(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(S=>S.activeExports),{clearCompleted:r,removeExport:a,updateExport:l}=i.useExportActions(),[c,u]=h.useState(!1),[d,m]=h.useState(!1),x=Array.from(n.values()).sort((S,N)=>N.startedAt.getTime()-S.startedAt.getTime()),g=x.some(S=>S.status==="completed"||S.status==="failed"),f=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!(!S||!N)){u(!0);try{const j=Array.from(n.values());await Promise.all(j.map(async w=>{try{const y=await i.getExportStatus(S,N,w.id);let C;if(y.status==="completed")try{C=await i.getDownloadUrl(S,N,w.id)}catch(T){console.error(`Failed to get download URL for ${w.id}:`,T)}l(w.id,{status:y.status,progress:y.progress,completedChunks:y.completedChunks,completedAt:y.completedAt?new Date(y.completedAt):void 0,lastUpdatedAt:new Date,fileSize:y.fileSize,error:y.error,downloadUrl:C})}catch(y){console.error(`Failed to refresh export ${w.id}:`,y)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,l]),b=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!S||!N){r();return}m(!0);try{const j=x.filter(y=>y.status==="completed"||y.status==="failed"),w=await Promise.allSettled(j.map(async y=>(await i.cancelExport(S,N,y.id),y.id)));for(const y of w)y.status==="fulfilled"?a(y.value):console.error("Failed to delete export:",y.reason)}finally{m(!1)}},[x,s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,r,a]),A=h.useCallback(async S=>{const N=s==null?void 0:s.apiServiceUrl,j=t==null?void 0:t.accessToken;if(N&&j)try{await i.cancelExport(N,j,S),a(S);return}catch(w){console.error(`Failed to cancel export ${S}:`,w)}a(S)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,a]);return x.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Ws,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active exports"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Large exports will appear here"})]}):e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("h4",{className:"font-semibold",children:"Exports"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:f,disabled:c,title:"Refresh status",children:e.jsx(i.RefreshCw,{className:`h-4 w-4 ${c?"animate-spin":""}`})}),g&&e.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-sm",onClick:b,disabled:d,children:d?"Clearing...":"Clear all"})]})]}),e.jsx("div",{className:"max-h-[350px] overflow-y-auto",children:e.jsx("div",{className:"divide-y",children:x.map(S=>e.jsx(Sn,{export:S,onRemove:A},S.id))})})]})}function Ca({variant:t}){const s=i.useExportStore(d=>d.activeExports),n=i.useInProgressExportsCount(),r=s.size>0,a=Array.from(s.values()).some(d=>d.status==="completed"||d.status==="failed"),c=n>0?n>9?"9+":String(n):null,u=r;return e.jsxs(o.Popover,{children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs(o.Button,{variant:t??"ghost",size:"xs",className:"relative w-7 px-0 text-muted-foreground hover:text-foreground","aria-label":"Export notifications",children:[e.jsx(i.Bell,{className:"h-3.5 w-3.5"}),u&&e.jsx("span",{className:`absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground ${c?"-right-0.5 -top-0.5 h-3.5 min-w-3.5 px-0.5 text-[9px] font-semibold":"right-1 top-1 h-1.5 w-1.5"}`,children:c})]})}),e.jsx(o.PopoverContent,{className:"w-80 p-0",align:"end",sideOffset:8,children:e.jsx(kn,{})})]})}function Sa(t){if(t)return{renamed:t.type==="rename"?{oldId:t.oldId,newId:t.newId}:void 0,removedControlId:t.type==="remove"?t.controlId:void 0,cardBindingsById:t.type==="add"||t.type==="update"?t.cardBindingsById:void 0,affectedBindingControlIds:t.type==="add"||t.type==="update"?t.affectedBindingControlIds:void 0}}function Dn({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:a="manage"}){const l=a==="create",{forceClose:c,handleOpenChange:u,isCreateFlowActive:d,preventPassiveDismissDuringCreate:m,resolvedOpen:x,setIsCreateFlowActive:g}=me.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:a==="create",dismissMode:r?"passive":"explicit-only"}),f=o.useDashboardStore(F=>F.dashboard),{setDashboardControlsModel:b}=o.useDashboardActions(),{participants:A}=i.useDashboardStructuralParticipants(o.getDashboardCards(f)),S=Array.from(new Map(A.flatMap(F=>F.fieldChoices.map(U=>{var G;return[U.value,{option:U,target:(G=F.fieldTargetMap)==null?void 0:G[U.value]}]}))).values()),N=Array.from(new Map(A.flatMap(F=>F.metricChoices.map(U=>{var G;return[U.value,{option:U,target:(G=F.metricTargetMap)==null?void 0:G[U.value]}]}))).values()),j=o.collectDashboardControlIds({...f||{},controls:[]}),w=i.buildDashboardStructuralParticipantIdsByControlId(f),y=(F,U,G)=>{b(F,U,Sa(G))},C=h.useCallback(()=>{if(l){c();return}g(!1)},[l,c,g]),T=e.jsx(me.ControlDefinitionListEditor,{scope:"dashboard",controls:f.controls||[],reservedControlIds:j,defaultValues:f.defaultControlValues||{},usageByControlId:i.buildDashboardControlUsageById(f),availableFieldChoices:S,availableMetricChoices:N,structuralParticipants:A,structuralParticipantIdsByControlId:w,initialCreateFlow:a==="create",onCreateFlowActiveChange:g,onCreateFlowComplete:C,onChange:y,emptyMessage:"No dashboard controls yet."}),V=d?"Add dashboard control":"Dashboard Controls",D=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Dashboard Controls"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),T]});return r?e.jsxs(o.Popover,{open:x,onOpenChange:u,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:n||e.jsxs(o.Button,{variant:"outline",className:"h-7 px-2",size:"sm",children:[e.jsx(o.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Controls"]})}),e.jsx(o.PopoverContent,{className:"w-[620px] max-w-[95vw] space-y-4",align:"end",onEscapeKeyDown:m,onPointerDownOutside:m,children:D})]}):e.jsx(i.Dialog,{open:x,onOpenChange:u,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:m,onPointerDownOutside:m,children:[e.jsxs(i.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(i.DialogDescription,{className:d?"sr-only":"text-[13px]",children:d?"Configure and add a shared dashboard control.":"Add shared controls viewers can use across the dashboard. Each card can decide how to respond to the same control."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:T})]})})}const ka=["enum","multi_enum","text","number","boolean","date"];function En({open:t,onOpenChange:s,initialMode:n="manage"}){var D;const r=n==="create",{forceClose:a,handleOpenChange:l,isCreateFlowActive:c,preventPassiveDismissDuringCreate:u,resolvedOpen:d,setIsCreateFlowActive:m}=me.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),x=o.useDashboardStore(F=>F.dashboard),g=o.useDashboardStore(F=>F.selectedSheetId),{setDashboardInputs:f}=o.useDashboardActions(),b=(D=x.sheets)==null?void 0:D.find(F=>F.id===g),A=(b==null?void 0:b.kind)==="document"&&!!b.document,S=h.useMemo(()=>A&&(b!=null&&b.document)?i.getDocumentSheetDashboardInputs(x,b.id):[],[x,A,b==null?void 0:b.document,b==null?void 0:b.id]),N=h.useMemo(()=>S.filter(F=>F.kind==="control"),[S]),j=h.useMemo(()=>N.map(F=>F.control),[N]),w=h.useMemo(()=>Ea(j),[j]),y=h.useMemo(()=>Da(x),[x]),C=h.useCallback(()=>{if(r){a();return}m(!1)},[r,a,m]),T=h.useCallback((F,U,G)=>{!A||!(b!=null&&b.document)||f(Ia({allInputs:x.inputs||[],documentSheetId:b.id,currentDocumentInputs:S,nextControls:F,nextDefaultValues:U,change:G}))},[x.inputs,S,A,b,f]);if(!A||!(b!=null&&b.document))return null;const V=c?"Add document control":"Document Controls";return e.jsx(i.Dialog,{open:d,onOpenChange:l,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs(i.DialogHeader,{className:c?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(i.DialogDescription,{className:c?"sr-only":"text-[13px]",children:c?"Configure and add a document-local control input.":"Add document-local control inputs. They are stored on this document sheet and are not dashboard controls."})]}),e.jsx("div",{className:"min-h-0 overflow-y-auto pr-1",children:e.jsx(me.ControlDefinitionListEditor,{scope:"dashboard",controls:j,reservedControlIds:y,defaultValues:w,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:ka,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:C,onChange:T,emptyMessage:"No document controls yet."})})]})})}function Da(t){return(t.controls||[]).map(s=>s.id)}function Ea(t){const s={};for(const n of t)n.defaultValue!==void 0&&(s[n.id]=n.defaultValue);return s}function Aa(t,s){return s?Object.prototype.hasOwnProperty.call(s,t.id)?{...t,defaultValue:s[t.id]}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}:t.defaultValue===void 0?t:{...t,defaultValue:void 0}}function Ia({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:a,change:l}){const c=new Map(r.map(f=>[f.id,Aa(f,a)])),u=(l==null?void 0:l.type)==="rename"?{oldId:l.oldId,newId:l.newId}:null,d=new Set,m=[];for(const f of n){if(f.kind!=="control"){m.push(f);continue}const b=c.get(f.control.id)||((u==null?void 0:u.oldId)===f.control.id?c.get(u.newId):void 0);if(!b)continue;d.add(b.id);const A=i.createUniqueDashboardInputVariableNameFromName(b.id,[...t,...m].filter(N=>N.id!==f.id)),S=b.id===A?b:{...b,id:A};m.push({...f,label:S.label,variableName:A,requiredAtExecution:S.requiredAtExecution,control:S})}for(const f of c.values())d.has(f.id)||m.push(i.createDashboardControlInputFromControl({control:f,existingInputs:[...t,...m],sheetId:s}));const x=new Set(n.map(f=>f.id));return[...t.filter(f=>!x.has(f.id)),...m]}function An({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:a="default",className:l,primaryButtonClassName:c,secondaryButtonClassName:u,pickerContentClassName:d,settingsContentClassName:m}){const x=a==="toolbar",[g,f]=h.useState(!1),b=i.useSurfaceAppearance("interactive");return e.jsxs("div",{className:o.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",x?"h-8":"h-7",l),children:[e.jsxs(o.Popover,{open:t,onOpenChange:s,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs(o.Button,{variant:"ghost",size:"xs",className:o.cn("h-full rounded-none border-0 bg-transparent pl-2.5 pr-2 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",c),children:[t?e.jsx(Yr,{className:"h-3.5 w-3.5"}):e.jsx(i.Filter,{className:"h-3.5 w-3.5"}),"Filter"]})}),e.jsx(o.PopoverContent,{align:"end",sideOffset:6,className:o.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",d),style:b.contentStyle,children:n})]}),e.jsxs(o.Popover,{open:g,onOpenChange:f,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsx(o.Button,{variant:"ghost",size:"xs",className:o.cn("h-full w-7 rounded-none border-0 border-l border-border/60 bg-transparent px-0 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",u),"aria-label":"Filter and control actions",children:e.jsx(K.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsx(o.PopoverContent,{align:"end",sideOffset:6,className:o.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",m),style:b.contentStyle,children:r(()=>f(!1))})]})]})}function Ta(){me.useSyncLegacyEditorState();const t=o.useDashboardStore(d=>d.selectedSheetId),s=o.useDashboardStore(d=>d.selectedFrameId),n=o.useDashboardStore(d=>d.dashboard),r=o.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:a}=o.useDashboardActions(),{setCard:l}=o.useEditorActions(),c=o.useEditorStore(d=>d.card.dataSource);return h.useEffect(()=>{var m,x;let d=r();if(!d){const g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(b=>b.id===t),f=(x=g==null?void 0:g.frames)==null?void 0:x[0];f&&(a(f.id),d=f)}if(d){const g=d.cards.find(f=>f.id===d.activeCardId);g&&l(g)}},[r,t,s,n,a,l]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function La(){const t=o.useDashboardStore(d=>d.dashboard),s=o.useDashboardStore(d=>d.semanticExecutionPayload),n=o.useDashboardStore(d=>d.actions.addFilter),{hasEntities:r}=Ta(),{isLoading:a}=i.useFilterableFields(),l=h.useMemo(()=>i.getGlobalDateFilterCoverage(t,s),[t,s]),u=!i.getGlobalDateFilter(t.filters)&&l.hasEligibleCards&&!a;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[u&&e.jsx("div",{className:"border-b border-border/60 p-2",children:e.jsxs("button",{type:"button",onClick:()=>n(i.createDefaultGlobalDateFilter()),title:`Applies to ${l.eligibleCardCount} of ${l.totalCardCount} date-aware cards`,className:"flex w-full items-start gap-2 rounded-[4px] px-2 py-1.5 text-left outline-none transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-border",children:[e.jsx(i.CalendarRange,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"text-[12px] font-medium text-foreground",children:"Add global date filter"}),e.jsx("span",{className:"text-[11px] leading-[1.4] text-muted-foreground",children:"One date range across all date-aware cards."})]})]})}),!r&&e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(i.Database,{className:"mb-3 h-10 w-10 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-1 text-[13px] font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Configure a data source for this card to enable filtering."})]}),r&&e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx(i.FilterableFieldsPanel,{context:"filter"})})]})}const Qs=!1;function Fa({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const a=o.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:l}=o.useDashboardActions();a!=null&&a.displayMode;const c=(a==null?void 0:a.toolbarWrap)??!1;return a==null||a.showDownloadButton,e.jsxs("div",{className:"w-[300px]",children:[e.jsxs("div",{className:"p-1",children:[e.jsx(Vt,{icon:i.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(Vt,{icon:o.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(Vt,{icon:i.Pencil,label:"Manage controls",onClick:()=>{n(),r()}})]}),e.jsx("div",{className:"border-t border-border/60"}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Display"}),Qs,e.jsx(Ra,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:c,onCheckedChange:u=>l({toolbarWrap:u===!0})}),Qs]})]})}function Vt({icon:t,label:s,onClick:n}){return e.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left text-[13px] text-foreground transition-colors hover:bg-muted/40",children:[e.jsx(t,{className:"h-3.5 w-3.5 text-muted-foreground"}),s]})}function Ra({id:t,label:s,checked:n,onCheckedChange:r}){return e.jsxs("div",{className:"flex items-center gap-2 rounded-[4px] px-1 py-1 transition-colors hover:bg-muted/40",children:[e.jsx(i.Checkbox,{id:t,checked:n,onCheckedChange:r}),e.jsx(o.Label,{htmlFor:t,className:"cursor-pointer text-[12px] font-normal leading-[1.3]",children:s})]})}function Pa({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:a,settingsContentClassName:l}){var V;const[c,u]=h.useState(null),d=o.useDashboardStore(D=>D.dashboard),m=o.useDashboardStore(D=>D.selectedSheetId),x=o.useDashboardStore(D=>D.showFilters),g=i.useAssistantLayoutStore(D=>D.setPanelOpen),f=o.useDashboardStore(D=>D.actions),{setDocumentInspectorTab:b,setShowFilters:A}=f,S=(V=d.sheets)==null?void 0:V.find(D=>D.id===m),N=o.isDocumentSheet(S),j=h.useCallback(D=>{window.setTimeout(()=>{u(D)},0)},[]),w=h.useCallback(D=>{if(N&&m){D&&b(m,"inputs");return}D&&g("dashboard",!1),A(D)},[N,m,b,g,A]),y=h.useCallback(()=>{w(!0)},[w]),C=h.useCallback(()=>{j("create")},[j]),T=h.useCallback(()=>{j("manage")},[j]);return e.jsxs(e.Fragment,{children:[e.jsx(An,{showFilters:N?!1:x,onShowFiltersChange:w,pickerContent:e.jsx(La,{}),settingsContent:D=>e.jsx(Fa,{onAddFilter:y,onAddControl:C,onManageControls:T,onDismiss:D}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:a,settingsContentClassName:l}),c?N?e.jsx(En,{open:!0,onOpenChange:D=>{D||u(null)},initialMode:c}):e.jsx(Dn,{open:!0,onOpenChange:D=>{D||u(null)},showTrigger:!1,initialMode:c}):null]})}class xt extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function In(t,s){return`${t.replace(/\/$/,"")}${s}`}function xe(t){return encodeURIComponent(t)}function pt(t){const s=new URLSearchParams;Object.entries(t).forEach(([r,a])=>{a!==void 0&&a!==""&&s.set(r,String(a))});const n=s.toString();return n?`?${n}`:""}async function Ma(t){if((t.headers.get("content-type")??"").includes("application/json"))return t.json().catch(()=>({}));const n=await t.text().catch(()=>"");return n?{error:n}:{}}function Tn(t){if(!t||typeof t!="object")return null;const s=t;return typeof s.error=="string"?s.error:null}async function pe(t,s,n,r){const a=await fetch(In(t,n),{cache:(r==null?void 0:r.cache)??"no-store",...r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,...(r==null?void 0:r.headers)||{}}}),l=await a.json().catch(()=>({}));if(!a.ok)throw new xt(Tn(l)||"Briefings API request failed",a.status,l);return l}async function Ln(t,s,n,r){const a=await fetch(In(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!a.ok){const l=await Ma(a);throw new xt(Tn(l)||"Briefing artifact request failed",a.status,l)}return{kind:r,content:await a.text(),contentType:a.headers.get("content-type")??"text/plain",filename:Ba(a.headers.get("content-disposition"))}}function Ba(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function Fn(t,s,n){return pe(t,s,`/v1/briefings${pt({scope:n==null?void 0:n.scope,tenantId:n==null?void 0:n.tenantId,tenantUserId:n==null?void 0:n.tenantUserId,status:n==null?void 0:n.status,page:n==null?void 0:n.page,pageSize:n==null?void 0:n.pageSize,search:n==null?void 0:n.search})}`)}async function Va(t,s,n){return pe(t,s,`/v1/briefings/tenant-summaries${pt({status:n==null?void 0:n.status})}`)}async function as(t,s,n){return pe(t,s,`/v1/briefings/${xe(n)}`)}async function Rn(t,s,n){return pe(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function ft(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function os(t,s,n){return ft(t,s,n,{status:"PAUSED"})}async function is(t,s,n){return ft(t,s,n,{status:"ACTIVE"})}async function ls(t,s,n){return pe(t,s,`/v1/briefings/${xe(n)}`,{method:"DELETE"})}async function cs(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs`,{method:"POST",body:JSON.stringify(r)})}async function Pn(t,s,n){return pe(t,s,"/v1/briefings/preview-plan",{method:"POST",body:JSON.stringify({draft:n})})}async function Mn(t,s,n){return pe(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function Bn(t,s,n){return(await pe(t,s,`/v1/briefings/preview-runs/${xe(n)}`)).previewRun}async function Vn(t,s,n){return pe(t,s,`/v1/briefings/preview-runs/${xe(n)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Oa(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs${pt({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function ds(t,s,n,r){return(await pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`)).run}async function On(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Un(t,s,n,r){return pe(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}`,{method:"DELETE"})}async function Ua(t,s,n,r,a){return Ln(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}/artifact${pt({kind:a})}`,a)}async function $a(t,s,n,r){return Ln(t,s,`/v1/briefings/${xe(n)}/runs/${xe(r)}/evidence`,"evidence")}async function $n(t,s,n){var a;const r=await pe(t,s,"/v1/ai/generate",{method:"POST",body:JSON.stringify({type:"polish-text",context:{text:n}})});if(!r.success||!((a=r.result)!=null&&a.polished))throw new xt(r.error||"Polish returned no result",502,r);return r.result.polished}const _a={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},za={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function Ie(t){return ae(t)}function Js(t){switch(t.type){case"dashboard":return`${t.type}:${t.dashboardId}`;case"dashboard_sheet":case"document_sheet":return`${t.type}:${t.dashboardId}:${t.sheetId}`;case"visual":return`${t.type}:${t.dashboardId}:${t.visualId}`;case"card":return`${t.type}:${t.dashboardId}:${t.cardId}`}}function us(t){var s;if((s=t.title)!=null&&s.trim())return t.title.trim();switch(t.type){case"dashboard":return"Dashboard PDF";case"dashboard_sheet":return"Dashboard sheet PDF";case"document_sheet":return"Paginated report PDF";case"visual":return"Saved visual";case"card":return"Dashboard card"}}function qa(t){var s;switch(t.type){case"dashboard":return((s=t.settings)==null?void 0:s.sheetSelection)==="current"?"Current dashboard sheet":"All dashboard sheets";case"dashboard_sheet":return"Dashboard sheet";case"document_sheet":return"Paginated report";case"visual":return"Saved visual";case"card":return t.format==="csv"?"Card data CSV":"Card render"}}function _n(t){var s;switch(t.type){case"dashboard":case"dashboard_sheet":case"document_sheet":return["pdf"];case"visual":return["pdf","png"];case"card":{const n=(s=t.settings)==null?void 0:s.cardType;return Kn(n)}}}function Ha(t,s){return _n(t).includes(s)?{...Ie(t),format:s,settings:Hn(t.settings,s)}:Ie(t)}function Ka(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...Ie(t),settings:n}}function zn(t){var c,u;if(t.source.type!=="dashboard")return[];const s=t.source.dashboardId,n=t.dashboard,r=[{key:`dashboard:${s}:all`,kind:"dashboard",title:"Full dashboard PDF",detail:"All dashboard sheets",dashboardId:s,formats:["pdf"],defaultFormat:"pdf"}];if(!n)return r;const a=o.getDashboardSheets(n.sheets),l=a.find(d=>d.id===t.selectedSheetId)??a[0];l&&r.push({key:`dashboard_sheet:${s}:${l.id}`,kind:"dashboard_sheet",title:`${Ut(l)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:l.id,formats:["pdf"],defaultFormat:"pdf"});for(const d of n.sheets||[])o.isDocumentSheet(d)&&r.push({key:`document_sheet:${s}:${d.id}`,kind:"document_sheet",title:`${Ut(d)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:d.id,formats:["pdf"],defaultFormat:"pdf"});if(l)for(const d of Gn(l)){if(d.card.type==="text")continue;const m=Kn(d.card.type);r.push({key:`card:${s}:${d.card.id}`,kind:"card",title:d.card.title||"Untitled card",detail:`${Ut(l)} · ${d.card.type}`,dashboardId:s,sheetId:l.id,cardId:d.card.id,cardType:d.card.type,frameId:(c=d.frame)==null?void 0:c.id,cardControlDefinitions:d.card.controls,controlBindings:d.card.controlBindings,tablePreferences:(u=d.card.preferences)==null?void 0:u.tablePrefs,formats:m,defaultFormat:i.getDefaultExportFormat(d.card.type)})}return r}function Qt(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Ga({option:s,format:n,runtime:t.runtime});switch(s.kind){case"dashboard":return{type:"dashboard",dashboardId:s.dashboardId,format:"pdf",title:s.title,settings:r};case"dashboard_sheet":return{type:"dashboard_sheet",dashboardId:s.dashboardId,sheetId:Ot(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:Ot(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:Ot(s.cardId),format:n,title:s.title,settings:r}}}function Ys(t){const s=zn(t),n=s.find(l=>l.kind==="dashboard_sheet"),a=s.find(l=>l.kind==="dashboard")??n;return a?[Qt({option:a,runtime:t.runtime})]:[]}function Ga(t){const s={...Hn(void 0,t.format)},n=t.runtime;return n!=null&&n.theme&&(s.theme=n.theme),t.option.kind==="dashboard"&&(s.sheetSelection="all"),t.option.kind==="dashboard_sheet"&&(s.sheetSelection="current",s.currentSheetId=t.option.sheetId,s.currentSheetName=t.option.title.replace(/\sPDF$/,"")),t.option.kind==="document_sheet"&&(s.currentSheetId=t.option.sheetId,s.currentSheetName=t.option.title.replace(/\sPDF$/,"")),t.option.kind==="card"&&(s.selectedSheetId=t.option.sheetId,s.cardType=t.option.cardType,t.option.cardControlDefinitions&&(s.cardControlDefinitions=ae(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=ae(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=ae(t.option.tablePreferences))),Wa({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Za(s.filterValues,n==null?void 0:n.timezone)),s}function Wa(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Xa({settings:s,option:n,runtime:r});return}const a=n.kind==="dashboard"?"all":"current",l=n.kind==="dashboard"?r.selectedSheetId:n.sheetId,c=i.buildDashboardExecutionSnapshot({dashboard:r.dashboard||void 0,filterValues:r.filterValues,selectedSheetId:l,sheetSelection:a,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap,semanticExecutionPayload:r.semanticExecutionPayload,timezone:r.timezone});s.sheetFilterValues=ae(c.filterValues),s.filterValues=ae(c.filterValues),s.controlValues=ae(c.controlValues),r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions));const u=Qa({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&a==="all"?void 0:l,sheetSelection:a});u&&(s.dashboardInputExecutionSnapshot=ae(u))}function Xa(t){var m,x,g;const{settings:s,option:n,runtime:r}=t,a=n.cardId,l=i.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=ae(l),!a){s.filterValues=ae(l),s.controlValues=ae(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions));return}const c=((m=r.inlineFilterValuesMap)==null?void 0:m[a])||[];c.length>0&&(s.inlineFilterValues=ae(c));const u=i.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:a,interactionStates:r.interactionStates||{},currentDashboardId:(x=r.dashboard)==null?void 0:x.id,semanticExecutionPayload:r.semanticExecutionPayload,filters:r.filters,filterValues:r.filterValues,inlineFilterValuesMap:{...r.inlineFilterValuesMap||{},[a]:c},dashboardControls:r.dashboardControls||r.controlDefinitions,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap,timezone:r.timezone});u?(s.filterValues=ae(u.queryContext.cardFilterValues),s.controlValues=ae(u.queryContext.controlValues),s.controlDefinitions=ae(u.queryContext.controlDefinitions),s.cardControlDefinitions=ae(u.queryContext.cardControlDefinitions),s.controlBindings=ae(u.queryContext.controlBindings)):(s.filterValues=ae(l),s.controlValues={...r.controlValues||{},...((g=r.cardControlValuesMap)==null?void 0:g[a])||{}},r.controlDefinitions&&(s.controlDefinitions=ae(r.controlDefinitions)));const d=Ja({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:c,controlValues:s.controlValues});d&&(s.dashboardInputExecutionSnapshot=ae(d))}function Qa(t){var u;const{option:s,runtime:n}=t,r=n.dashboard;if(!((u=r==null?void 0:r.inputs)!=null&&u.length))return;const a=new Date().toISOString(),l=n.timezone||qn();if(s.kind==="document_sheet"&&s.sheetId)return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:s.sheetId,sheetKind:"document",mode:"document",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:a,timezone:l}).snapshot;const c=t.sheetSelection==="all"?o.getDashboardSheets(r.sheets).map(d=>d.id):t.selectedSheetId?[t.selectedSheetId]:[];if(c.length!==0)return i.buildDashboardSheetsInputExecutionSnapshot({dashboard:r,sheetIds:c,sheetKind:"dashboard",mode:"dashboard",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:a,timezone:l}).snapshot}function Ja(t){var u;const{option:s,runtime:n}=t,r=n.dashboard;if(!((u=r==null?void 0:r.inputs)!=null&&u.length)||!s.cardId)return;const a=Ya(r,s.sheetId,s.cardId),l=t.inlineFilterValues!==void 0?{...n.inlineFilterValuesMap||{},[s.cardId]:t.inlineFilterValues}:n.inlineFilterValuesMap,c=t.filterValues!==void 0?i.applyFilterOverridesToDashboardInputSlots({dashboardInputValues:n.dashboardInputValues,dashboard:r,filterValues:t.filterValues,sheetId:(a==null?void 0:a.sheet.id)||s.sheetId,cardId:s.cardId,sheetKind:"dashboard"}):n.dashboardInputValues;return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:(a==null?void 0:a.sheet.id)||s.sheetId,card:(a==null?void 0:a.card)||null,sheetKind:"dashboard",mode:"visual",runtimeValues:{dashboardInputValues:c,filterValues:t.filterValues??n.filterValues,controlValues:t.controlValues??n.controlValues,inlineFilterValuesMap:l,cardControlValuesMap:n.cardControlValuesMap},generatedAt:new Date().toISOString(),timezone:n.timezone||qn()}).snapshot}function Ya(t,s,n){const r=t.sheets||[],a=s?r.filter(l=>l.id===s):r;for(const l of a)for(const c of Gn(l))if(c.card.id===n)return{sheet:l,card:c.card}}function qn(){return typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Za(t,s){if(!Array.isArray(t))return"";const n=t.filter(r=>!!r&&typeof r=="object"&&typeof r.name=="string");return i.formatFilterLine(n,{timezone:s})}function Hn(t,s){return s==="csv"?{...za,...t}:{..._a,...t}}function Kn(t){return t?i.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function Gn(t){const s=[],n=new Set,r=(a,l)=>{!(a!=null&&a.id)||n.has(a.id)||(n.add(a.id),s.push({card:a,frame:l}))};for(const a of t.cards||[])r(a);for(const a of t.frames||[])for(const l of a.cards||[])r(l,a);return s}function Ot(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function Ut(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function ae(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Wn=["markdown"],eo={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Wn],includeEvidence:!0,includeSql:!0},schedule:{enabled:!1,scheduleExpr:"",timezone:"UTC",status:"ACTIVE"},delivery:{enabled:!1,recipients:[],channels:[],subject:"",message:""},limits:{}};function Xn(t){const s=t.trim();return s.length>0?s:void 0}function to(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ie),output:{...t.output,artifactFormats:[...t.output.artifactFormats]},schedule:{...t.schedule},delivery:{...t.delivery,recipients:t.delivery.recipients.map(s=>({...s})),channels:[...t.delivery.channels],channelConfigs:t.delivery.channelConfigs?{...t.delivery.channelConfigs}:void 0},limits:{...t.limits}}}function so(t){return t.type==="generated_analysis"?t.instruction:t.type==="custom_message"?t.message:""}function Qn(t,s){return t.type==="custom_message"?{type:"custom_message",message:s}:t.type==="none"?{type:"none"}:{type:"generated_analysis",instruction:s}}function ms(t){return Qn(t.body,t.instruction.trim())}function Jn(t){return{artifactFormats:[...t.artifactFormats],includeEvidence:t.includeEvidence,includeSql:t.includeSql,...t.audience?{audience:t.audience}:{},...t.tone?{tone:t.tone}:{},...t.format?{format:t.format}:{}}}function Yn(t){const s={};return t.maxToolCalls!==void 0&&(s.maxToolCalls=t.maxToolCalls),t.maxRows!==void 0&&(s.maxRows=t.maxRows),t.timeoutMs!==void 0&&(s.timeoutMs=t.timeoutMs),Object.keys(s).length>0?s:void 0}function Zn(t,s){if(!t)return;const n=s.reduce((r,a)=>(t[a]!==void 0&&(r[a]=t[a]),r),{});return Object.keys(n).length>0?n:void 0}function er(t){return t.recipients.length===0&&t.channels.length===0?null:{recipients:t.recipients.map(s=>({...s})),channels:[...t.channels],channelConfigs:Zn(t.channelConfigs,t.channels)}}function no(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Wn],includeEvidence:(t==null?void 0:t.includeEvidence)??!0,includeSql:(t==null?void 0:t.includeSql)??!0,audience:t==null?void 0:t.audience,tone:t==null?void 0:t.tone,format:t==null?void 0:t.format}}function ro(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function ao(t){return{enabled:!0,recipients:(t==null?void 0:t.recipients.map(s=>({...s})))??[],channels:t!=null&&t.channels?[...t.channels]:[],subject:"",message:"",channelConfigs:Zn(t==null?void 0:t.channelConfigs,(t==null?void 0:t.channels)??[])}}function oo(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function io(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function $t(t,s,n,r,a){oo(n,r,a)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${a}`})}function tr(t){return lt(eo,t??{})}function lt(t,s){var c,u,d,m;const n=s.instruction??(s.body?so(s.body):t.instruction),r=Qn(s.body?{...s.body}:{...t.body},n),a=(c=s.delivery)!=null&&c.channels?[...s.delivery.channels]:[...t.delivery.channels],l=((u=s.delivery)==null?void 0:u.channelConfigs)??t.delivery.channelConfigs;return{...to(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(Ie):t.attachments.map(Ie),output:{...t.output,...s.output,artifactFormats:(d=s.output)!=null&&d.artifactFormats?[...s.output.artifactFormats]:[...t.output.artifactFormats]},schedule:{...t.schedule,...s.schedule},delivery:{...t.delivery,...s.delivery,recipients:(m=s.delivery)!=null&&m.recipients?s.delivery.recipients.map(x=>({...x})):t.delivery.recipients.map(x=>({...x})),channels:a,channelConfigs:l},limits:{...t.limits,...s.limits}}}function He(t){return{name:t.name,description:t.description??"",instruction:ro(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ie),output:no(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:ao(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function Jt(t){return{name:t.name.trim(),description:Xn(t.description)??null,status:t.schedule.status,scheduleExpr:t.schedule.enabled?t.schedule.scheduleExpr.trim():null,timezone:t.schedule.timezone.trim()||"UTC",source:{...t.source},body:ms(t),attachments:t.attachments.map(Ie),presentation:Jn(t.output),limits:Yn(t.limits),deliveryConfig:er(t.delivery)}}function sr(t){return{name:t.name.trim(),description:Xn(t.description)??null,status:t.schedule.status,scheduleExpr:t.schedule.enabled?t.schedule.scheduleExpr.trim():null,timezone:t.schedule.timezone.trim()||"UTC",source:{...t.source},body:ms(t),attachments:t.attachments.map(Ie),presentation:Jn(t.output),limits:Yn(t.limits),deliveryConfig:er(t.delivery)}}function Yt(t){var r,a,l,c,u;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=ms(t);if(n.type!=="none"&&!t.instruction.trim()&&s.push({field:"instruction",message:"Instruction is required"}),n.type==="none"&&t.attachments.length===0&&s.push({field:"body",message:"Add briefing instructions, a custom message, or at least one attachment."}),t.source.type==="dashboard"&&!t.source.dashboardId.trim()&&s.push({field:"source.dashboardId",message:"Dashboard source requires a dashboard id"}),t.output.artifactFormats.length===0&&s.push({field:"output.artifactFormats",message:"Choose at least one output format"}),t.schedule.timezone.trim()||s.push({field:"schedule.timezone",message:"Timezone is required"}),t.schedule.enabled&&!t.schedule.scheduleExpr.trim()&&s.push({field:"schedule.scheduleExpr",message:"Schedule expression is required when scheduling is enabled"}),t.delivery.recipients.length>0||t.delivery.channels.length>0){if((t.delivery.channels.length===0||t.delivery.channels.some(m=>m!=="SLACK"))&&t.delivery.recipients.length===0&&s.push({field:"delivery.recipients",message:"Add at least one recipient or remove delivery channels"}),t.delivery.channels.length===0&&s.push({field:"delivery.channels",message:"Choose at least one delivery channel or remove recipients"}),t.delivery.recipients.forEach((m,x)=>{m.type==="email"&&!io(m.address)&&s.push({field:`delivery.recipients.${x}.address`,message:"Email recipient address is invalid"})}),t.delivery.channels.includes("WEBHOOK")){const m=(r=t.delivery.channelConfigs)==null?void 0:r.WEBHOOK;(l=(a=m==null?void 0:m.webhookConfig)==null?void 0:a.url)!=null&&l.trim()||s.push({field:"delivery.channelConfigs.WEBHOOK.webhookConfig.url",message:"Webhook URL is required for webhook delivery"})}if(t.delivery.channels.includes("SLACK")){const m=(u=(c=t.delivery.channelConfigs)==null?void 0:c.SLACK)==null?void 0:u.slackConfig;((m==null?void 0:m.destination.type)!=="channel"||!m.destination.channelId.trim())&&s.push({field:"delivery.channelConfigs.SLACK.slackConfig.destination.channelId",message:"Choose a Slack channel"})}}return $t(s,"maxToolCalls",t.limits.maxToolCalls,1,100),$t(s,"maxRows",t.limits.maxRows,1,1e5),$t(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const tt="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function lo({attachment:t,open:s,onOpenChange:n,onChange:r,children:a}){const l=_n(t),c=t.settings||{},u=t.format==="csv",d=m=>{r(Ka(t,m))};return e.jsxs(o.Popover,{open:s,onOpenChange:n,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:a}),e.jsxs(o.PopoverContent,{align:"start",className:"z-[60] w-[320px] space-y-3 p-3",onOpenAutoFocus:m=>m.preventDefault(),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:o.cn(tt,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:us(t)})]}),l.length>1?e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Format"}),e.jsxs(o.Select,{value:t.format,onValueChange:m=>r(Ha(t,m)),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsx(o.SelectContent,{children:l.map(m=>e.jsx(o.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(uo,{settings:c,onChange:d}):e.jsx(co,{settings:c,onChange:d})]})]})}function co({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Page size"}),e.jsxs(o.Select,{value:t.pageSize||"letter",onValueChange:n=>s({pageSize:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:"letter",children:"Letter"}),e.jsx(o.SelectItem,{value:"legal",children:"Legal"}),e.jsx(o.SelectItem,{value:"a4",children:"A4"}),e.jsx(o.SelectItem,{value:"a3",children:"A3"}),e.jsx(o.SelectItem,{value:"tabloid",children:"Tabloid"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Orientation"}),e.jsxs(o.Select,{value:t.orientation||"portrait",onValueChange:n=>s({orientation:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:"portrait",children:"Portrait"}),e.jsx(o.SelectItem,{value:"landscape",children:"Landscape"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(ct,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(ct,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function uo({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:o.cn(tt,"mb-1 block"),children:"Delimiter"}),e.jsxs(o.Select,{value:t.delimiter||",",onValueChange:n=>s({delimiter:n}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{children:[e.jsx(o.SelectItem,{value:",",children:"Comma"}),e.jsx(o.SelectItem,{value:";",children:"Semicolon"}),e.jsx(o.SelectItem,{value:" ",children:"Tab"})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(ct,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(ct,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function ct({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-foreground/80",children:[e.jsx(i.Checkbox,{checked:s,onCheckedChange:r=>n(r===!0)}),e.jsx("span",{children:t})]})}function mo({attachments:t,onChange:s,onAdd:n,disabled:r}){const a=t.length===0;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{type:"button",disabled:r,onClick:n,"aria-label":a?"Attach files":"Add another attachment",className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Paperclip,{className:"h-3 w-3"}),a?"Attach":null]}),t.map((l,c)=>e.jsx(ho,{attachment:l,disabled:r,onUpdate:u=>{const d=[...t];d[c]=u,s(d)},onRemove:()=>s(t.filter((u,d)=>d!==c))},`${l.type}:${c}:${us(l)}`)),a?null:e.jsxs("button",{type:"button",disabled:r,onClick:n,className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"Add"]})]})}function ho({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[a,l]=h.useState(!1),c=us(t),u=qa(t),d=t.format.toUpperCase();return e.jsxs("span",{className:o.cn("group inline-flex h-6 items-center gap-1 rounded-control border border-border bg-background pl-1.5 pr-0.5 text-[11px] text-foreground/80",a&&"border-ring "),title:u?`${c} · ${u}`:c,children:[e.jsx(lo,{attachment:t,open:a,onOpenChange:l,onChange:n,children:e.jsxs("button",{type:"button",disabled:s,className:"inline-flex max-w-[180px] items-center gap-1 disabled:opacity-50",children:[e.jsx(xo,{format:t.format,className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate font-medium text-foreground",children:c}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground/70",children:d})]})}),e.jsx("button",{type:"button",disabled:s,onClick:r,className:"inline-flex h-4 w-4 items-center justify-center rounded-control text-muted-foreground/70 hover:bg-muted hover:text-foreground/80 disabled:opacity-50","aria-label":`Remove ${c}`,children:e.jsx(K.X,{className:"h-2.5 w-2.5"})})]})}function xo({format:t,className:s}){const n=t==="csv"?i.FileSpreadsheet:i.FileText;return e.jsx(n,{className:o.cn(s)})}const po="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function fo({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:a,runtime:l,selectedAttachments:c,onSubmit:u}){const d=h.useMemo(()=>zn({source:n,dashboard:r,selectedSheetId:a}),[n,r,a]),[m,x]=h.useState([]);h.useEffect(()=>{if(!t)return;const T=[];for(const V of c){const D=Js(V),F=d.find(U=>U.formats.some(G=>{const B=Qt({option:U,format:G,runtime:l});return Js(B)===D}));F&&T.push({optionKey:F.key,format:V.format??F.defaultFormat})}x(T)},[t,d,c,l]);const g=h.useMemo(()=>new Set(m.map(T=>T.optionKey)),[m]),f=h.useMemo(()=>{const T={};for(const V of m)T[V.optionKey]=V.format;return T},[m]),b=(T,V)=>{x(D=>D.some(U=>U.optionKey===T)?D.filter(U=>U.optionKey!==T):[...D,{optionKey:T,format:V}])},A=(T,V)=>{x(D=>D.map(F=>F.optionKey===T?{...F,format:V}:F))},S=()=>{const T=[];for(const V of m){const D=d.find(F=>F.key===V.optionKey);D&&T.push(Qt({option:D,format:V.format,runtime:l}))}u(T),s(!1)},N=()=>s(!1),j=h.useMemo(()=>d.filter(T=>T.kind==="dashboard"||T.kind==="dashboard_sheet"),[d]),w=h.useMemo(()=>d.filter(T=>T.kind==="document_sheet"),[d]),y=h.useMemo(()=>d.filter(T=>T.kind==="card"),[d]),C=m.length;return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"flex max-h-[80vh] w-[min(560px,calc(100vw-32px))] max-w-none flex-col gap-0 rounded-card p-0",showCloseButton:!0,children:[e.jsxs(i.DialogHeader,{className:"border-b border-border px-4 py-3 text-left",children:[e.jsx(i.DialogTitle,{className:"text-[14px] font-semibold leading-5",children:"Add attachments"}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Choose what gets sent with this briefing."})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:n.type!=="dashboard"?e.jsx("div",{className:"rounded-card border border-dashed border-border px-3 py-3 text-[12px] leading-[1.55] text-muted-foreground",children:"Attachments are available when authoring from a dashboard."}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(_t,{label:"Dashboard",options:j,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A}),e.jsx(_t,{label:"Paginated reports",options:w,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A,emptyText:"No paginated report sheets are available."}),e.jsx(_t,{label:"Current sheet cards",options:y,selectedOptionKeys:g,formatByOptionKey:f,onToggle:b,onFormatChange:A,emptyText:"No exportable cards are available on the current dashboard sheet."})]})}),e.jsxs(i.DialogFooter,{className:"flex flex-row items-center justify-between gap-2 border-t border-border px-4 py-3 sm:justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:C===0?"Nothing selected":`${C} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(o.Button,{type:"button",variant:"outline",size:"xs",onClick:N,children:"Cancel"}),e.jsx(o.Button,{type:"button",size:"xs",onClick:S,disabled:n.type!=="dashboard",children:C>0?`Add ${C} ${C===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function _t({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:a,onFormatChange:l,emptyText:c}){return e.jsxs("section",{children:[e.jsx("div",{className:o.cn(po,"mb-2"),children:t}),s.length===0?e.jsx("div",{className:"rounded-card border border-dashed border-border px-3 py-2 text-[12px] text-muted-foreground",children:c||"Nothing available."}):e.jsx("div",{className:"divide-y divide-border rounded-card border border-border",children:s.map(u=>{const d=n.has(u.key),m=r[u.key]??u.defaultFormat;return e.jsxs("div",{className:o.cn("flex w-full items-start gap-2 px-3 py-2 transition-colors hover:bg-muted "),children:[e.jsxs("button",{type:"button",role:"checkbox","aria-checked":d,onClick:()=>a(u.key,u.defaultFormat),className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[e.jsx(go,{selected:d}),e.jsx(bo,{kind:u.kind,format:m,cardType:u.cardType,className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:u.title}),e.jsx("span",{className:"mt-0.5 block truncate text-[11px] text-muted-foreground",children:u.detail})]})]}),e.jsx("div",{className:"shrink-0",children:u.formats.length>1?e.jsxs(o.Select,{value:m,onValueChange:x=>l(u.key,x),children:[e.jsx(o.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:x=>x.stopPropagation(),children:e.jsx(o.SelectValue,{})}),e.jsx(o.SelectContent,{children:u.formats.map(x=>e.jsx(o.SelectItem,{value:x,children:x.toUpperCase()},x))})]}):e.jsx("span",{className:"inline-flex h-6 items-center text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:m})})]},u.key)})})]})}function go({selected:t}){return e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-0.5 flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control border transition-colors",t?"border-primary bg-primary":"border-border "),children:t?e.jsx(o.Check,{className:"h-2.5 w-2.5 text-primary-foreground",strokeWidth:3}):null})}function bo({kind:t,format:s,cardType:n,className:r}){const a=s==="csv"?i.FileSpreadsheet:t==="dashboard"?i.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?me.Rows3:o.ChartColumn:i.FileText;return e.jsx(a,{className:r})}const jo=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,yo=250;function Ye(t){switch(t.type){case"email":return`email:${t.address.toLowerCase()}`;case"user":return`user:${t.userId}`;case"tenant_user":return`tenant_user:${t.tenantUserId}`;case"group":return`group:${t.groupId}`}}function vo(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function No(t){return t.type==="group"?t.groupId:null}function Ze(t){return(t==null?void 0:t.trim().toLowerCase())||null}function Zs(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function en(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function tn({value:t,onChange:s,className:n,disabled:r=!1,prefix:a,placeholder:l}){const c=h.useRef(null),[u,d]=h.useState(!1),[m,x]=h.useState(""),[g,f]=h.useState(0),[b,A]=h.useState(()=>new Map),[S,N]=h.useState(()=>new Map),[j,w]=h.useState("people"),y=i.useDebounce(m,yo),{currentUser:C}=i.useCurrentUserInfo(),T=(C==null?void 0:C.type)==="tenant",{users:V,isLoading:D}=i.useUnifiedUsers({search:y,active:!0,type:T?"tenant":"all",tenantId:T?C.tenantId:void 0,limit:25}),{groups:F,isLoading:U}=i.useGroups({search:y,type:T?"TENANT_GROUP":"all",tenantId:T?C.tenantId:void 0,limit:25}),G=h.useMemo(()=>new Set(t.map(Ye)),[t]),B=h.useMemo(()=>new Set(t.map(vo).filter(I=>!!I)),[t]),_=h.useMemo(()=>new Set(t.map(No).filter(I=>!!I)),[t]),$=h.useMemo(()=>{const I=new Map(b);return V.forEach(P=>{I.set(P.id,Zs(P))}),C!=null&&C.id&&I.set(C.id,{kind:"user",id:C.id,name:C.name||C.email||"User",email:C.email||"",type:C.type}),I},[b,V,C]),M=h.useMemo(()=>{const I=new Set;return t.forEach(P=>{var H;if(P.type==="email"){const te=Ze(P.address);te&&I.add(te);return}if(P.type==="group")return;const fe=P.type==="tenant_user"?P.tenantUserId:P.userId,E=Ze((H=$.get(fe))==null?void 0:H.email);E&&I.add(E)}),I},[$,t]),Q=h.useMemo(()=>{const I=new Map(S);return F.forEach(P=>{I.set(P.id,en(P))}),I},[S,F]),ee=h.useMemo(()=>V.filter(I=>{if(B.has(I.id))return!1;const P=Ze(I.email);return P&&M.has(P)?!1:T?I.type==="tenant"&&I.tenantId===(C==null?void 0:C.tenantId):!0}).map(Zs),[V,B,M,T,C==null?void 0:C.tenantId]),L=h.useMemo(()=>ee.filter(I=>I.type==="organization"),[ee]),W=h.useMemo(()=>ee.filter(I=>I.type==="tenant"),[ee]),k=h.useMemo(()=>F.filter(I=>_.has(I.id)?!1:(C==null?void 0:C.type)==="tenant"?I.type==="TENANT_GROUP"&&I.tenantId===C.tenantId:!0).map(en),[F,_,C==null?void 0:C.type,C==null?void 0:C.tenantId]),oe=h.useMemo(()=>T?[{key:"people",label:"People",count:W.length},{key:"groups",label:"Groups",count:k.length}]:[{key:"people",label:"People",count:L.length},{key:"tenant_users",label:"Tenant users",count:W.length},{key:"groups",label:"Groups",count:k.length}],[k.length,T,L.length,W.length]),Y=h.useMemo(()=>j==="groups"?[]:j==="tenant_users"||T?W:L,[j,T,L,W]),X=h.useMemo(()=>j==="groups"?k:[],[j,k]),he=h.useMemo(()=>[...Y,...X],[Y,X]),ye=he.length===0?0:Math.min(g,he.length-1),ie=m.trim(),z=jo.test(ie),Pe=Ze(ie),ve=Pe?M.has(Pe):!1,ke=D||U,Se=I=>{G.has(Ye(I))||(s([...t,I]),x(""),f(0))},q=I=>{s(t.filter(P=>Ye(P)!==I))},Ne=()=>{!z||ve||Se({type:"email",address:ie})},O=I=>{const P=Ze(I.email);P&&M.has(P)||(A(fe=>{const E=new Map(fe);return E.set(I.id,I),E}),Se(I.type==="tenant"?{type:"tenant_user",tenantUserId:I.id}:{type:"user",userId:I.id}))},ne=I=>{N(P=>{const fe=new Map(P);return fe.set(I.id,I),fe}),Se({type:"group",groupId:I.id})},qe=I=>{if(I.key==="Enter"){if(I.preventDefault(),z&&!ve){Ne();return}const P=he[ye];if((P==null?void 0:P.kind)==="user"){O(P);return}if((P==null?void 0:P.kind)==="group"){ne(P);return}}else if(I.key==="ArrowDown")I.preventDefault(),f(P=>Math.min(P+1,Math.max(he.length-1,0)));else if(I.key==="ArrowUp")I.preventDefault(),f(P=>Math.max(P-1,0));else if(I.key==="Escape")d(!1);else if(I.key==="Backspace"&&m.length===0){const P=t[t.length-1];P&&q(Ye(P))}},Oe=t.map(I=>{const P=Ye(I);if(I.type==="email")return{key:P,label:I.name||I.address,icon:e.jsx(i.AtSign,{className:"h-3 w-3"}),onRemove:()=>q(P)};if(I.type==="group"){const H=Q.get(I.groupId);return{key:P,label:(H==null?void 0:H.name)||"Group",icon:e.jsx(ns,{className:"h-3 w-3"}),onRemove:()=>q(P)}}const fe=I.type==="tenant_user"?I.tenantUserId:I.userId,E=$.get(fe);return{key:P,label:(E==null?void 0:E.name)||(E==null?void 0:E.email)||"User",icon:e.jsx(i.User,{className:"h-3 w-3"}),onRemove:()=>q(P)}});return e.jsx("div",{className:o.cn("relative",n),children:e.jsxs(o.Popover,{open:u&&!r,onOpenChange:d,children:[e.jsx(o.Anchor2,{asChild:!0,children:e.jsxs("div",{className:o.cn("flex min-h-9 cursor-text flex-wrap items-center gap-1.5 rounded-control border bg-background px-2 py-1.5 transition-colors",u?"border-ring ring-2 ring-ring/10":"border-border hover:border-border",r&&"cursor-not-allowed opacity-60"),onClick:()=>{var I;r||((I=c.current)==null||I.focus(),d(!0))},children:[a?e.jsx("span",{className:"inline-flex shrink-0 items-center text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:a}):null,Oe.map(I=>e.jsx(wo,{icon:I.icon,label:I.label,onRemove:I.onRemove},I.key)),e.jsx("input",{ref:c,className:"h-6 min-w-[160px] flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground/70 disabled:cursor-not-allowed",value:m,disabled:r,placeholder:l??(t.length>0?"Add more...":"Add people, emails, or groups"),onChange:I=>{x(I.target.value),f(0),d(!0)},onFocus:()=>d(!0),onKeyDown:qe})]})}),e.jsx(o.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:I=>I.preventDefault(),className:o.cn("z-[60] w-[var(--radix-popover-trigger-width)] min-w-[360px] rounded-card border border-border bg-background p-0 text-foreground shadow-md outline-none","max-h-[min(320px,var(--radix-popover-content-available-height))] overflow-y-auto"),children:e.jsx(Co,{activeIndex:ye,activeFilter:j,emailAlreadyAdded:ve,filters:oe,groupSuggestions:X,loading:ke,onAddEmail:Ne,onFilterChange:I=>{w(I),f(0)},onGroupClick:ne,onUserClick:O,orderedSuggestions:he,query:ie,queryIsEmail:z,userSuggestions:Y,viewerType:C==null?void 0:C.type})})]})})}function wo({icon:t,label:s,onRemove:n}){return e.jsxs("span",{className:"inline-flex h-6 max-w-full items-center gap-1.5 rounded-control border border-border bg-muted pl-1.5 pr-1 text-[12px]",children:[e.jsx("span",{className:"shrink-0 text-muted-foreground",children:t}),e.jsx("span",{className:"min-w-0 truncate text-foreground",children:s}),e.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),n()},className:"rounded-control p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Remove ${s}`,children:e.jsx(K.X,{className:"h-2.5 w-2.5"})})]})}function Co({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:a,loading:l,onAddEmail:c,onFilterChange:u,onGroupClick:d,onUserClick:m,orderedSuggestions:x,query:g,queryIsEmail:f,userSuggestions:b,viewerType:A}){const S=!l&&x.length===0&&!(f&&!n);return e.jsxs("div",{className:"py-1 text-[13px]",children:[e.jsx("div",{className:"flex items-center gap-1 border-b border-border/60 px-2 pb-1",children:r.map(N=>e.jsxs("button",{type:"button",onClick:()=>u(N.key),className:o.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===N.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:N.label}),e.jsx("span",{className:o.cn("tabular-nums",s===N.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:N.count})]},N.key))}),l?e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-[12px] text-muted-foreground",children:[e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Searching"]}):null,b.length>0?e.jsx(sn,{heading:"People",children:b.map(N=>{var w;const j=x.indexOf(N);return e.jsx(nn,{active:j===t,avatar:e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground/80",children:(w=(N.name||N.email||"?")[0])==null?void 0:w.toUpperCase()}),detail:N.name?N.email:void 0,tag:N.type==="organization"?"Org user":"Tenant user",viewerType:A,title:N.name||N.email,onClick:()=>m(N)},N.id)})}):null,a.length>0?e.jsx(sn,{heading:"Groups",children:a.map(N=>{const j=x.indexOf(N);return e.jsx(nn,{active:j===t,avatar:e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-control border border-border bg-muted text-muted-foreground",children:e.jsx(ns,{className:"h-3 w-3"})}),detail:N.memberCount!==void 0?`${N.memberCount} member${N.memberCount===1?"":"s"}`:N.description??void 0,tag:N.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:A,title:N.name,onClick:()=>d(N)},N.id)})}):null,f&&!n?e.jsx("div",{className:"border-t border-border px-1.5 py-1.5",children:e.jsxs("button",{type:"button",onClick:c,className:"flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left hover:bg-muted",children:[e.jsx(yn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13px] text-foreground",children:["Send to ",e.jsx("span",{className:"font-medium",children:g})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Add as external email"})]}),e.jsx("span",{className:"ml-auto shrink-0 rounded-control border border-border bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"Enter"})]})}):null,S?e.jsx("div",{className:"px-2.5 py-6 text-center text-[12px] text-muted-foreground",children:g?"No people or groups match. Enter a valid email to add an external recipient.":"Pick a category above or type to search people, groups, or external emails."}):null]})}function sn({heading:t,children:s}){return e.jsxs("div",{className:"px-1.5 pb-1",children:[e.jsx("div",{className:"px-1.5 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t}),s]})}function nn({active:t,avatar:s,detail:n,onClick:r,tag:a,title:l,viewerType:c}){return e.jsxs("button",{type:"button",onClick:r,className:o.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left",t?"bg-muted ":"hover:bg-muted "),children:[s,e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[13px] text-foreground",children:l}),n?e.jsx("span",{className:"block truncate text-[11px] text-muted-foreground",children:n}):null]}),c==="organization"?e.jsx("span",{className:"shrink-0 rounded-control border border-border bg-background px-1.5 py-0.5 text-[10px] text-muted-foreground",children:a}):null]})}function dt(t){return t==="SUCCESS"||t==="FAILED"}function ut(t){return t==="QUEUED"||t==="RUNNING"}function Zt({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}){const[m,x]=h.useState(null),[g,f]=h.useState("idle"),b=h.useRef(null),A=h.useRef({fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d});h.useEffect(()=>{A.current={fetchRun:a,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}},[a,u,l,c,d]);const S=h.useCallback(()=>{x(null),f("idle")},[]),N=h.useCallback(()=>{b.current=null},[]),j=h.useCallback(y=>{var C,T;if(A.current.onRun(y),dt(y.status)){b.current=y.id,x(null),f("terminal"),(T=(C=A.current).onTerminalRun)==null||T.call(C,y);return}if(ut(y.status)){b.current=null,x(y.id),f("polling");return}x(null),f("idle")},[]),w=h.useCallback(y=>{b.current!==y&&(x(y),f("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(b.current===m){x(null),f("terminal");return}let y=!1,C=!1,T=null;const V=Date.now(),D=async()=>{var F,U,G,B,_,$;if(!(y||C)){if(Date.now()-V>r){x(M=>M===m?null:M),f("timed_out"),(U=(F=A.current).onTimeout)==null||U.call(F,m);return}C=!0;try{const M=await A.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(y)return;if(A.current.onRun(M),dt(M.status)){b.current=M.id,x(Q=>Q===M.id?null:Q),f("terminal"),(B=(G=A.current).onTerminalRun)==null||B.call(G,M);return}if(!ut(M.status)){x(Q=>Q===M.id?null:Q),f("idle");return}T=window.setTimeout(D,n)}catch(M){y||(f("error"),($=(_=A.current).onError)==null||$.call(_,M))}finally{C=!1}}};return f("polling"),D(),()=>{y=!0,T&&window.clearTimeout(T)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&g==="polling",resetTerminalRun:N,startRun:j,startRunId:w,status:g,stop:S}}function rn({label:t,description:s,checked:n,onSelect:r,name:a}){return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[e.jsx("input",{type:"radio",name:a,checked:n,onChange:r,className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-0.5 inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border",n?"border-primary":"border-border"),children:n?e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}):null}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] text-foreground",children:t}),e.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:s})]})]})}function So({includeEvidence:t,includeSql:s,includeHtml:n,onChange:r}){const a=[t,s,n].filter(Boolean).length;return e.jsxs(o.Popover,{children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Output options",children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"Output options",e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",a,"/3"]}),e.jsx(K.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(o.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-[320px] rounded-card border-border bg-popover p-0 text-popover-foreground",children:[e.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output options"}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:"Choose what gets included in the rendered briefing."})]}),e.jsxs("div",{className:"space-y-2.5 px-3 py-2.5",children:[e.jsx(zt,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:l=>r("evidence",l)}),e.jsx(zt,{label:"Include SQL in evidence",description:"Show the SQL the briefing ran. Useful for debugging or for a technical audience.",checked:s,onChange:l=>r("sql",l)}),e.jsx(zt,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:l=>r("html",l)})]})]})]})}function zt({label:t,description:s,checked:n,onChange:r}){return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:a=>r(a.target.checked),className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-[2px] flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control border",n?"border-primary bg-primary":"border-border"),children:n?e.jsx(o.Check,{className:"h-2 w-2 text-primary-foreground",strokeWidth:3.5}):null}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:t}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:s})]})]})}const es=`Tell me what changed in the business and what is driving it.
|
|
62
62
|
|
|
63
63
|
Watch:
|
|
64
64
|
- Top-line movement versus the previous comparable period
|