react-semaphor 0.1.390 → 0.1.392

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +120 -252
  3. package/dist/brand-studio/index.cjs +1 -1
  4. package/dist/brand-studio/index.js +7 -7
  5. package/dist/chunks/analyze-result-contract-C9Gv2_qW.js +1585 -0
  6. package/dist/chunks/analyze-result-contract-Zgg-Bbpj.js +1 -0
  7. package/dist/chunks/{braces--20GzUQh.js → braces-8TRlDwDw.js} +1 -1
  8. package/dist/chunks/{braces-C0Vh_Mft.js → braces-D2tStQjF.js} +1 -1
  9. package/dist/chunks/{calendar-preferences-dialog-B-VsxhsA.js → calendar-preferences-dialog-49fcEPXS.js} +4 -4
  10. package/dist/chunks/{calendar-preferences-dialog-DE67Z3oQ.js → calendar-preferences-dialog-DwLeBLy2.js} +1 -1
  11. package/dist/chunks/dashboard-briefing-launcher-CgkSKkZR.js +80 -0
  12. package/dist/chunks/{dashboard-briefing-launcher-BIj3X7b3.js → dashboard-briefing-launcher-cgPKz1yX.js} +252 -252
  13. package/dist/chunks/dashboard-controls-D12ZSUP_.js +52 -0
  14. package/dist/chunks/{dashboard-controls-BXxucM4f.js → dashboard-controls-VMFm3OP4.js} +87 -87
  15. package/dist/chunks/{dashboard-json-C6oZuipD.js → dashboard-json-C-GG5yC7.js} +4 -4
  16. package/dist/chunks/{dashboard-json-BNwshkK2.js → dashboard-json-CvK0oI24.js} +1 -1
  17. package/dist/chunks/{edit-dashboard-visual-CmfrI_L3.js → edit-dashboard-visual-B5KB7dx4.js} +977 -977
  18. package/dist/chunks/edit-dashboard-visual-ql99faTz.js +178 -0
  19. package/dist/chunks/{index-icb12JV1.js → index-CQmKDEbe.js} +735 -741
  20. package/dist/chunks/{index-4W_ElSBJ.js → index-DXCBPLDu.js} +218 -223
  21. package/dist/chunks/{layout-grid-B7-klXiK.js → layout-grid-C0OI-MRn.js} +1 -1
  22. package/dist/chunks/{layout-grid-DV89AC9_.js → layout-grid-CiubineE.js} +1 -1
  23. package/dist/chunks/{palette-Dj-dgPYh.js → palette-C4KTXOug.js} +1 -1
  24. package/dist/chunks/{palette-5IwhMbSF.js → palette-Cp1hqZtm.js} +1 -1
  25. package/dist/chunks/{save-C5fwVdTF.js → save-C__QggEE.js} +1 -1
  26. package/dist/chunks/{save-16C6YSW2.js → save-DgMfP0j8.js} +1 -1
  27. package/dist/chunks/{search-0LmWwZzW.js → search-BHsQIWBV.js} +17 -7
  28. package/dist/chunks/{search-Dq1Mbb03.js → search-DNCejM7Z.js} +9 -4
  29. package/dist/chunks/source-identity-uMaUe036.js +1 -0
  30. package/dist/chunks/{source-identity-CN4xiyKJ.js → source-identity-y0VSSreA.js} +33 -15
  31. package/dist/chunks/{switch-bdJp0Bkw.js → switch-B79Hn4Qh.js} +27 -32
  32. package/dist/chunks/{switch-DUdaHFZQ.js → switch-BXQAlSuW.js} +637 -647
  33. package/dist/chunks/use-create-flow-overlay-state-7MFN3PWX.js +21 -0
  34. package/dist/chunks/{use-create-flow-overlay-state-YvqCp6Zo.js → use-create-flow-overlay-state-Bw5LRkf9.js} +93 -92
  35. package/dist/chunks/{validators-CHPH6ORs.js → validators-4EGCWWga.js} +1 -1
  36. package/dist/chunks/{validators-lWo8m0Q7.js → validators-CPtkrola.js} +1 -1
  37. package/dist/chunks/{x-B_cx7LwM.js → x-B6ghREd2.js} +10 -5
  38. package/dist/chunks/{x-IdR_js6f.js → x-CXDkqdur.js} +28 -18
  39. package/dist/dashboard/index.cjs +1 -1
  40. package/dist/dashboard/index.js +1 -1
  41. package/dist/dashboard-authoring/index.cjs +1 -1
  42. package/dist/dashboard-authoring/index.js +3 -3
  43. package/dist/data-app-builder/index.cjs +13 -13
  44. package/dist/data-app-builder/index.js +11 -11
  45. package/dist/data-app-sdk/index.cjs +5 -5
  46. package/dist/data-app-sdk/index.js +1698 -1121
  47. package/dist/data-app-sdk-adapters/index.cjs +1 -1
  48. package/dist/data-app-sdk-adapters/index.js +6 -7
  49. package/dist/data-app-sdk-validation/index.cjs +1 -1
  50. package/dist/data-app-sdk-validation/index.js +3 -3
  51. package/dist/index.cjs +1 -1
  52. package/dist/index.js +13 -13
  53. package/dist/surfboard/index.cjs +1 -1
  54. package/dist/surfboard/index.js +2 -2
  55. package/dist/types/analytics-protocol.d.ts +2107 -43
  56. package/dist/types/dashboard-assistant.d.ts +3 -1
  57. package/dist/types/data-app-sdk-adapters.d.ts +1 -1
  58. package/dist/types/data-app-sdk-validation.d.ts +4 -2
  59. package/dist/types/data-app-sdk.d.ts +73 -5
  60. package/package.json +2 -1
  61. package/src/data-app-sdk/README.md +55 -0
  62. package/dist/chunks/analyze-result-contract-CtXfp3nv.js +0 -1
  63. package/dist/chunks/analyze-result-contract-DuhlklhI.js +0 -102
  64. package/dist/chunks/dashboard-briefing-launcher-Czx6BcXW.js +0 -80
  65. package/dist/chunks/dashboard-controls-BP-DcPFs.js +0 -52
  66. package/dist/chunks/edit-dashboard-visual-BAprin3J.js +0 -178
  67. package/dist/chunks/source-identity-C-xaeE_I.js +0 -1
  68. package/dist/chunks/use-create-flow-overlay-state-BIHKf_XK.js +0 -21
@@ -0,0 +1,80 @@
1
+ "use strict";const e=require("react/jsx-runtime"),h=require("react"),i=require("./index-DXCBPLDu.js"),o=require("./switch-B79Hn4Qh.js"),ss=require("./layout-grid-C0OI-MRn.js"),K=require("./x-B6ghREd2.js"),me=require("./use-create-flow-overlay-state-7MFN3PWX.js");require("./analyze-result-contract-Zgg-Bbpj.js");const Ae=require("./search-DNCejM7Z.js"),Gs=require("./date-formatter-B4EBSe9C.js");require("./index-DRlMUglg.js");require("react-dom");/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Qr=K.createLucideIcon("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
7
+ * @license lucide-react v0.453.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Jr=K.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
12
+ * @license lucide-react v0.453.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Ws=K.createLucideIcon("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/**
17
+ * @license lucide-react v0.453.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const Yr=K.createLucideIcon("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/**
22
+ * @license lucide-react v0.453.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Zr=K.createLucideIcon("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/**
27
+ * @license lucide-react v0.453.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const yn=K.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
32
+ * @license lucide-react v0.453.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const Wt=K.createLucideIcon("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
37
+ * @license lucide-react v0.453.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const ea=K.createLucideIcon("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/**
42
+ * @license lucide-react v0.453.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const vn=K.createLucideIcon("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
47
+ * @license lucide-react v0.453.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const Nn=K.createLucideIcon("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
52
+ * @license lucide-react v0.453.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const ns=K.createLucideIcon("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/**
57
+ * @license lucide-react v0.453.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
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.
62
+
63
+ Watch:
64
+ - Top-line movement versus the previous comparable period
65
+ - KPI changes using the measures available in this dashboard or project
66
+ - Largest positive and negative drivers using available breakdown fields
67
+ - Notable changes by any available segment, product, customer, region, account, channel, location, or movement type
68
+ - Important outliers, missing context, or data gaps that affect the read
69
+
70
+ Include in the briefing:
71
+ - Executive summary in plain English
72
+ - KPI comparison with current, previous, delta, and percent change when available
73
+ - Driver table or chart when useful
74
+ - 2-3 recommended next actions
75
+ - Evidence link rather than raw SQL in the main body`,an=`Hi team,
76
+
77
+ Sharing this dashboard. The PDF below has the selected dashboard view and current filters applied.
78
+
79
+ Reply if you have questions.`;function ko(t,s,n){const r=t.includes("markdown")?t.filter(a=>a!==s):["markdown"];return n?Array.from(new Set([...r,s])):r}const qt=[{label:"Email report",description:"Email body with dashboard attachments",seedsDashboardAttachment:!0,available:t=>t.type==="dashboard",draft:(t,s)=>({name:"Dashboard Email Report",instruction:an,body:{type:"custom_message",message:an},attachments:t.type==="dashboard"?(s==null?void 0:s.attachments)??[]:void 0,output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["EMAIL"]}})},{label:"Business review",description:"Executive movement and drivers using available fields",draft:()=>({name:"Weekly Business Briefing",instruction:es,body:{type:"generated_analysis",instruction:es},attachments:[],output:{includeEvidence:!0,includeSql:!0}})}],re="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",et="inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",Re="inline-flex h-7 items-center gap-1.5 rounded-control border border-border bg-background px-2.5 text-[12px] text-foreground hover:bg-muted disabled:opacity-50",on="inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",Ht="z-[70]";function Do({scheduleExpr:t,timezone:s,onScheduleChange:n}){const r=h.useMemo(()=>i.parseScheduleExpr(t),[t]),[a,l]=h.useState(()=>mt()),[c,u]=h.useState(null),d=i.buildSchedulePreview(r,s,ln(a),c?cn(c):null),[m,x]=h.useState(!1),g=j=>{n({scheduleExpr:i.buildScheduleExpr(j),timezone:s})},f=j=>{const w=j==="weekly"&&r.weekdays.length===0?[1,2,3,4,5]:r.weekdays;g({...r,repeats:j,weekdays:w})},b=(j,w)=>{g({...r,hour:j,minute:w})},A=j=>{g({...r,weekdays:j})},S=`${String(r.hour).padStart(2,"0")}:${String(r.minute).padStart(2,"0")}`,N=h.useMemo(()=>Eo(),[]);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:re,children:"When"}),e.jsx("span",{className:"truncate text-[11px] text-muted-foreground",children:d})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"Repeats"}),e.jsxs(o.Select,{value:r.repeats,onValueChange:j=>f(j),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsxs(o.SelectContent,{className:Ht,children:[e.jsx(o.SelectItem,{value:"daily",children:"Daily"}),e.jsx(o.SelectItem,{value:"weekly",children:"Weekly"}),e.jsx(o.SelectItem,{value:"biweekly",children:"Every two weeks"}),e.jsx(o.SelectItem,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"Time"}),e.jsxs(o.Select,{value:S,onValueChange:j=>{const[w,y]=j.split(":").map(C=>parseInt(C,10));b(w,y)},children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(o.SelectValue,{})}),e.jsx(o.SelectContent,{className:o.cn(Ht,"max-h-[280px]"),children:N.map(({value:j,label:w})=>e.jsx(o.SelectItem,{value:j,children:w},j))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(o.Popover,{open:m,onOpenChange:x,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-expanded":m,className:o.cn(et,"h-6 px-1.5 text-[11px]"),children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"More options",e.jsx(K.ChevronDown,{className:o.cn("h-3 w-3 text-muted-foreground/70 transition-transform",m&&"rotate-180")})]})}),e.jsxs(o.PopoverContent,{align:"end",className:"z-[60] w-[300px] space-y-2.5 p-3",onOpenAutoFocus:j=>j.preventDefault(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:re,children:"More options"}),e.jsx("button",{onClick:()=>x(!1),className:"rounded-control p-0.5 text-muted-foreground/70 hover:bg-muted hover:text-foreground/80","aria-label":"Close",children:e.jsx(K.X,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"First occurrence"}),e.jsx(dn,{icon:e.jsx(i.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:a,placeholder:"Pick a start date",disabledBefore:mt(),onChange:j=>{j&&l(j)},renderLabel:j=>j?ln(j):"Today"})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"Timezone"}),e.jsxs(o.Select,{value:s,onValueChange:j=>n({scheduleExpr:i.buildScheduleExpr(r),timezone:j}),children:[e.jsx(o.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[e.jsx(i.Globe,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"min-w-0 truncate",children:e.jsx(o.SelectValue,{})})]})}),e.jsx(o.SelectContent,{className:o.cn(Ht,"max-h-[280px]"),children:i.COMMON_TIMEZONES.map(j=>e.jsx(o.SelectItem,{value:j,children:Ao(j)},j))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"Ends"}),e.jsx(dn,{icon:e.jsx(i.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:c,placeholder:"No end date",clearable:!0,clearLabel:"No end date",disabledBefore:a,onChange:u,renderLabel:j=>j?cn(j):"No end date"})]}),r.repeats==="weekly"?e.jsxs("div",{children:[e.jsx("label",{className:o.cn(re,"mb-1 block"),children:"On these days"}),e.jsx("div",{className:"flex gap-1",children:["S","M","T","W","T","F","S"].map((j,w)=>{const y=r.weekdays.includes(w);return e.jsx("button",{type:"button",onClick:()=>{A(y?r.weekdays.filter(C=>C!==w):[...r.weekdays,w].sort())},className:o.cn("inline-flex h-7 w-7 items-center justify-center rounded-control border text-[11px] font-medium",y?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:border-border"),children:j},w)})})]}):null]})]})})]})}function Eo(){const t=[];for(let s=0;s<24;s+=1)for(const n of[0,30]){const r=`${String(s).padStart(2,"0")}:${String(n).padStart(2,"0")}`;t.push({value:r,label:i.formatTimeLabel(s,n)})}return t}function Ao(t){return!t||t==="UTC"?"UTC":{"America/New_York":"Eastern Time (ET)","America/Chicago":"Central Time (CT)","America/Denver":"Mountain Time (MT)","America/Los_Angeles":"Pacific Time (PT)","Europe/London":"London (GMT/BST)","Europe/Berlin":"Berlin (CET/CEST)","Asia/Singapore":"Singapore (SGT)","Asia/Tokyo":"Tokyo (JST)","Australia/Sydney":"Sydney (AEST/AEDT)"}[t]??t}function mt(){const t=new Date;return t.setHours(0,0,0,0),t}function Io(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function ln(t){return Io(t,mt())?"Today":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function cn(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function dn({value:t,icon:s,placeholder:n,clearable:r,clearLabel:a,disabledBefore:l,onChange:c,renderLabel:u}){const[d,m]=h.useState(!1),x=u(t),g=!t;return e.jsxs(o.Popover,{open:d,onOpenChange:m,children:[e.jsx(o.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-8 w-full items-center justify-between gap-2 rounded-control border border-border bg-background px-2.5 text-[12.5px] text-foreground hover:border-border focus-visible:border-ring focus-visible:outline-none",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s,e.jsx("span",{className:o.cn("truncate",g&&"text-muted-foreground/70"),children:g?n??x:x})]}),e.jsx(K.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"})]})}),e.jsxs(o.PopoverContent,{align:"start",className:"z-[60] w-auto p-0",onOpenAutoFocus:f=>f.preventDefault(),children:[e.jsx(i.Calendar$1,{mode:"single",selected:t??void 0,defaultMonth:t??l??mt(),onSelect:f=>{c(f??null),m(!1)},disabled:l?{before:l}:void 0}),r?e.jsx("div",{className:"border-t border-border p-2",children:e.jsx("button",{type:"button",onClick:()=>{c(null),m(!1)},className:"inline-flex h-7 w-full items-center justify-center rounded-control text-[12px] text-foreground/70 hover:bg-muted",children:a??"Clear"})}):null]})]})}function To({source:t,resolvedSourceContext:s,sourceDetail:n,onChange:r}){const[a,l]=h.useState(!1),c=h.useRef(null),u=s.source.type==="dashboard"?s.source:null,d=u!==null;h.useEffect(()=>{if(!a)return;const N=j=>{const w=j.target;c.current&&!c.current.contains(w)&&!(w instanceof Element&&w.closest("[data-scope-popover]"))&&l(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[a]);const m=t.type==="project",x=s.source.type==="dashboard"?s.label??"This dashboard":"This dashboard",g=s.source.type==="dashboard"?s.detail??n??null:n,f="This project",b="Use any data in this project.",A=m?f:x,S=m?b:g;return d?e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:c,type:"button",onClick:()=>l(N=>!N),"aria-expanded":a,className:"group flex w-full items-center justify-between rounded-card border border-border bg-muted/40 px-3 py-2 text-left hover:border-border",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[12px]",children:[e.jsx(i.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:A}),S?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground/70","aria-hidden":!0,children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground/70",children:S})]}):null]}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground group-hover:text-foreground",children:["Change",e.jsx(K.ChevronDown,{className:o.cn("h-3 w-3 transition-transform",a&&"rotate-180")})]})]}),a?e.jsxs("div",{"data-scope-popover":!0,className:"absolute left-0 right-0 top-full z-20 mt-1 overflow-hidden rounded-card border border-border bg-background shadow-md",children:[e.jsx(un,{active:!m,label:x,detail:g??null,description:"Use only the datasets this dashboard already reads.",onSelect:()=>{u&&r(u),l(!1)},isLast:!1}),e.jsx(un,{active:m,label:f,detail:"All project data",description:"Broaden scope so the briefing can reach any data in this project.",onSelect:()=>{r({type:"project"}),l(!1)},isLast:!0})]}):null]}):e.jsxs("div",{className:"rounded-card border border-border bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[12px]",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:A})]}),S?e.jsx("div",{className:"mt-0.5 pl-5 text-[11px] text-muted-foreground",children:S}):null]})}function un({active:t,label:s,detail:n,description:r,onSelect:a,isLast:l}){return e.jsxs("button",{type:"button",onClick:a,className:o.cn("flex w-full items-start gap-2.5 px-3 py-2.5 text-left transition-colors hover:bg-muted ",!l&&"border-b border-border/60 "),children:[e.jsx("span",{"aria-hidden":!0,className:o.cn("mt-1 inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border",t?"border-primary":"border-border "),children:t?e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}):null}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-[12.5px]",children:[e.jsx(i.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"font-medium text-foreground",children:s}),n?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[11px] text-muted-foreground/70","aria-hidden":!0,children:"·"}),e.jsx("span",{className:"truncate text-[11px] text-muted-foreground/70",children:n})]}):null]}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.45] text-muted-foreground",children:r})]})]})}function Lo({channels:t,selectedChannelId:s,onChange:n,destinationKind:r,onDestinationKindChange:a,loading:l,disabled:c,className:u}){const d=h.useRef(null),[m,x]=h.useState(!1),[g,f]=h.useState(""),b=h.useMemo(()=>t.find(j=>j.id===s)??null,[t,s]),A=h.useMemo(()=>{const j=g.trim().toLowerCase();return j?t.filter(w=>w.name.toLowerCase().includes(j)):t},[t,g]),S=r==="dm",N=c||S;return e.jsx("div",{className:o.cn("relative",u),children:e.jsxs(o.Popover,{open:m&&!N,onOpenChange:x,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",m?"border-ring ring-2 ring-ring/10":"border-border hover:border-border",N&&"cursor-not-allowed opacity-60"),onClick:()=>{var j;N||((j=d.current)==null||j.focus(),x(!0))},children:[e.jsx("span",{className:"inline-flex shrink-0 items-center text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"To"}),e.jsxs("div",{className:"inline-flex shrink-0 items-center gap-0.5 rounded-[4px] border border-border bg-muted/40 p-0.5",onClick:j=>j.stopPropagation(),children:[e.jsx("button",{type:"button",onClick:()=>a==null?void 0:a("channel"),className:o.cn("inline-flex h-5 items-center rounded-[3px] px-1.5 text-[10.5px] font-medium transition-colors",r==="channel"?"bg-foreground text-background":"text-muted-foreground hover:text-foreground"),children:"Channel"}),e.jsxs("button",{type:"button",disabled:!0,title:"Direct messages to specific recipients are coming in V2",className:"inline-flex h-5 cursor-not-allowed items-center rounded-[3px] px-1.5 text-[10.5px] font-medium text-muted-foreground/60",children:["DM",e.jsx("span",{className:"ml-1 rounded-[2px] bg-muted px-1 text-[8.5px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"soon"})]})]}),b?e.jsx(Fo,{channel:b,onRemove:()=>{var j;n(""),(j=d.current)==null||j.focus(),x(!0)}}):null,e.jsx("input",{ref:d,className:"h-6 min-w-[140px] flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground/70 disabled:cursor-not-allowed",value:g,disabled:N,placeholder:S?"DM delivery coming in V2":b?"Change channel…":l?"Loading channels…":"Search channels…",onChange:j=>{f(j.target.value),x(!0)},onFocus:()=>x(!0)})]})}),e.jsx(o.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:j=>j.preventDefault(),className:o.cn("z-[60] w-[var(--radix-popover-trigger-width)] min-w-[320px] rounded-card border border-border bg-background p-1 text-foreground shadow-md outline-none","max-h-[min(280px,var(--radix-popover-content-available-height))] overflow-y-auto"),children:A.length===0?e.jsx("div",{className:"px-2.5 py-3 text-center text-[12px] text-muted-foreground",children:t.length===0?"No bot-postable channels yet. Add channels from the Slack admin page.":"No channels match your search."}):e.jsx("ul",{className:"text-[12px]",children:A.map(j=>{const w=j.id===s;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{n(j.id),f(""),x(!1)},className:o.cn("flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left",w?"bg-muted text-foreground":"text-foreground/85 hover:bg-muted/60"),children:[j.isPrivate?e.jsx(i.Lock,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(i.Hash,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:j.name}),typeof j.memberCount=="number"?e.jsxs("span",{className:"ml-auto text-[11px] text-muted-foreground",children:[j.memberCount," members"]}):null]})},j.id)})})})]})})}function Fo({channel:t,onRemove:s}){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.isPrivate?e.jsx(i.Lock,{className:"h-3 w-3"}):e.jsx(i.Hash,{className:"h-3 w-3"})}),e.jsx("span",{className:"min-w-0 truncate text-foreground",children:t.name}),typeof t.memberCount=="number"?e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["· ",t.memberCount," members"]}):null,e.jsx("button",{type:"button",onClick:n=>{n.stopPropagation(),s()},className:"rounded-control p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":`Remove channel ${t.name}`,children:e.jsx(K.X,{className:"h-2.5 w-2.5"})})]})}const ts=dt,ze=ut;function Ro(t){var r,a;const s=(r=t==null?void 0:t.email)==null?void 0:r.trim();if(!s)return null;const n=(a=t==null?void 0:t.name)==null?void 0:a.trim();return{type:"email",address:s,...n&&n!==s?{name:n}:{}}}function nr(t){const s=h.useMemo(()=>t?new Date(t).getTime():null,[t]),[n,r]=h.useState(()=>Date.now());return h.useEffect(()=>{if(s===null)return;r(Date.now());const a=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(a)},[s]),s===null?null:Math.max(0,Math.floor((n-s)/1e3))}function hs(t){const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`}function de(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Po(t){if(!de(t))return null;const s=typeof t.subject=="string"?t.subject:null,n=typeof t.body=="string"?t.body:null,r=Array.isArray(t.recipients)?t.recipients.flatMap(c=>!de(c)||typeof c.label!="string"?[]:[{type:c.type==="email"||c.type==="user"||c.type==="tenant_user"||c.type==="group"?c.type:"email",label:c.label,...typeof c.detail=="string"?{detail:c.detail}:{},...typeof c.memberCount=="number"?{memberCount:c.memberCount}:{},...typeof c.hasMoreMembers=="boolean"?{hasMoreMembers:c.hasMoreMembers}:{},...Array.isArray(c.previewMembers)?{previewMembers:c.previewMembers.flatMap(d=>!de(d)||typeof d.label!="string"?[]:[{type:d.type==="user"||d.type==="tenant_user"||d.type==="email"?d.type:"email",label:d.label,...typeof d.detail=="string"?{detail:d.detail}:{}}])}:{}}]):null,a=Array.isArray(t.channels)?t.channels.filter(c=>typeof c=="string"):null,l=Array.isArray(t.attachments)?t.attachments.filter(c=>typeof c=="string"):null;return!s||!n||!r||!a||!l?null:{subject:s,body:n,...typeof t.bodyHtml=="string"&&t.bodyHtml.trim()?{bodyHtml:t.bodyHtml}:{},recipients:r,channels:a,attachments:l,...typeof t.attachmentNotice=="string"?{attachmentNotice:t.attachmentNotice}:{}}}function Mo(t){if(!de(t))return null;const s=typeof t.channel=="string"?t.channel:null,n=typeof t.text=="string"?t.text:null,r=Array.isArray(t.blocks)?t.blocks.filter(de):null;if(!s||!n||!r)return null;const a=de(t.thread)?{text:typeof t.thread.text=="string"?t.thread.text:"",blocks:Array.isArray(t.thread.blocks)?t.thread.blocks.filter(de):[],reply_broadcast:!1}:void 0;return{channel:s,text:n,blocks:r,unfurl_links:!1,unfurl_media:!1,...a?{thread:a}:{}}}function Bo(t){if(!de(t))return null;if(t.type==="email"){const s=typeof t.address=="string"?t.address:null;if(!s)return null;const n=typeof t.name=="string"?t.name:null;return{type:"email",label:n||s,...n?{detail:s}:{}}}if(t.type==="group"){const s=typeof t.name=="string"?t.name:null,n=typeof t.groupId=="string"?t.groupId:null;return{type:"group",label:s||"Group",...n&&!s?{detail:n}:{}}}if(t.type==="tenant_user"){const s=typeof t.name=="string"?t.name:null,n=typeof t.email=="string"?t.email:null,r=typeof t.tenantUserId=="string"?t.tenantUserId:null;return{type:"tenant_user",label:s||n||"Tenant user",...n&&s?{detail:n}:{},...r&&!s&&!n?{detail:r}:{}}}if(t.type==="user"){const s=typeof t.name=="string"?t.name:null,n=typeof t.email=="string"?t.email:null,r=typeof t.userId=="string"?t.userId:null;return{type:"user",label:s||n||"User",...n&&s?{detail:n}:{},...r&&!s&&!n?{detail:r}:{}}}return null}function rr(t){if(!de(t.result))return null;const s=de(t.result.deliveryReadiness)?t.result.deliveryReadiness:null,n=s&&de(s.intent)?s.intent:null,r=de(t.result.deliveryPackage)?t.result.deliveryPackage:null,a=de(t.result.deliveryResult)?t.result.deliveryResult:null,l=de(t.result.package)?t.result.package:null,c=typeof(r==null?void 0:r.subject)=="string"&&r.subject||typeof(s==null?void 0:s.subject)=="string"&&s.subject||typeof(n==null?void 0:n.subject)=="string"&&n.subject||typeof t.result.title=="string"&&t.result.title||"Briefing email",u=typeof(r==null?void 0:r.bodyMarkdown)=="string"&&r.bodyMarkdown||typeof(n==null?void 0:n.body)=="string"&&n.body||typeof t.result.summary=="string"&&t.result.summary||"",d=typeof(r==null?void 0:r.bodyHtml)=="string"&&r.bodyHtml.trim()?r.bodyHtml:null;if(!u)return null;const m=Array.isArray(n==null?void 0:n.recipients)?n.recipients.flatMap(f=>{const b=Bo(f);return b?[b]:[]}):[],x=Array.isArray(n==null?void 0:n.channels)?n.channels.filter(f=>typeof f=="string"):typeof(a==null?void 0:a.channel)=="string"?[a.channel]:[],g=Array.isArray(l==null?void 0:l.attachments)?l.attachments.flatMap(f=>de(f)?typeof f.label=="string"?[f.label]:typeof f.title=="string"?[f.title]:typeof f.filename=="string"?[f.filename]:[]:[]):[];return{subject:c,body:u,...d?{bodyHtml:d}:{},recipients:m,channels:x,attachments:g}}function ar({html:t,title:s="Briefing HTML artifact",className:n}){const r=h.useMemo(()=>i.purify.sanitize(t,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"]}),[t]);return e.jsx("iframe",{title:s,srcDoc:r,sandbox:"",className:o.cn("h-[760px] w-full rounded-card border border-border bg-background ",n)})}const J={info:{surface:"border-border bg-blue-50/60 text-foreground dark:border-border dark:bg-blue-950/30",icon:"text-blue-600 dark:text-blue-400"},success:{surface:"border-emerald-200 bg-emerald-50/70 text-foreground dark:border-emerald-900/50 dark:bg-emerald-950/30",icon:"text-emerald-700 dark:text-emerald-300",dot:"bg-emerald-500",label:"text-emerald-700 dark:text-emerald-400",iconBg:"bg-emerald-100 dark:bg-emerald-900/60"},danger:{surface:"border-destructive/30 bg-destructive/10 text-destructive",icon:"text-destructive",dot:"bg-destructive",iconBg:"bg-destructive/15"},warning:{surface:"border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300",dot:"bg-amber-500"},neutral:{dot:"bg-border"}};function mn(t,s){if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;return{status:typeof n.status=="string"?n.status:"SKIPPED",channel:typeof n.channel=="string"?n.channel:s,sentCount:typeof n.sentCount=="number"?n.sentCount:0,failedCount:typeof n.failedCount=="number"?n.failedCount:0,attemptedCount:typeof n.attemptedCount=="number"?n.attemptedCount:0,attachmentCount:typeof n.attachmentCount=="number"?n.attachmentCount:0,message:typeof n.message=="string"?n.message:""}}function Vo(t){return t.status==="SUCCESS"?"Complete":t.status==="FAILED"?"Failed":t.status==="RUNNING"?"Running":"Queued"}function xs(t){const s=t==null?void 0:t.result;if(!s||typeof s!="object"||Array.isArray(s))return null;const n=s.deliveryResult;if(!n||typeof n!="object"||Array.isArray(n))return null;const r=n,a=mn(r.email,"EMAIL"),l=mn(r.slack,"SLACK"),c=[a,l].filter(u=>u!==null);if(c.length>0){const u=c.some(g=>g.status==="FAILED"),d=c.filter(g=>g.status==="SENT").length,m=u&&d===0?"FAILED":u?"PARTIAL":d>0?"SENT":typeof r.status=="string"?r.status:"SKIPPED",x=c.map(g=>g.message).filter(Boolean).join(" ")||(typeof r.message=="string"?r.message:"");return{status:m,channel:typeof r.channel=="string"?r.channel:"BRIEFING",sentCount:c.reduce((g,f)=>g+f.sentCount,0),failedCount:c.reduce((g,f)=>g+f.failedCount,0),attemptedCount:c.reduce((g,f)=>g+f.attemptedCount,0),attachmentCount:c.reduce((g,f)=>g+f.attachmentCount,0),message:x,channels:{email:a??void 0,slack:l??void 0}}}return{status:typeof r.status=="string"?r.status:"SKIPPED",channel:typeof r.channel=="string"?r.channel:"EMAIL",sentCount:typeof r.sentCount=="number"?r.sentCount:0,failedCount:typeof r.failedCount=="number"?r.failedCount:0,attemptedCount:typeof r.attemptedCount=="number"?r.attemptedCount:0,attachmentCount:typeof r.attachmentCount=="number"?r.attachmentCount:0,message:typeof r.message=="string"?r.message:""}}function Oo(t){var s,n,r,a;if(t.channel==="BRIEFING"||t.channels){const l=(n=(s=t.channels)==null?void 0:s.email)==null?void 0:n.status,c=(a=(r=t.channels)==null?void 0:r.slack)==null?void 0:a.status;if(l==="SENT"&&c==="SENT")return"Email and Slack sent";if(l==="SENT"&&c==="FAILED")return"Email sent, Slack failed";if(l==="FAILED"&&c==="SENT")return"Slack sent, email failed";if(l==="SENT")return"Email sent";if(c==="SENT")return"Slack sent";if(l==="FAILED"||c==="FAILED")return"Delivery failed";if(t.status==="SENT")return"Delivery sent"}return t.status==="SENT"?t.channel==="SLACK"?"Slack sent":t.sentCount===1?"Email sent":`${t.sentCount} emails sent`:t.status==="FAILED"?t.channel==="SLACK"?"Slack failed":t.failedCount===1?"Email failed":`${t.failedCount||t.attemptedCount||0} emails failed`:t.status==="NOT_CONFIGURED"?"Email not configured":t.message||"Email delivery skipped"}function Uo(t){return t.status==="SENT"?J.success.surface:t.status==="FAILED"||t.status==="PARTIAL"?J.danger.surface:J.warning.surface}function or(t){return t.status==="SUCCESS"?e.jsx(o.Check,{className:o.cn("h-3 w-3",J.success.icon)}):t.status==="FAILED"?e.jsx(K.X,{className:o.cn("h-3 w-3",J.danger.icon)}):t.status==="RUNNING"?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-muted-foreground/70"})}const $o=[{pattern:/^plan preview/i,label:"Plan preview"},{pattern:/^analysis preview/i,label:"Analysis preview"}];function _o(t){const s=t.runtime.split(/;\s*/).map(a=>a.trim()).filter(Boolean),n=t.toolCalls.split(/;\s*/).map(a=>a.trim()).filter(Boolean),r=[];for(const{pattern:a,label:l}of $o){const c=hn(s.find(d=>a.test(d))),u=hn(n.find(d=>a.test(d)));(c||u)&&r.push({label:l,duration:c,toolCalls:u})}return r}function hn(t){return t&&t.replace(/^(plan|analysis)\s+preview\s+(should return in|takes|uses(?: at most)?|usually (?:takes|uses(?: at most)?))\s+/i,"").replace(/[.;]\s*$/,"").trim()||null}const xn=3;function zo({previewPlan:t,previewRun:s,scopeLabel:n}){return e.jsxs("div",{className:"space-y-5","aria-label":"Briefing plan",children:[e.jsxs("div",{children:[e.jsx("div",{className:re,children:"What I understood from your brief"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(Ee,{field:"Datasets",value:e.jsx(oi,{plan:t})}),e.jsx(Ee,{field:"Investigate",value:t.understood.investigation}),e.jsx(Ee,{field:"Threshold",value:t.understood.threshold}),e.jsx(Ee,{field:"Audience",value:t.understood.audience}),e.jsx(Ee,{field:"Format",value:t.understood.format,isLast:!0})]})]}),t.scope.grounding?e.jsx(qo,{plan:t}):null,e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"What I'll do"}),e.jsx("ol",{className:"space-y-3",children:t.steps.map(r=>e.jsx(ii,{order:r.order,title:r.title,detail:r.detail,tools:r.tools,optional:r.optional},r.order))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"rounded-card border border-border px-3 py-2",children:[e.jsx("div",{className:re,children:"Scope"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 text-[12px] text-foreground/80",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:(n==null?void 0:n.trim())||t.scope.sourceLabel})]})]}),e.jsxs("div",{className:"rounded-card border border-border px-3 py-2",children:[e.jsx("div",{className:re,children:"Estimate"}),(()=>{var c;const a=_o(t.estimate).find(u=>u.label.toLowerCase().includes("analysis")),l=(a==null?void 0:a.duration)??((c=t.estimate.runtime)==null?void 0:c.trim())??null;return e.jsx("div",{className:"mt-1 text-[12px] tabular-nums text-foreground/80",children:l??"—"})})()]})]}),t.ambiguities.length>0?e.jsx("div",{className:"rounded-card border border-border bg-muted px-2.5 py-1.5 text-[11px] leading-[1.55] text-muted-foreground",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("ul",{className:"space-y-0.5",children:t.ambiguities.map(r=>e.jsx("li",{children:r},r))})]})}):null,s&&!ze(s.status)?e.jsx(ir,{run:s,labelPrefix:"Preview"}):null]})}function qo({plan:t}){const s=t.scope.grounding;if(!s)return null;const n=s.datasetLabel&&s.datasetName?`${s.datasetLabel} (${s.datasetName})`:s.datasetName??s.datasetLabel??"Not selected yet",r=s.dimensions.length?s.dimensions.join(", "):"Best available dimensions";return e.jsxs("div",{children:[e.jsx("div",{className:re,children:"What I'll analyze"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(Ee,{field:"Metric",value:s.metric??"Not selected yet"}),e.jsx(Ee,{field:"Dataset",value:n}),e.jsx(Ee,{field:"Time field",value:s.dateField??"Not selected yet"}),e.jsx(Ee,{field:"Breakdown",value:r}),e.jsx(Ee,{field:"Confidence",value:`${s.confidence} · ${s.reason}`,isLast:!0})]})]})}function ir({run:t,labelPrefix:s}){const n=t.progress??null,r=n?ur(n.recentEvents??[],n.label).slice(-4).reverse():[],a=ze(t.status),l=n?ht(n.label):`${s?`${s} `:""}${Vo(t)}`,c=mr(t),u=n!=null&&n.updatedAt?new Date(n.updatedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit",second:"2-digit"}):null;return e.jsxs("div",{className:"rounded-card border border-border px-3 py-2","aria-label":`${s?`${s} `:""}run progress`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-foreground",children:[a?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):or(t),e.jsx("span",{className:"font-medium",children:l})]}),n!=null&&n.detail&&t.status!=="FAILED"?e.jsx("p",{className:"mt-1 text-[11px] leading-[1.5] text-muted-foreground",children:n.detail}):null]}),u?e.jsx("span",{className:"shrink-0 text-[10px] tabular-nums text-muted-foreground/70",children:u}):null]}),r.length>0?e.jsxs("div",{className:"mt-2 border-t border-border/60 pt-2",children:[e.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70",children:"Recent activity"}),e.jsx("ol",{className:"space-y-1.5",children:r.map((d,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-[11px] leading-[1.45] text-muted-foreground",children:[e.jsx(o.Check,{className:"mt-0.5 h-3 w-3 shrink-0 text-border"}),e.jsx("span",{children:dr(d.label)})]},`${d.updatedAt}-${d.label}-${m}`))})]}):null,c.length>0?e.jsx("p",{className:"mt-2 text-[11px] leading-[1.55] text-muted-foreground",children:c.join(" ")}):null]})}function lr({run:t,onRetryRun:s,retryDisabled:n,retryDisabledReason:r,onDeleteRun:a,deletePending:l}){const[c,u]=h.useState(!1),[d,m]=h.useState(!1),x=cr(t.completedAt??t.startedAt??t.scheduledFor),f=(t.error?/cancel/i.test(t.error):!1)?"Run cancelled":"Run failed";return e.jsxs("div",{className:o.cn("rounded-card border px-3 py-2.5",J.danger.surface),role:"alert","aria-label":f,children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:o.cn("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full",J.danger.iconBg),children:e.jsx(K.X,{className:o.cn("h-3 w-3",J.danger.icon)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline gap-2 text-[13px]",children:[e.jsx("span",{className:o.cn("font-medium",J.danger.icon),children:f}),x?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:x}):null]}),t.error?e.jsx("p",{className:"mt-1 text-[11px] leading-[1.55] text-foreground/80",children:t.error}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?e.jsxs("button",{type:"button",onClick:s,disabled:n,title:n?r:"Retry run",className:"inline-flex h-7 items-center gap-1.5 rounded-control border border-border bg-background px-2.5 text-[12px] font-medium text-foreground hover:bg-muted disabled:opacity-50",children:[e.jsx(i.RefreshCw,{className:"h-3 w-3"}),"Retry"]}):null,a?e.jsxs(i.DropdownMenu,{open:d,onOpenChange:m,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"More run actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsx(i.DropdownMenuContent,{align:"end",className:"z-[60] w-44",children:e.jsxs(i.DropdownMenuItem,{onClick:b=>{b.preventDefault(),m(!1),u(!0)},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete run"]})})]}):null]})]}),a?e.jsx(i.AlertDialog,{open:c,onOpenChange:b=>{l||u(b)},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:"Delete this run record?"}),e.jsx(i.AlertDialogDescription,{children:"The briefing itself stays. Only this run's record (status, error message, activity log) is removed and won't appear in history."})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{disabled:l,children:"Cancel"}),e.jsxs(i.AlertDialogAction,{disabled:l,onClick:b=>{b.preventDefault(),a()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[l?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.Trash2,{className:"h-3 w-3"}),"Delete run"]})]})]})}):null]})}function Ho({run:t}){const s=xs(t);return!ts(t.status)||!s||s.status==="SKIPPED"?null:e.jsxs("div",{className:o.cn("rounded-card border px-3 py-2 text-[12px]",Uo(s)),"aria-label":"Email delivery status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(me.SendHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Oo(s)})]}),s.message?e.jsx("p",{className:"mt-1 text-[11px] leading-[1.5] opacity-80",children:s.message}):null,e.jsxs("p",{className:"mt-1 text-[11px] leading-[1.5] opacity-70",children:[s.attachmentCount===1?"1 attachment":`${s.attachmentCount} attachments`,s.attemptedCount>0?` · ${s.attemptedCount} attempted`:""]})]})}function cr(t){if(!t)return null;const s=new Date(t);return Number.isNaN(s.getTime())?null:s.toLocaleString([],{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Ko(t){const s=xs(t);return t.status==="FAILED"?(s==null?void 0:s.status)==="FAILED"?"Last email failed":"Last run failed":(s==null?void 0:s.channel)==="BRIEFING"||s!=null&&s.channels?s.status==="SENT"?"Last delivery sent":s.status==="FAILED"||s.status==="PARTIAL"?"Last delivery failed":"Last delivery completed":(s==null?void 0:s.status)==="SENT"?s.channel==="SLACK"?"Last Slack sent":s.sentCount===1?"Last email sent":"Last emails sent":(s==null?void 0:s.status)==="FAILED"?"Last email failed":"Last run completed"}function Go({run:t,onViewOutput:s,onDeleteRun:n,onRetryRun:r,retryDisabled:a,retryDisabledReason:l,deletePending:c}){const u=xs(t),d=cr(t.completedAt??t.startedAt??t.scheduledFor);if(t.status==="FAILED"||(u==null?void 0:u.status)==="FAILED")return e.jsx(lr,{run:t,onRetryRun:r,retryDisabled:a,retryDisabledReason:l,onDeleteRun:n,deletePending:c});const x=u&&u.status!=="SKIPPED"?[u.attachmentCount===1?"1 attachment":`${u.attachmentCount} attachments`,u.attemptedCount>0?`${u.attemptedCount} attempted`:null].filter(Boolean).join(" · "):t.error;return e.jsx("div",{className:o.cn("rounded-card border px-3 py-2",J.success.surface),"aria-label":"Latest briefing run",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:o.cn("flex items-center gap-1.5 text-[12px] font-medium",J.success.label),children:[or(t),e.jsx("span",{children:Ko(t)}),d?e.jsx("span",{className:"font-normal text-muted-foreground",children:d}):null]}),x?e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:x}):null]}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs("button",{type:"button",className:Re,onClick:s,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})})]})})}function ht(t){return t.replace(/\s+(started|completed)$/i,"")}function dr(t){const s=/^(.*)\s+(started|completed)$/i.exec(t.trim());if(!s)return t;const n=s[1];return`${s[2].toLowerCase()==="completed"?"Completed":"Started"} ${n}`}function pn({run:t}){const s=t.progress??null,n=s?ur(s.recentEvents??[],s.label).slice(-4).reverse():[],r=s!=null&&s.detail&&s.detail!==s.label?s.detail:null,a=mr(t);return e.jsxs("div",{className:"border-b border-border bg-muted/60 px-4 py-3",children:[r?e.jsx("p",{className:"mb-3 text-[12px] leading-[1.5] text-foreground/80",children:r}):null,n.length>0?e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70",children:"Recent activity"}),e.jsx("ol",{className:"space-y-1.5",children:n.map((l,c)=>e.jsxs("li",{className:"flex items-start gap-2 text-[11px] leading-[1.45] text-muted-foreground",children:[e.jsx(o.Check,{className:"mt-0.5 h-3 w-3 shrink-0 text-border"}),e.jsx("span",{children:dr(l.label)})]},`${l.updatedAt}-${l.label}-${c}`))})]}):null,t.status==="FAILED"&&"error"in t&&t.error?e.jsx("p",{role:"alert",className:"mt-2 text-[11px] leading-[1.55] text-destructive",children:t.error}):null,a.length>0?e.jsx("p",{className:"mt-2 text-[11px] leading-[1.55] text-muted-foreground",children:a.join(" ")}):null]})}function ur(t,s){const n=s?s.replace(/\s+(started|completed)$/i,"").trim().toLowerCase():null,r=n?t.filter(u=>u.label.replace(/\s+(started|completed)$/i,"").trim().toLowerCase()!==n):t.slice(),a=new Set;for(const u of r){const d=/^(.*)\s+completed$/i.exec(u.label.trim());d&&a.add(d[1].trim().toLowerCase())}const l=r.filter(u=>{const d=/^(.*)\s+started$/i.exec(u.label.trim());if(!d)return!0;const m=d[1].trim().toLowerCase();return!a.has(m)}),c=new Map;for(const u of l)c.set(u.label.trim().toLowerCase(),u);return Array.from(c.values())}function Wo(){return e.jsx("div",{className:o.cn("border-b px-4 py-2 text-[12px] leading-[1.5]",J.info.surface),role:"note",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(o.Info,{className:o.cn("mt-0.5 h-3 w-3 shrink-0",J.info.icon)}),e.jsxs("p",{children:["Briefings typically take"," ",e.jsx("span",{className:"font-medium text-foreground",children:"1–3 minutes"}),". You can leave this open or come back later — we'll save the result."]})]})})}function Xo({run:t,onExpand:s}){var a;const n=nr(t.startedAt),r=(a=t.progress)!=null&&a.label?ht(t.progress.label):"Briefing running";return e.jsxs("div",{className:"fixed bottom-4 right-4 z-50 w-[320px] overflow-hidden rounded-card border border-border bg-background shadow-md",children:[e.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-start gap-2.5 px-3 py-2.5 text-left transition-colors hover:bg-muted","aria-label":"Expand briefing run",children:[e.jsx(o.LoaderCircle,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-[13px] font-medium text-foreground",children:r}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:n!==null?e.jsx("span",{className:"font-mono tabular-nums",children:hs(n)}):"Starting…"})]}),e.jsx(Ae.Maximize2,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"})]}),e.jsx("div",{className:"border-t border-border/60 bg-muted px-3 py-1.5",children:e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"We'll notify you when it's ready"})})]})}function Qo({title:t,durationSeconds:s,status:n,onView:r,onDismiss:a}){const l=n==="success";return e.jsx("div",{className:o.cn("border-b px-4 py-2.5",l?J.success.surface:J.danger.surface),role:"status",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:o.cn("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full",l?J.success.iconBg:J.danger.iconBg),children:l?e.jsx(o.Check,{className:o.cn("h-3 w-3",J.success.icon)}):e.jsx(K.X,{className:"h-3 w-3 text-destructive"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:t}),s!==null&&l?e.jsxs("p",{className:"mt-0.5 text-[11px] text-foreground/70",children:["Generated in ",hs(s)]}):null]}),l?e.jsxs("button",{type:"button",onClick:r,className:"inline-flex h-6 items-center gap-1 rounded-control bg-primary px-2 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:["View briefing",e.jsx(i.ArrowRight,{className:"h-3 w-3"})]}):null,e.jsx("button",{type:"button",onClick:a,className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Dismiss",children:e.jsx(K.X,{className:"h-3 w-3"})})]})})}function Jo({run:t}){const s=nr(t==null?void 0:t.startedAt);return s===null?null:e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",hs(s)]})}function Yo({pendingAction:t,previewRun:s,savedActiveRun:n,onShowDetails:r,onCancelPreviewRun:a,onCancelSavedRun:l,onMinimizeRun:c,detailsVisible:u}){var j,w,y,C;const d=s&&ze(s.status)?s:null,m=n;let x=null,g=null,f=!1;if(t==="plan"?(x="Reviewing your brief",g="Reading the brief and planning the analysis…"):t==="preview"?(x="Starting preview run",g="Starting the preview…"):t==="run"?(x="Starting briefing run",g="Preparing the run…"):d?(x=(j=d.progress)!=null&&j.label?ht(d.progress.label):"Running preview",g=((w=d.progress)==null?void 0:w.detail)??null,f=!!d.progress):m&&(x=(y=m.progress)!=null&&y.label?ht(m.progress.label):"Running",g=((C=m.progress)==null?void 0:C.detail)??null,f=!!m.progress),!x)return null;const b=!u&&g,A=m??d,S=!!(m&&c)&&t!=="cancelRun",N=m?l:d?a:void 0;return e.jsx("div",{className:"border-b border-border bg-muted/60","aria-live":"polite","aria-label":"Run progress",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-[12px]",children:[e.jsx(o.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate font-medium text-foreground",children:x}),e.jsx(Jo,{run:A}),b?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"shrink-0 text-border",children:"·"}),e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:g})]}):null,e.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[f?e.jsx("button",{type:"button",onClick:r,className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground","aria-expanded":u,"aria-label":u?"Hide details":"Show details",title:u?"Hide details":"Show details",children:e.jsx(K.ChevronDown,{className:o.cn("h-3 w-3 transition-transform",u&&"rotate-180")})}):null,S&&c?e.jsxs("button",{type:"button",onClick:c,className:"inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-control border border-border bg-background px-2 text-[11px] font-medium text-foreground hover:bg-muted","aria-label":"Run in background",title:"Run in background — we'll save the result",children:[e.jsx(Ae.Minimize2,{className:"h-3 w-3"}),"Run in background"]}):null,N?e.jsx("button",{type:"button",onClick:N,disabled:t==="cancelRun",className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50","aria-label":"Cancel run",title:"Cancel run",children:t==="cancelRun"?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(K.X,{className:"h-3 w-3"})}):null]})]})})}function mr(t){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))return[];const s=t.result.warnings;return Array.isArray(s)?s.filter(n=>typeof n=="string"):[]}function Zo(t){var s,n;return((n=(s=t.result)==null?void 0:s.limits)==null?void 0:n.previewKind)==="email_package"}function hr({children:t,muted:s}){return e.jsx("span",{className:o.cn("inline-flex min-h-6 max-w-full items-center rounded-control border px-2 py-1 text-[12px] leading-[1.25]",s?"border-dashed border-border bg-muted text-muted-foreground":"border-border bg-muted text-foreground"),children:t})}function ei({recipient:t}){const[s,n]=h.useState(!1),r=t.previewMembers??[];return t.type==="group"&&r.length>0?e.jsxs("div",{className:"relative inline-flex",children:[e.jsxs("button",{type:"button",className:"inline-flex min-h-6 max-w-full items-center rounded-control border border-border bg-muted px-2 py-1 text-left text-[12px] leading-[1.25] text-foreground hover:border-border",onClick:()=>n(l=>!l),"aria-expanded":s,children:[e.jsx("span",{className:"min-w-0 truncate",children:t.label}),t.detail?e.jsx("span",{className:"ml-1.5 min-w-0 truncate text-muted-foreground",children:t.detail}):null,s?e.jsx(K.ChevronDown,{className:"ml-1.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(Ae.ChevronRight,{className:"ml-1.5 h-3 w-3 shrink-0 text-muted-foreground"})]}),s?e.jsxs("div",{className:"absolute left-0 top-full z-20 mt-1 w-[280px] rounded-card border border-border bg-background p-2 shadow-md",children:[e.jsx("div",{className:re,children:"Members"}),e.jsx("div",{className:"mt-1.5 space-y-1",children:r.map((l,c)=>e.jsxs("div",{className:"rounded-control bg-muted px-2 py-1.5 text-[12px] leading-4",children:[e.jsx("div",{className:"truncate text-foreground",children:l.label}),l.detail?e.jsx("div",{className:"truncate text-muted-foreground",children:l.detail}):null]},`${l.type}-${l.label}-${c}`))}),t.hasMoreMembers?e.jsxs("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:["Showing first ",r.length," of ",t.memberCount??"many"," members"]}):null]}):null]}):e.jsxs(hr,{children:[e.jsx("span",{className:"min-w-0 truncate",children:t.label}),t.detail?e.jsx("span",{className:"ml-1.5 min-w-0 truncate text-muted-foreground",children:t.detail}):null]})}function xr({markdown:t,className:s}){return e.jsx("div",{className:o.cn("text-[13px] leading-[1.6] text-foreground ",s),children:e.jsx(i.Markdown,{remarkPlugins:[i.remarkGfm],components:{h1:({children:n})=>e.jsx("h1",{className:"mb-4 text-[18px] font-semibold leading-6 text-foreground",children:n}),h2:({children:n})=>e.jsx("h2",{className:"mb-2 mt-5 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground first:mt-0",children:n}),h3:({children:n})=>e.jsx("h3",{className:"mb-2 mt-4 text-[13px] font-semibold text-foreground",children:n}),p:({children:n})=>e.jsx("p",{className:"mb-3 max-w-[760px] text-[13px] leading-[1.65] text-foreground last:mb-0",children:n}),ul:({children:n})=>e.jsx("ul",{className:"mb-4 max-w-[760px] list-disc space-y-1.5 pl-5 text-[13px] leading-[1.6] marker:text-muted-foreground/70 last:mb-0",children:n}),ol:({children:n})=>e.jsx("ol",{className:"mb-4 max-w-[760px] list-decimal space-y-1.5 pl-5 text-[13px] leading-[1.6] marker:text-muted-foreground/70 last:mb-0",children:n}),li:({children:n})=>e.jsx("li",{className:"pl-0.5",children:n}),table:({children:n})=>e.jsx("div",{className:"my-4 overflow-x-auto rounded-card border border-border",children:e.jsx("table",{className:"w-full min-w-full border-collapse text-[12px]",children:n})}),th:({children:n})=>e.jsx("th",{className:"border-b border-border bg-muted px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:n}),td:({children:n})=>e.jsx("td",{className:"border-b border-border/60 px-3 py-2 align-top text-foreground last:border-b-0",children:n}),a:({children:n,href:r})=>e.jsx("a",{href:r,className:"font-medium text-primary underline decoration-primary/30 underline-offset-2 hover:text-primary",target:r!=null&&r.startsWith("#")?void 0:"_blank",rel:r!=null&&r.startsWith("#")?void 0:"noreferrer",children:n}),img:({alt:n,src:r})=>e.jsx("img",{alt:n??"",src:r??"",className:"my-4 max-h-[280px] w-auto max-w-full rounded-card border border-border object-contain"}),blockquote:({children:n})=>e.jsx("blockquote",{className:"my-4 max-w-[760px] border-l-2 border-border pl-3 text-foreground/70",children:n}),hr:()=>e.jsx("hr",{className:"my-5 border-border"}),code:({children:n})=>e.jsx("code",{className:"rounded-control bg-muted px-1 py-0.5 font-mono text-[11px] text-foreground",children:n}),pre:({children:n})=>e.jsx("pre",{className:"my-4 overflow-x-auto rounded-card border border-border bg-muted p-3 font-mono text-[11px] leading-[1.55] text-foreground/80",children:n})},children:t})})}function ps({preview:t,onExpand:s}){var l;const[n,r]=h.useState("rendered"),a=!!((l=t.bodyHtml)!=null&&l.trim());return e.jsxs("article",{className:"overflow-hidden rounded-card border border-border bg-background",children:[e.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border/60 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-[14px] font-semibold leading-5 text-foreground",children:t.subject||"Untitled"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground/70",children:"To"}),t.recipients.length>0?t.recipients.map((c,u)=>e.jsx(ei,{recipient:c},`${c.type}-${c.label}-${u}`)):e.jsx("span",{className:"italic text-muted-foreground/70",children:"No recipients"}),t.channels.length>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:["via ",t.channels.join(", ").toLowerCase()]})]}):null]})]}),a||s?e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a?e.jsx(o.Tabs,{value:n,onValueChange:c=>r(c==="html"?"html":"rendered"),children:e.jsxs(o.TabsList,{size:"xs",children:[e.jsx(o.TabsTrigger,{value:"rendered",children:"Rendered"}),e.jsx(o.TabsTrigger,{value:"html",children:"HTML"})]})}):null,s?e.jsx("button",{type:"button",onClick:s,"aria-label":"Expand preview to a larger view",className:"-mr-1 -mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground/70 hover:bg-muted hover:text-foreground/80",children:e.jsx(Ae.Maximize2,{className:"h-3.5 w-3.5"})}):null]}):null]}),n==="html"&&a?e.jsx(ar,{html:t.bodyHtml??"",title:"Briefing email HTML preview",className:"h-[620px] rounded-none border-0"}):e.jsx(xr,{markdown:t.body,className:"px-4 py-3.5"}),t.attachments.length>0||t.attachmentNotice?e.jsxs("footer",{className:"border-t border-border/60 px-4 py-2",children:[t.attachments.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:"Attached:"}),t.attachments.map(c=>e.jsx(hr,{children:c},c))]}):null,t.attachmentNotice?e.jsxs("div",{className:"mt-2 flex items-start gap-1.5 rounded-card border border-border bg-muted px-2.5 py-1.5 text-[11px] leading-[1.45] text-muted-foreground",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:t.attachmentNotice})]}):null]}):null]})}function Ke(t){if(!de(t))return null;const s=t.text;return typeof s=="string"?s:null}function ti(t){return t.type==="header"||t.type==="section"?Ke(t.text):t.type==="context"&&Array.isArray(t.elements)&&t.elements.map(n=>de(n)?Ke(n):null).filter(n=>!!n).join(" · ")||null}function si(t){return t.flatMap(s=>s.type!=="actions"||!Array.isArray(s.elements)?[]:s.elements.flatMap(n=>{if(!de(n))return[];const r=Ke(n.text);return r?[r]:[]}))}function ni(t){const s={header:null,context:null,sections:[],actions:null};for(const n of t)n.type==="header"&&!s.header?s.header=n:n.type==="context"&&!s.context?s.context=n:n.type==="actions"&&!s.actions?s.actions=n:n.type==="section"&&s.sections.push(n);return s}function Kt({size:t=6}){const s=t===5?"h-5 w-5":"h-6 w-6";return e.jsx("div",{className:o.cn("flex shrink-0 items-center justify-center rounded-[4px] bg-foreground",s),"aria-hidden":!0,children:e.jsxs("svg",{viewBox:"0 0 100 100",fill:"none",className:"h-[60%] w-[60%] text-background",children:[e.jsx("rect",{x:"20",y:"15",width:"60",height:"12",rx:"6",fill:"currentColor"}),e.jsx("rect",{x:"20",y:"35",width:"40",height:"12",rx:"6",fill:"currentColor"}),e.jsx("rect",{x:"40",y:"55",width:"40",height:"12",rx:"6",fill:"currentColor"}),e.jsx("rect",{x:"20",y:"75",width:"60",height:"12",rx:"6",fill:"currentColor"})]})})}function ri({channel:t}){const n=/^[CDG][A-Z0-9]{6,}$/.test(t)?t:t.startsWith("#")?t.slice(1):t;return e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(i.Hash,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:n})]})}function ai({preview:t,onExpand:s,trustLine:n,reactions:r}){const a=ni(t.blocks),l=a.header?Ke(a.header.text):null,c=a.context?ti(a.context):null,u=a.sections.map(g=>Ke(g.text)).filter(g=>!!g),d=a.actions?si([a.actions]):[],[m,x]=h.useState(!0);return e.jsxs("article",{className:"overflow-hidden rounded-card border border-border bg-background",children:[e.jsxs("header",{className:"flex items-center justify-between gap-3 border-b border-border/60 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate text-[13px] font-semibold leading-5 text-foreground",children:"Slack message preview"}),e.jsx("div",{className:"mt-0.5",children:e.jsx(ri,{channel:t.channel})})]})]}),s?e.jsx("button",{type:"button",onClick:s,"aria-label":"Expand preview to a larger view",className:"-mr-1 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground/70 hover:bg-muted hover:text-foreground/80",children:e.jsx(Ae.Maximize2,{className:"h-3.5 w-3.5"})}):null]}),e.jsxs("div",{className:"px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{size:6}),e.jsx("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Semaphor"}),e.jsx("span",{className:"rounded-[3px] bg-muted px-1 py-0 text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"APP"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"9:00 AM"})]}),l?e.jsx("div",{className:"mt-2 text-[13.5px] font-semibold leading-[1.35] text-foreground",children:l}):null,c?e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:c}):null,(l||c)&&u.length>0?e.jsx("div",{className:"my-2.5 h-px bg-border/60"}):null,u.length>0?e.jsx("div",{className:"space-y-2 text-[12.5px] leading-[1.55] text-foreground/85",children:u.map((g,f)=>e.jsx("p",{className:"whitespace-pre-line",children:g},`section-${f}`))}):null,d.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:d.map((g,f)=>e.jsx("button",{type:"button",tabIndex:-1,className:o.cn("inline-flex h-7 items-center gap-1.5 rounded-control px-2.5 text-[11.5px] font-medium",f===0?"bg-foreground text-background":"border border-border bg-background text-foreground/80"),children:g},g))}):null,n?e.jsx("div",{className:"mt-2.5 text-[10.5px] italic text-muted-foreground/80",children:n}):null,r&&r.length>0?e.jsx("div",{className:"mt-2 flex items-center gap-1",children:r.map(g=>e.jsxs("span",{className:"inline-flex h-5 items-center gap-1 rounded-full border border-border bg-muted px-1.5 text-[10.5px]",children:[e.jsx("span",{children:g.emoji}),e.jsx("span",{className:"tabular-nums text-muted-foreground",children:g.count})]},g.emoji))}):null,t.thread?e.jsxs("button",{type:"button",onClick:()=>x(g=>!g),className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-foreground/80 hover:underline",children:[e.jsx(Kt,{size:5}),e.jsx("span",{className:"font-medium text-foreground",children:"1 reply"}),e.jsxs("span",{className:"text-muted-foreground",children:["· ",m?"hide thread":"view thread"]})]}):null]}),t.thread&&m?e.jsx("div",{className:"mx-4 mb-4 ml-7 border-l-2 border-border/60 pl-3",children:e.jsxs("div",{className:"rounded-card border border-border bg-background p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{size:5}),e.jsx("span",{className:"text-[11.5px] font-semibold text-foreground",children:"Semaphor"}),e.jsx("span",{className:"rounded-[3px] bg-muted px-1 py-0 text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"APP"}),e.jsx("span",{className:"text-[10.5px] text-muted-foreground",children:"9:00 AM"})]}),e.jsx("div",{className:o.cn(re,"mb-1 mt-2"),children:"Detail"}),e.jsx("div",{className:"whitespace-pre-line text-[11.5px] leading-[1.55] text-foreground/80",children:t.thread.text})]})}):null]})}function Ee({field:t,value:s,isLast:n}){return e.jsxs("div",{className:o.cn("grid grid-cols-[110px_1fr] gap-3 px-3 py-2 text-[12px]",!n&&"border-b border-border/60 "),children:[e.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:t}),e.jsx("div",{className:"text-foreground",children:s})]})}function oi({plan:t}){const s=t.scope.datasets;return s.length?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-border bg-muted px-1.5 py-0.5 text-[11px] leading-4 text-foreground/80",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),n]},n))}):e.jsxs("div",{className:"flex items-start gap-1.5 text-muted-foreground",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:"No reachable datasets discovered during plan preview. Choose a dashboard, domain, metric, or more specific business question before running."})]})}function ii({order:t,title:s,detail:n,optional:r}){const[a,l]=h.useState(!1);return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:o.cn("mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",r?"border-border text-muted-foreground/70 0":"border-border/60 text-foreground "),children:t}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:o.cn("text-[12.5px] leading-[1.45]",r?"text-foreground/70 ":"text-foreground "),children:[s,r?e.jsx("span",{className:"ml-1.5 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"if needed"}):null]}),n?e.jsxs("div",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:[e.jsx("div",{className:o.cn("whitespace-pre-wrap break-words",!a&&`line-clamp-${xn}`),style:a?void 0:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:xn,overflow:"hidden"},children:n}),n.length>220?e.jsx("button",{type:"button",onClick:()=>l(c=>!c),className:"mt-0.5 text-[11px] text-foreground/60 hover:text-foreground",children:a?"Show less":"Show all fields"}):null]}):null]})]})}function fn({previewRun:t,onExpand:s,fullWidth:n}){var A,S,N,j,w,y;const r=t.result,a=(A=r==null?void 0:r.artifactPreview)==null?void 0:A.markdown,l=(S=r==null?void 0:r.artifactPreview)==null?void 0:S.html,c=Zo(t),u=c?Po((N=r==null?void 0:r.limits)==null?void 0:N.emailPreview):null,d=((j=r==null?void 0:r.limits)==null?void 0:j.previewKind)==="slack_message"?Mo(r.limits.slackPreview):null,m=t.status==="FAILED",x=m&&!!((w=t.error)!=null&&w.toLowerCase().includes("cancel")),g=m?J.danger:J.success,f=m?J.danger.icon:J.success.label,b=x?"Cancelled":m?"Failed":"Complete";return e.jsxs("div",{className:o.cn("space-y-4",n&&"max-w-none"),"aria-label":"Briefing preview result",children:[c?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-card border border-border/60 bg-muted/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsxs("span",{className:o.cn("inline-flex items-center gap-1",f),children:[e.jsx("span",{className:o.cn("h-1.5 w-1.5 rounded-full",g.dot)}),b]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"text-muted-foreground",children:"Preview run"})]}),s?e.jsxs("button",{type:"button",onClick:s,className:o.cn(et,"h-6 px-1.5 text-[11px]"),"aria-label":"Expand preview to a larger view",children:[e.jsx(Ae.Maximize2,{className:"h-3 w-3"}),"Expand"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:re,children:c?"Email preview":d?"Slack preview":"The story"}),!c&&!d?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"mt-2 text-[15px] font-semibold leading-6 text-foreground",children:(r==null?void 0:r.title)??(m?"Briefing preview stopped":"Briefing preview")}),m&&t.error?e.jsx("p",{role:"alert",className:o.cn("mt-2 rounded-card border px-3 py-2 text-[12px] leading-[1.5]",J.danger.surface),children:t.error}):null,r!=null&&r.summary?e.jsx("p",{className:"mt-2 text-[13px] leading-[1.55] text-foreground/80",children:r.summary}):null]}):null]}),u?e.jsx(ps,{preview:u,onExpand:s}):d?e.jsx(ai,{preview:d,onExpand:s,trustLine:"Runs with your permissions on this dashboard's data"}):a?e.jsx("article",{className:o.cn("rounded-card border border-border px-4 py-3",c&&"bg-background "),children:e.jsx(xr,{markdown:a})}):l?e.jsx(ar,{html:l,title:"Briefing preview HTML artifact",className:n?"h-[820px]":"h-[680px]"}):e.jsx("div",{className:"rounded-card border border-dashed border-border px-4 py-6 text-center text-[12px] text-muted-foreground",children:"No rendered briefing artifact is available for this preview yet."}),(y=r==null?void 0:r.warnings)!=null&&y.length&&!c?e.jsx("div",{className:"rounded-card border border-border bg-muted px-3 py-2 text-[11px] leading-[1.55] text-muted-foreground",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:r.warnings.join(" ")})]})}):null]})}function gn({run:t,onExpand:s,onDeleteRun:n,onRetryRun:r,retryDisabled:a,retryDisabledReason:l,deletePending:c}){const u=rr(t),d=t.status==="FAILED";return e.jsxs("div",{className:"space-y-4","aria-label":"Briefing run result",children:[d?e.jsx(lr,{run:t,onRetryRun:r,retryDisabled:a,retryDisabledReason:l,onDeleteRun:n,deletePending:c}):null,u?e.jsxs("div",{children:[e.jsx("div",{className:re,children:"Email"}),e.jsx("div",{className:"mt-2",children:e.jsx(ps,{preview:u,onExpand:s})})]}):null,!u&&de(t.result)&&typeof t.result.summary=="string"?e.jsxs("div",{children:[e.jsx("div",{className:re,children:"Briefing"}),e.jsx("article",{className:"mt-2 rounded-card border border-border px-4 py-3 text-[13px] leading-[1.55] text-foreground",children:t.result.summary})]}):null,e.jsx(Ho,{run:t}),e.jsx(ir,{run:t,labelPrefix:"Run"})]})}function li({previewRun:t,isStale:s,onViewOutput:n}){var a,l;const r=((a=t.result)==null?void 0:a.title)??((l=t.result)==null?void 0:l.summary)??"Generated briefing preview";return e.jsx("div",{className:o.cn("rounded-card border px-3 py-2",J.success.surface),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:o.cn("flex items-center gap-1.5 text-[11px] font-medium",J.success.label),children:[e.jsx(o.Check,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:"Preview output available"})]}),e.jsx("div",{className:"mt-1 truncate text-[12px] text-foreground/80",children:r}),s?e.jsx("div",{className:"mt-0.5 text-[10px] leading-[1.45] text-muted-foreground",children:"Generated before your latest edits."}):null]}),e.jsxs("button",{type:"button",className:Re,onClick:n,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})]})})}function it(t,s){return t.includes(s)?t:[...t,s]}function ci(t,s){const n=t.filter(r=>r!==s);return n.length>0?n:[s]}const di={createBriefing:Rn,updateBriefing:ft,pauseBriefing:os,resumeBriefing:is,deleteBriefing:ls,getBriefing:as,runBriefingNow:cs,getBriefingRun:ds,cancelBriefingRun:On,deleteBriefingRun:Un,previewBriefingPlan:Pn,runBriefingPreview:Mn,getBriefingPreviewRun:Bn,cancelBriefingPreviewRun:Vn,polishBriefingText:$n},bn=2e3,ui=10*6e4,mi=20*6e4;function hi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ce(t){return t instanceof Error&&t.message?t.message:"Something went wrong. Please try again."}function xi(t,s){return`${t.replace(/\/$/,"")}${s}`}function pi(t,s){if(!t)return s;try{return new URL(s,new URL(t).origin).toString()}catch{return s}}async function Gt(t,s,n,r){const a=await fetch(xi(t,n),{cache:"no-store",...r,headers:{...(r==null?void 0:r.headers)??{},Authorization:`Bearer ${s}`}}),l=await a.json().catch(()=>({}));if(!a.ok){const c=l&&typeof l=="object"&&"error"in l?String(l.error):"Request failed";throw new Error(c)}return l}function pr(t,s){return s||(t!=null&&t.source?{source:t.source,label:t.source.type==="dashboard"?"This dashboard":"This project"}:{source:{type:"project"},label:"This project"})}function jn(t){if(t.briefing)return He(t.briefing);const s=pr(t.briefing,t.sourceContext);return tr({source:s.source,name:s.source.type==="dashboard"?"Dashboard Briefing":"Project Briefing",instruction:es,...t.defaultRecipient?{delivery:{recipients:[t.defaultRecipient],channels:["EMAIL"]}}:{}})}function fi(t){return t==="PAUSED"||t==="DISABLED"?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"}function fr({apiServiceUrl:t,token:s,briefing:n,sourceContext:r,title:a="Briefing",className:l,client:c,generateRequestId:u=hi,onSaved:d,onDeleted:m,onRunStarted:x,onCancel:g,onBack:f,onMinimizeRun:b}){var Vs,Os,Us,$s,_s,zs,qs,Hs,Ks;const{authToken:A,tokenProps:S}=i.useSemaphorContext(),N=((Os=(Vs=S.config)==null?void 0:Vs.projectFeatures)==null?void 0:Os.features.aiWritingHelpers)!==!1,{currentUser:j}=i.useCurrentUserInfo(),w=o.useDashboardStore(p=>p.dashboard),y=o.useDashboardStore(p=>p.theme),C=o.useDashboardStore(p=>p.selectedSheetId),T=o.useDashboardStore(p=>p.filterValues),V=o.useDashboardStore(p=>p.controlValues),D=o.useDashboardStore(p=>p.semanticExecutionPayload),F=o.useDashboardStore(p=>p.cardControlValuesMap),U=o.useDashboardStore(p=>p.inlineFilterValuesMap),G=o.useDashboardStore(p=>p.dashboardInputValues),B=o.useInteractionStore(p=>p.interactionStates),_=t??(S==null?void 0:S.apiServiceUrl),$=s??(A==null?void 0:A.accessToken),M=h.useMemo(()=>({...di,...c}),[c]),Q=h.useMemo(()=>pr(n,r),[n,r]),ee=h.useMemo(()=>Ro(j),[j]),[L,W]=h.useState(n??null),[k,oe]=h.useState(()=>jn({briefing:n,sourceContext:Q,defaultRecipient:ee})),[Y,X]=h.useState(null),[he,ye]=h.useState([]),[ie,z]=h.useState(null),[Pe,ve]=h.useState(null),[ke,Se]=h.useState(null),[q,Ne]=h.useState(null),[O,ne]=h.useState(0),[qe,Oe]=h.useState(null),[I,P]=h.useState(!1),[fe,E]=h.useState("edit"),[H,te]=h.useState(0),[we,Me]=h.useState(!1),[yr,gt]=h.useState("EMAIL"),[vr,bt]=h.useState(!1),[fs,jt]=h.useState(null),[Nr,yt]=h.useState(!1),[ue,wr]=h.useState(null),[vt,gs]=h.useState([]),[st,bs]=h.useState(!1),[js,ys]=h.useState(null),[Cr,Sr]=h.useState(0),[Ue,nt]=h.useState(null),[kr,Nt]=h.useState(!1),[wt,vs]=h.useState(!1),[Ns,ws]=h.useState(null),[Ge,Ct]=h.useState(null);h.useEffect(()=>{if(!Ge)return;const p=window.setTimeout(()=>Ct(null),12e3);return()=>window.clearTimeout(p)},[Ge]);const Cs=h.useRef(void 0),{activeRunId:Dr,resetTerminalRun:Ss,startRun:St,stop:kt}=Zt({apiServiceUrl:_,token:$,intervalMs:bn,timeoutMs:mi,fetchRun:({apiServiceUrl:p,token:v,runId:R})=>{if(!(L!=null&&L.id))throw new Error("Missing saved Briefing id for run polling.");return M.getBriefingRun(p,v,L.id,R)},onRun:p=>{ve(p)},onTerminalRun:p=>{E("result"),z(null)},onError:p=>{z(`Unable to refresh briefing run status: ${Ce(p)}`)},onTimeout:()=>{z("Briefing run status refresh timed out. Refresh the run to check the latest status.")}}),{activeRunId:Er,startRun:Ar,stop:Dt}=Zt({apiServiceUrl:_,token:$,intervalMs:bn,timeoutMs:ui,fetchRun:({apiServiceUrl:p,token:v,runId:R})=>M.getBriefingPreviewRun(p,v,R),onRun:p=>{Ne(p),p.status==="SUCCESS"&&Oe(v=>v??O)},onTerminalRun:p=>{p.status==="FAILED"?z(p.error||"Briefing preview failed."):(z(null),E("result"))},onError:p=>{z(`Unable to refresh briefing preview status: ${Ce(p)}`)},onTimeout:p=>{Ne(v=>(v==null?void 0:v.id)===p?{...v,status:"FAILED",completedAt:v.completedAt??new Date().toISOString(),error:v.error||"Briefing preview status refresh timed out."}:v),z("Briefing preview status refresh timed out.")}}),ce=!!(L!=null&&L.id),Et=(L==null?void 0:L.status)==="PAUSED"||k.schedule.status==="PAUSED",Ir=ce&&!!(L!=null&&L.scheduleExpr||k.schedule.enabled),$e=Pe??(L==null?void 0:L.latestRun)??null,ge=$e&&ze($e.status)&&Dr===$e.id?$e:null,je=$e&&ts($e.status)?$e:null,Tr=q&&ts(q.status)?q:null,be=fe==="result"&&(Tr||je)?"result":fe==="plan"&&ke?"plan":"edit",Lr=Q.detail??(k.source.type==="dashboard"?(w==null?void 0:w.title)??null:"All project data available to this token"),ks=(L==null?void 0:L.status)??k.schedule.status,At=q!==null&&ze(q.status)&&Er===q.id,It=At||ge!==null,Be=Y!==null||It,Fr=be==="edit"&&je!==null&&!It,Tt=(q==null?void 0:q.status)==="SUCCESS"&&q.result?q:null,Rr=Tt!==null&&qe!==null&&qe!==O,We=fs==="preview"?q:null,Te=fs==="saved"?je:null,Xe=Te?rr(Te):null,Pr=((Us=We==null?void 0:We.result)==null?void 0:Us.title)??(Xe==null?void 0:Xe.subject)??(de(Te==null?void 0:Te.result)&&typeof Te.result.title=="string"?Te.result.title:null)??(L==null?void 0:L.name)??"Briefing preview",rt=h.useMemo(()=>({dashboard:w,theme:y||"light",filters:w==null?void 0:w.filters,selectedSheetId:C,filterValues:T,inlineFilterValuesMap:U,controlValues:V,controlDefinitions:(w==null?void 0:w.controls)||[],dashboardControls:(w==null?void 0:w.controls)||[],cardControlValuesMap:F,dashboardInputValues:G,semanticExecutionPayload:D,interactionStates:B}),[F,V,w,G,T,B,U,D,C,y]);h.useEffect(()=>{const p=(n==null?void 0:n.id)??null;if(Cs.current===p)return;Cs.current=p,Ss(),kt(),Dt(),W(n??null);let v=jn({briefing:n,sourceContext:Q,defaultRecipient:ee}),R=null;if(!n){const Bt=qt.findIndex(Je=>!Je.available||Je.available(v.source));if(Bt!==-1){const Je=qt[Bt];v=lt(v,Je.draft(v.source,{attachments:Je.seedsDashboardAttachment?Ys({source:v.source,dashboard:w,selectedSheetId:C,runtime:rt}):void 0})),R=Bt}}oe(v),te(R),ve(null),Se(null),Ne(null),Oe(null);const se=(n==null?void 0:n.latestRun)??null;z(null),E("edit"),se&&ze(se.status)&&St(se)},[rt,n,w,ee,Ss,Q,C,St,Dt,kt]);const Lt=k.delivery.channels.includes("EMAIL"),Le=k.delivery.channels.includes("SLACK"),at=Lt&&Le,Z=(_s=($s=k.delivery.channelConfigs)==null?void 0:$s.SLACK)==null?void 0:_s.slackConfig,Ds=((zs=Z==null?void 0:Z.destination)==null?void 0:zs.type)==="channel"?Z.destination.channelId??"":"",Fe=vt.find(p=>p.id===Ds),ot=(Z==null?void 0:Z.threadMentions)??[],Es=ot.length>0,As=JSON.stringify({recipients:ot}),Ft=Le&&!Lt?"SLACK":Lt&&!Le?"EMAIL":yr,Rt=Ft==="EMAIL"?"SLACK":"EMAIL";h.useEffect(()=>{if(!_||!$||!Le)return;let p=!1;return bs(!0),ys(null),Promise.all([Gt(_,$,"/v1/integrations/SLACK/status"),Gt(_,$,"/v1/integrations/slack/channels").catch(v=>{if(v instanceof Error&&/not configured/i.test(v.message))return{channels:[]};throw v})]).then(([v,R])=>{p||(wr(v),gs(R.channels))}).catch(v=>{p||(ys(Ce(v)),gs([]))}).finally(()=>{p||bs(!1)}),()=>{p=!0}},[Le,_,$,Cr]),h.useEffect(()=>{if(!_||!$||!Le){nt(null);return}if(!Es||!(ue!=null&&ue.installed)){nt(null);return}let p=!1;return Gt(_,$,"/v1/integrations/slack/mention-status",{method:"POST",headers:{"Content-Type":"application/json"},body:As}).then(v=>{p||nt(v)}).catch(()=>{p||nt(null)}),()=>{p=!0}},[Le,Es,_,$,ue==null?void 0:ue.installed,As]);const le=p=>{oe(v=>lt(v,p)),ye([]),z(null),L!=null&&L.id||(Se(null),ne(v=>v+1),E("edit"))},De=()=>!_||!$?(z("Missing Semaphor API credentials."),null):{apiServiceUrl:_,token:$},Mr=async p=>{const v=Yt(k);if(ye(v.issues),z(null),!v.valid)return null;const R=De();if(!R)return null;p!=null&&p.pendingAction&&X(p.pendingAction);try{const se=L!=null&&L.id?await M.updateBriefing(R.apiServiceUrl,R.token,L.id,sr(k)):await M.createBriefing(R.apiServiceUrl,R.token,Jt(k));return W(se.briefing),oe(He(se.briefing)),d==null||d(se.briefing),se.briefing}catch(se){return z(Ce(se)),null}finally{p!=null&&p.pendingAction&&X(null)}},Br=async()=>Mr({pendingAction:"save"}),Is=()=>{const p=Yt(k);return ye(p.issues),z(null),p.valid?Jt(k):null},Ts=async p=>{const v=De();if(!v)return null;const R=Is();if(!R)return null;X("plan");try{const se=await M.previewBriefingPlan(v.apiServiceUrl,v.token,R);return Se(se.plan),p!=null&&p.silent||E("plan"),se.plan}catch(se){return z(Ce(se)),null}finally{X(null)}},Vr=async()=>{const p=De();if(!p)return;const v=Is();if(v)try{const R=ke??await Ts({silent:!0});if(!R)return;X("preview");const se=await M.runBriefingPreview(p.apiServiceUrl,p.token,{draft:v,planId:R.id,requestId:u()});Oe(O),Ar(se.previewRun)}catch(R){z(Ce(R))}finally{X(null)}},Pt=async()=>{const p=De();if(p){if(!(L!=null&&L.id)){await Vr();return}if(_e){z("Save your changes before running this briefing.");return}X("run"),z(null),Ne(null);try{const v=await M.runBriefingNow(p.apiServiceUrl,p.token,L.id,{requestId:u()});St(v.run),x==null||x(v)}catch(v){z(Ce(v))}finally{X(null)}}},Ls=async()=>{if(!(L!=null&&L.id))return null;const p=De();if(!p)return null;const v=await M.getBriefing(p.apiServiceUrl,p.token,L.id);return W(v.briefing),oe(He(v.briefing)),d==null||d(v.briefing),v.briefing},Or=async()=>{if(!(L!=null&&L.id)||!(ge!=null&&ge.id))return;const p=De();if(p){X("cancelRun"),z(null);try{const v=await M.cancelBriefingRun(p.apiServiceUrl,p.token,L.id,ge.id);kt(),ve(v.run),E("result"),await Ls().catch(()=>null)}catch(v){z(Ce(v))}finally{X(null)}}},Ur=async()=>{if(!At||!(q!=null&&q.id))return;const p=De();if(p){X("cancelRun"),z(null);try{const v=await M.cancelBriefingPreviewRun(p.apiServiceUrl,p.token,q.id);Dt(),Ne(v.previewRun),E("result")}catch(v){z(Ce(v))}finally{X(null)}}},$r=()=>{!L||!ge||b==null||b({briefing:{...L,latestRun:ge},run:ge})},_r=async()=>{if(!k.instruction.trim())return;const v=De();if(v){vs(!0),ws(null);try{const R=await M.polishBriefingText(v.apiServiceUrl,v.token,k.instruction),se=k.instruction;le({instruction:R}),Ct({previousText:se})}catch(R){ws(Ce(R))}finally{vs(!1)}}},zr=()=>{Ge&&(le({instruction:Ge.previousText}),Ct(null))},Fs=async p=>{if(!(L!=null&&L.id))return;const v=De();if(v){X("deleteRun"),z(null);try{await M.deleteBriefingRun(v.apiServiceUrl,v.token,L.id,p);const R=await Ls().catch(()=>null),se=(R==null?void 0:R.latestRun)??null;ve(se),se||E("edit")}catch(R){z(Ce(R))}finally{X(null)}}},qr=async p=>{if(!(L!=null&&L.id))return;const v=De();if(v){X(p==="PAUSED"?"pause":"resume"),z(null);try{const R=p==="PAUSED"?await M.pauseBriefing(v.apiServiceUrl,v.token,L.id):await M.resumeBriefing(v.apiServiceUrl,v.token,L.id);W(R.briefing),oe(He(R.briefing)),d==null||d(R.briefing)}catch(R){z(Ce(R))}finally{X(null)}}},Hr=k.instruction.split(`
80
+ `).map(p=>p.trim()).find(p=>p.length>0),Rs=h.useMemo(()=>L?He(L):null,[L]),_e=!!Rs&&JSON.stringify(k)!==JSON.stringify(Rs),Ve=k.body.type==="custom_message",Mt=Ve?"Note":"Analysis",Qe=Ve?"Email body":"What should this briefing investigate?",Ps=Ve?"Write the email body that recipients will see.":"Describe the outcome in business terms. Mention what to watch, when to bother the team, and what to include in the briefing.",Ms=Ve?"Plain note — sent as-is in the email body. No analysis is generated for this preset.":"Tell the analyst what to watch, when to escalate, and what to include.",Bs=p=>{var v,R;if(gt(p),p==="EMAIL"){le({delivery:{channels:it(k.delivery.channels,"EMAIL")}});return}le({delivery:{channels:it(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((v=k.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...Z??{},destination:((R=Z==null?void 0:Z.destination)==null?void 0:R.type)==="channel"?Z.destination:{type:"channel",channelId:""},postThreadDetail:(Z==null?void 0:Z.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Kr=()=>{if(at){le({delivery:{channels:ci(k.delivery.channels,Rt)}});return}Bs(Rt)},Gr=p=>{var R;const v=vt.find(se=>se.id===p);gt("SLACK"),le({delivery:{channels:it(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((R=k.delivery.channelConfigs)==null?void 0:R.SLACK)??{},formatProfile:"concise",slackConfig:{...Z??{},destination:{type:"channel",channelId:p,...v?{channelName:v.name}:{},...v?{isPrivate:v.isPrivate}:{}},postThreadDetail:(Z==null?void 0:Z.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Wr=p=>{var v,R;gt("SLACK"),le({delivery:{channels:it(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((v=k.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...Z??{},destination:((R=Z==null?void 0:Z.destination)==null?void 0:R.type)==="channel"?Z.destination:{type:"channel",channelId:""},threadMentions:p,postThreadDetail:(Z==null?void 0:Z.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Xr=h.useMemo(()=>{const p=k.schedule.enabled?k.schedule.scheduleExpr||"Scheduled":"On demand",v=k.delivery.recipients.length,R=v===0?"No email recipients":`${v} email recipient${v===1?"":"s"}`,se=Fe?`#${Fe.name}`:"Slack channel";return at?`${p} · ${R} · ${se}`:Le?`${p} · ${Fe?`#${Fe.name}`:"Slack channel"}`:`${p} · ${R}`},[k.delivery.recipients.length,k.schedule.enabled,k.schedule.scheduleExpr,at,Le,Fe]);return e.jsxs("section",{className:o.cn("flex h-full min-h-0 w-full max-w-[480px] flex-col border-l border-border bg-background text-foreground",l),"aria-label":"Briefing author",children:[e.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[f?e.jsxs("button",{type:"button",onClick:f,className:"-ml-1 mb-1 inline-flex items-center gap-1 rounded-control px-1 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[e.jsx(Ae.ChevronRight,{className:"h-3 w-3 rotate-180"}),"Back to briefings"]}):null,e.jsx("h2",{className:"truncate text-[14px] font-semibold leading-5 text-foreground",children:a})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[ce?e.jsx("span",{className:o.cn("inline-flex items-center rounded-control px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.06em]",fi(ks)),children:ks}):null,g?e.jsx("button",{type:"button","aria-label":"Close briefing author",onClick:g,className:"rounded-control p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(K.X,{className:"h-3.5 w-3.5"})}):null]})]}),be!=="edit"?e.jsxs("button",{type:"button",onClick:()=>E("edit"),className:"flex w-full items-center justify-between gap-2 border-b border-border px-4 py-2.5 text-left transition-colors hover:bg-muted/60",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-[12px] text-foreground/80",children:Hr||k.name||"Untitled briefing"}),e.jsx("div",{className:"mt-0.5 truncate text-[10px] text-muted-foreground",children:Xr})]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:["Edit brief",e.jsx(K.ChevronDown,{className:"h-3 w-3 rotate-180"})]})]}):null,ge?e.jsx(Wo,{}):null,e.jsx(Yo,{pendingAction:Y,previewRun:q,savedActiveRun:ge,detailsVisible:we,onShowDetails:()=>Me(p=>!p),onCancelPreviewRun:At?Ur:void 0,onCancelSavedRun:ge?Or:void 0,onMinimizeRun:ge&&b?$r:void 0}),we&&q&&ze(q.status)?e.jsx(pn,{run:q}):we&&ge?e.jsx(pn,{run:ge}):null,e.jsx("div",{className:"flex-1 space-y-5 overflow-y-auto px-4 py-4",children:be==="edit"?e.jsxs(e.Fragment,{children:[ce?null:e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"Start from"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:qt.map((p,v)=>{if(p.available&&!p.available(k.source))return null;const R=H===v;return e.jsx("button",{type:"button",onClick:()=>{te(v),le(p.draft(k.source,{attachments:p.seedsDashboardAttachment?Ys({source:k.source,dashboard:w,selectedSheetId:C,runtime:rt}):void 0}))},className:o.cn("inline-flex h-6 items-center rounded-control border px-2 text-[11px] transition-colors",R?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"),"aria-label":`${p.label} preset — ${p.description}`,children:p.label},p.label)})})]}),Tt?e.jsx(li,{previewRun:Tt,isStale:Rr,onViewOutput:()=>E("result")}):null,Fr&&je?e.jsx(Go,{run:je,onViewOutput:()=>E("result"),onDeleteRun:je.status==="FAILED"?()=>Fs(je.id):void 0,onRetryRun:je.status==="FAILED"&&ce?()=>{Pt()}:void 0,retryDisabled:Be||ce&&_e,retryDisabledReason:ce&&_e?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:Y==="deleteRun"}):null,e.jsxs("div",{className:"rounded-card border border-border bg-card text-card-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/60 px-3 py-1.5",children:[e.jsx("span",{className:re,children:Mt}),e.jsx("button",{type:"button",onClick:()=>Nt(!0),"aria-label":`Expand ${Mt.toLowerCase()}`,title:`Expand ${Mt.toLowerCase()}`,className:"inline-flex h-5 w-5 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:e.jsx(Ae.Maximize2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("label",{htmlFor:"briefing-name",className:"sr-only",children:"Name"}),e.jsx("input",{id:"briefing-name",className:"block w-full bg-transparent text-[15px] font-semibold leading-6 text-card-foreground outline-none placeholder:text-muted-foreground",value:k.name,onChange:p=>{te(null),le({name:p.target.value})},placeholder:"Weekly revenue briefing"}),e.jsx("label",{htmlFor:"briefing-instruction",className:"sr-only",children:Qe}),e.jsx("textarea",{id:"briefing-instruction",className:"mt-2 block w-full resize-y bg-transparent text-[13px] leading-[1.6] text-card-foreground/80 outline-none placeholder:text-muted-foreground",rows:10,value:k.instruction,onChange:p=>{te(null),le({instruction:p.target.value})},placeholder:Ps,"aria-label":Qe}),e.jsx("p",{className:"mt-2 text-[11px] leading-[1.5] text-muted-foreground",children:Ms})]}),Ve?null:e.jsxs("div",{className:"flex items-center justify-end gap-0.5 border-t border-border/60 px-3 py-1.5",children:[k.source.type==="dashboard"&&k.attachments.length===0?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:Be,onClick:()=>yt(!0),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 disabled:opacity-50","aria-label":"Attach files",children:[e.jsx(i.Paperclip,{className:"h-3 w-3"}),"Attach"]}),e.jsx("span",{className:"text-border",children:"·"})]}):null,e.jsx(So,{includeEvidence:k.output.includeEvidence,includeSql:k.output.includeSql,includeHtml:k.output.artifactFormats.includes("html"),onChange:(p,v)=>{le(p==="evidence"?{output:{includeEvidence:v}}:p==="sql"?{output:{includeSql:v}}:{output:{artifactFormats:ko(k.output.artifactFormats,"html",v)}})}})]})]}),e.jsx(i.Dialog,{open:kr,onOpenChange:Nt,children:e.jsxs(i.DialogContent,{className:"flex h-[80vh] max-h-[800px] w-[92vw] max-w-[860px] flex-col gap-0 p-0",children:[e.jsxs(i.DialogHeader,{className:"border-b border-border/60 px-5 py-3",children:[e.jsx(i.DialogTitle,{className:"text-[14px] font-semibold",children:Qe}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:Ms})]}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col px-5 py-4",children:[e.jsx("label",{htmlFor:"briefing-instruction-expanded",className:"sr-only",children:Qe}),e.jsx("textarea",{id:"briefing-instruction-expanded",autoFocus:!0,className:"min-h-0 flex-1 resize-none bg-transparent text-[14px] leading-[1.6] text-card-foreground/90 outline-none placeholder:text-muted-foreground",value:k.instruction,onChange:p=>{te(null),le({instruction:p.target.value})},placeholder:Ps,"aria-label":Qe})]}),e.jsxs("div",{className:"flex items-center gap-2 border-t border-border/60 px-5 py-2.5",children:[e.jsx("div",{className:"flex flex-1 items-center gap-2 text-[12px] text-muted-foreground",children:Ns?e.jsx("span",{className:"text-destructive",children:Ns}):Ge?e.jsxs("button",{type:"button",onClick:zr,className:"inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-foreground/80 hover:bg-muted hover:text-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Revert polish"]}):null}),N?e.jsxs("button",{type:"button",onClick:_r,disabled:wt||!k.instruction.trim()||!_||!$,title:"Fix typos, grammar, and minor wording without changing your meaning",className:Re,children:[wt?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.Sparkles,{className:"h-3 w-3"}),wt?"Polishing…":"Polish"]}):null,e.jsx("button",{type:"button",onClick:()=>Nt(!1),className:Re,children:"Done"})]})]})}),k.source.type==="dashboard"?e.jsxs("div",{children:[k.attachments.length>0?e.jsx(mo,{attachments:k.attachments,disabled:Be,onAdd:()=>yt(!0),onChange:p=>le({attachments:p.map(Ie)})}):null,e.jsx(fo,{open:Nr,onOpenChange:yt,source:k.source,dashboard:w,selectedSheetId:C,runtime:rt,selectedAttachments:k.attachments,onSubmit:p=>le({attachments:p})})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"When"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(rn,{label:"On demand only",description:"Save the briefing and run it manually when needed.",checked:!k.schedule.enabled,onSelect:()=>le({schedule:{enabled:!1}}),name:"briefing-schedule-mode"}),e.jsx(rn,{label:"Scheduled",description:"Store the cadence so the runner picks it up later.",checked:k.schedule.enabled,onSelect:()=>le({schedule:{enabled:!0}}),name:"briefing-schedule-mode"})]}),k.schedule.enabled?e.jsx("div",{className:"mt-3 pl-6",children:e.jsx(Do,{scheduleExpr:k.schedule.scheduleExpr||i.buildScheduleExpr(i.DEFAULT_SCHEDULE_VM),timezone:k.schedule.timezone||"UTC",onScheduleChange:p=>le({schedule:{scheduleExpr:p.scheduleExpr,timezone:p.timezone}})})}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"Send via"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"inline-flex items-center gap-0.5 rounded-control border border-border bg-background p-0.5",children:["EMAIL","SLACK"].map(p=>{const v=k.delivery.channels.includes(p),R=Ft===p;return e.jsxs("button",{type:"button",onClick:()=>Bs(p),"aria-pressed":v,className:o.cn("inline-flex h-6 items-center gap-1.5 rounded-[4px] px-2.5 text-[11.5px] font-medium transition-colors",v?"bg-foreground text-background":"text-muted-foreground hover:text-foreground",R&&v&&"ring-1 ring-foreground/20"),children:[p==="EMAIL"?e.jsx(yn,{className:"h-3 w-3"}):e.jsx(Wt,{className:"h-3 w-3"}),p==="EMAIL"?"Email":"Slack"]},p)})}),e.jsxs("button",{type:"button",onClick:Kr,className:o.cn(et,"h-6 px-1.5 text-[11px]"),children:[at?"- Remove":"+ Also send"," ",Rt==="EMAIL"?"Email":"Slack"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"Recipients"}),Ft==="EMAIL"?e.jsx(tn,{value:k.delivery.recipients,onChange:p=>le({delivery:{recipients:p}})}):ue===null&&st?e.jsxs("div",{className:"flex items-center gap-2 rounded-card border border-dashed border-border bg-muted/30 px-3 py-2 text-[12px] text-muted-foreground",children:[e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Loading Slack workspace…"]}):ue!=null&&ue.installed?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Lo,{channels:vt,selectedChannelId:Ds,onChange:Gr,destinationKind:"channel",onDestinationKindChange:()=>{},loading:st}),e.jsx(tn,{value:ot,onChange:Wr,prefix:"Thread @",placeholder:ot.length>0?"Add more…":"Mention people in the thread reply"}),Ue&&Ue.unlinkedCount>0?e.jsxs("div",{className:"flex items-start gap-1.5 rounded-control border border-amber-200 bg-amber-50/60 px-2.5 py-1.5 text-[11px] leading-[1.5] text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{children:[Ue.unlinkedCount," of"," ",Ue.linkedCount+Ue.unlinkedCount," ",Ue.linkedCount+Ue.unlinkedCount===1?"mention has":"mentions have"," ","no linked Slack account and will be silently skipped. Ask them to link from their"," ",e.jsx("span",{className:"font-medium",children:"Slack identity"})," ","settings."]})]}):null,e.jsxs("div",{className:"flex items-center gap-1.5 pt-1 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":!0}),e.jsx("span",{children:((Ks=ue==null?void 0:ue.workspace)==null?void 0:Ks.teamName)??"Slack"}),Fe?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{children:Fe.isMember?`Bot in #${Fe.name}`:`Can post to #${Fe.name}`})]}):null]}),js?e.jsx("p",{className:"text-[11px] text-destructive",children:js}):null]}):e.jsxs("div",{className:"space-y-2 rounded-card border border-dashed border-border bg-muted/30 px-4 py-4 text-center",children:[e.jsx("div",{className:"mx-auto inline-flex h-8 w-8 items-center justify-center rounded-control border border-border bg-background",children:e.jsx(Wt,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("div",{className:"text-[12.5px] font-medium text-foreground",children:"Slack is not connected"}),e.jsx("p",{className:"mx-auto max-w-[320px] text-[11.5px] leading-[1.5] text-muted-foreground",children:(qs=ue==null?void 0:ue.capabilities)!=null&&qs.canConfigure?"Connect the Slack workspace to choose channels the bot can post in.":"Ask an admin to connect Slack before this briefing can post to a channel."}),e.jsxs("div",{className:"mt-1 flex items-center justify-center gap-2",children:[(Hs=ue==null?void 0:ue.capabilities)!=null&&Hs.canConfigure?e.jsx("a",{href:pi(_,"/admin/integrations/slack"),target:"_blank",rel:"noopener noreferrer",className:on,children:"Connect Slack"}):null,e.jsxs("button",{type:"button",onClick:()=>Sr(p=>p+1),disabled:st,className:Re,children:[st?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.RefreshCw,{className:"h-3 w-3"}),"Refresh"]})]})]})]}),Ve?null:e.jsxs("div",{children:[e.jsx("div",{className:o.cn(re,"mb-2"),children:"Scope"}),e.jsx(To,{source:k.source,resolvedSourceContext:Q,sourceDetail:Lr,onChange:p=>le({source:p})})]})]}):be==="plan"&&ke?e.jsx(zo,{previewPlan:ke,previewRun:q&&q.status!=="SUCCESS"?q:null,scopeLabel:Q.source.type==="dashboard"?(w==null?void 0:w.title)??Q.label:Q.label}):be==="result"&&q?e.jsx(fn,{previewRun:q,onExpand:()=>{jt("preview"),bt(!0)}}):be==="result"&&je?e.jsx(gn,{run:je,onExpand:()=>{jt("saved"),bt(!0)},onDeleteRun:je.status==="FAILED"?()=>Fs(je.id):void 0,onRetryRun:je.status==="FAILED"&&ce?()=>{Pt()}:void 0,retryDisabled:Be||ce&&_e,retryDisabledReason:ce&&_e?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:Y==="deleteRun"}):null}),he.length>0||ie?e.jsxs("div",{className:"shrink-0 space-y-2 border-t border-destructive/30 bg-destructive/10 px-4 py-2.5",children:[he.length>0?e.jsxs("div",{role:"alert",className:"text-[12px] leading-[1.5] text-destructive",children:[e.jsxs("div",{className:"mb-1 inline-flex items-center gap-1.5 font-medium",children:[e.jsx(o.Info,{className:"h-3 w-3"}),"Fix these before saving:"]}),e.jsx("ul",{className:"space-y-0.5 pl-4",children:he.map(p=>e.jsx("li",{className:"list-disc marker:text-destructive/60",children:p.message},`${p.field}:${p.message}`))})]}):null,ie?e.jsxs("div",{role:"alert",className:"flex items-start gap-1.5 text-[12px] leading-[1.55] text-destructive",children:[e.jsx(o.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:ie})]}):null]}):null,e.jsx("footer",{className:"sticky bottom-0 border-t border-border bg-background px-4 py-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:ce&&Ir?e.jsxs("button",{type:"button",className:Re,disabled:Be,onClick:()=>qr(Et?"ACTIVE":"PAUSED"),children:[Y==="pause"||Y==="resume"?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):Et?e.jsx(i.Play,{className:"h-3 w-3"}):e.jsx(vn,{className:"h-3 w-3"}),Et?"Resume":"Pause"]}):!ce&&(be==="plan"||be==="result")?e.jsxs("button",{type:"button",className:et,onClick:()=>E("edit"),children:[e.jsx(Ae.ChevronRight,{className:"h-3 w-3 rotate-180"}),be==="result"?"Edit brief":"Tweak brief"]}):!ce&&g&&!f?e.jsx("button",{type:"button",className:et,onClick:g,children:"Discard"}):null}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ce&&be==="edit"&&!Ve?e.jsxs("button",{type:"button",className:Re,disabled:Be,onClick:()=>{Ts()},children:[Y==="plan"?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(Zr,{className:"h-3 w-3"}),"Show plan"]}):null,ce||!Ve?e.jsxs("button",{type:"button",className:Re,disabled:Be||ce&&_e,onClick:Pt,title:ce&&_e?"Save your changes before running — Run now uses the saved briefing.":void 0,children:[Y==="run"||Y==="preview"||It?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):be==="result"?e.jsx(i.RefreshCw,{className:"h-3 w-3"}):be==="plan"?e.jsx(Xt,{className:"h-3 w-3"}):ce?e.jsx(i.Send,{className:"h-3 w-3"}):e.jsx(Xt,{className:"h-3 w-3"}),ce?"Run now":be==="plan"?"Run plan":be==="result"?"Run again":"Dry run"]}):null,e.jsxs("button",{type:"button",className:ce?Re:on,disabled:Be,onClick:Br,children:[Y==="save"?e.jsx(o.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(o.Check,{className:"h-3 w-3"}),ce?"Save changes":"Create briefing"]})]})]})}),e.jsx(i.Dialog,{open:vr,onOpenChange:p=>{bt(p),p||jt(null)},children:e.jsxs(i.DialogContent,{className:"flex max-h-[90vh] w-[min(960px,calc(100vw-32px))] max-w-none flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(i.DialogHeader,{className:"border-b border-border px-6 py-3 text-left",children:[e.jsx(i.DialogTitle,{className:"truncate text-[14px] font-semibold leading-5",children:Pr}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Full briefing render"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:We?e.jsx(fn,{previewRun:We,fullWidth:!0}):Xe?e.jsx(ps,{preview:Xe}):Te?e.jsx(gn,{run:Te}):null})]})})]})}function gr({disabled:t,briefingCount:s,className:n,onClick:r}){const a=typeof s=="number"&&s>0;return e.jsxs(o.Button,{type:"button",size:"xs",variant:"outline",disabled:t,className:o.cn("gap-1.5",n),onClick:r,"aria-label":"Briefings",children:[e.jsx(ea,{className:"h-3.5 w-3.5"}),"Briefings",a?e.jsx("span",{className:"ml-0.5 rounded-control bg-muted px-1 text-[10px] tabular-nums text-foreground/70",children:s}):null]})}const gi={listBriefings:Fn,getBriefing:as,pauseBriefing:os,resumeBriefing:is,deleteBriefing:ls,runBriefingNow:cs},bi="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",ji="inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",br="inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50";function yi(t){return(t==null?void 0:t.trim())||"This dashboard"}function vi(t){return t==="This dashboard"?"Watch this dashboard":`Watch ${t}`}function Ni(t,s){return t.source.type==="dashboard"&&t.source.dashboardId===s}function wi(t){return t==="dashboard"?"This dashboard":"Project"}function Ci(t,s,n){return s==="dashboard"?t.filter(r=>Ni(r,n)):t}async function Si({apiClient:t,apiServiceUrl:s,token:n}){const a=[];let l=1,c=0,u=Number.POSITIVE_INFINITY;for(;c<u;){const d=await t.listBriefings(s,n,{scope:"organization",page:l,pageSize:100}),m=d.briefings;if(a.push(...m),c+=m.length,u=d.total,m.length===0||c>=u)break;l+=1}return a}function ki(t){if(!t)return"Never";const s=new Date(t);if(Number.isNaN(s.getTime()))return"Unknown";const n=Date.now()-s.getTime(),r=Math.round(n/6e4);if(r<1)return"now";if(r<60)return`${r}m ago`;const a=Math.round(r/60);if(a<24)return`${a}h ago`;const l=Math.round(a/24);if(l<7)return`${l}d ago`;const c=Math.round(l/7);return c<5?`${c}w ago`:`${Math.round(l/30)}mo ago`}function Di(t){return t.scheduleExpr?t.scheduleExpr:"On demand"}function Ei(t){if(t.lastRunStatus){const s=t.lastRunStatus.toString().toUpperCase();return s==="SUCCESS"?"Last run completed.":s==="FAILED"?"Last run failed.":`Last run ${t.lastRunStatus.toString().toLowerCase()}`}return null}function jr(t){return t.hasActiveRun?"Running":t.lastRunStatus?`Last run ${t.lastRunStatus.toString().toLowerCase()}`:"Idle"}function Ai(t){return t.source.type==="dashboard"?"This dashboard":"Project"}function Ii({activeView:t,onChange:s}){return e.jsx("div",{className:"flex shrink-0 items-center gap-1 rounded-control bg-muted p-0.5",role:"tablist","aria-label":"Briefing source view",children:["dashboard","project"].map(n=>{const r=t===n;return e.jsx("button",{type:"button",role:"tab","aria-selected":r,onClick:()=>s(n),className:o.cn("h-6 rounded-[3px] px-2 text-[11px] transition-colors",r?"bg-background font-medium text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:wi(n)},n)})})}function Ti({briefings:t,dashboardLabel:s,sourceView:n,error:r,loading:a,onSourceViewChange:l,onClose:c,onEdit:u,onNew:d,onRunNow:m,onTogglePause:x,onDelete:g,selectingId:f,busyId:b,manageBriefingsHref:A}){const S=t.length,N=t.filter(y=>y.status==="ACTIVE").length,j=t.find(y=>y.hasActiveRun)??null,w=n==="dashboard"?s:"Project briefings";return e.jsxs("section",{"aria-label":"Dashboard briefings",className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[e.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:bi,children:"Briefings"}),e.jsx("h2",{className:"mt-0.5 truncate text-[14px] font-semibold leading-5",children:w})]}),e.jsx("button",{type:"button",onClick:c,className:"rounded-control p-1 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close briefings panel",children:e.jsx(K.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border px-4 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(Ii,{activeView:n,onChange:l}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:a&&S===0?e.jsx("span",{children:"Loading briefings…"}):S===0?e.jsx("span",{children:"No briefings yet"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[S," watching"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[N," active"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[a?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,S>0?e.jsxs("button",{onClick:d,className:br,children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"New briefing"]}):null]})]}),j?e.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-muted/60 px-4 py-2 text-[12px]",children:[e.jsx(o.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:j.name}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground",children:jr(j)})]}):null,e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r?e.jsx("div",{className:"m-4 rounded-card border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:r}):null,!a&&t.length===0&&!r?e.jsx(Li,{onNew:d}):null,t.map(y=>e.jsx(Ri,{briefing:y,isOpening:f===y.id,isBusy:b===y.id,onOpen:()=>u(y.id),onRunNow:()=>m(y),onTogglePause:()=>x(y),onDelete:()=>g(y)},y.id))]}),A?e.jsx("div",{className:"border-t border-border px-4 py-2.5",children:e.jsxs("a",{href:A,className:o.cn(ji,"h-6 px-1 text-[11px]"),children:["Manage all briefings",e.jsx(Qr,{className:"h-3 w-3"})]})}):null]})}function Li({onNew:t}){return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-8 py-12 text-center",children:[e.jsx(Fi,{className:"mb-5 h-[88px] w-[112px] text-border"}),e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:"Have an analyst brief your team"}),e.jsx("p",{className:"mt-1.5 max-w-[320px] text-[12px] leading-5 text-muted-foreground",children:"Describe what to watch. An analyst digs into this dashboard and the data behind it, then briefs your team on the cadence you choose."}),e.jsxs("button",{onClick:t,className:o.cn(br,"mt-4"),children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"New briefing"]})]})}function Fi({className:t}){return e.jsxs("svg",{viewBox:"0 0 112 88",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"presentation","aria-hidden":"true",className:t,children:[e.jsx("rect",{x:"22",y:"6",width:"60",height:"72",rx:"3",stroke:"currentColor",strokeWidth:"1.25"}),e.jsx("line",{x1:"30",y1:"16",x2:"64",y2:"16",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),e.jsx("line",{x1:"30",y1:"21",x2:"52",y2:"21",stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",opacity:"0.5"}),e.jsx("circle",{cx:"31",cy:"32",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"32",x2:"72",y2:"32",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("circle",{cx:"31",cy:"38",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"38",x2:"68",y2:"38",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("circle",{cx:"31",cy:"44",r:"1",fill:"currentColor",opacity:"0.6"}),e.jsx("line",{x1:"35",y1:"44",x2:"74",y2:"44",stroke:"currentColor",strokeWidth:"1",opacity:"0.4",strokeLinecap:"round"}),e.jsx("rect",{x:"30",y:"64",width:"5",height:"8",rx:"0.5",fill:"currentColor",opacity:"0.55"}),e.jsx("rect",{x:"38",y:"60",width:"5",height:"12",rx:"0.5",fill:"currentColor",opacity:"0.7"}),e.jsx("rect",{x:"46",y:"56",width:"5",height:"16",rx:"0.5",fill:"currentColor",opacity:"0.85"}),e.jsx("rect",{x:"54",y:"62",width:"5",height:"10",rx:"0.5",fill:"currentColor",opacity:"0.6"}),e.jsx("rect",{x:"62",y:"58",width:"5",height:"14",rx:"0.5",fill:"currentColor",opacity:"0.75"}),e.jsx("circle",{cx:"86",cy:"62",r:"10",fill:"var(--background, white)",stroke:"currentColor",strokeWidth:"1.25"}),e.jsx("line",{x1:"93.5",y1:"69.5",x2:"100",y2:"76",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}function Ri({briefing:t,isOpening:s,isBusy:n,onOpen:r,onRunNow:a,onTogglePause:l,onDelete:c}){const u=t.status==="PAUSED",d=t.hasActiveRun,m=Ei(t),x=ki(t.lastRunAt),g=t.lastRunStatus,f=g==="SUCCESS"?J.success.dot:g==="FAILED"?J.danger.dot:g?J.warning.dot:J.neutral.dot;return e.jsxs("div",{className:o.cn("group relative border-b border-border/60 px-4 py-3 transition-colors hover:bg-muted/60",u&&"opacity-70"),children:[e.jsxs("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),r())},className:"cursor-pointer pr-8",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.name}),u?e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:"· Paused"}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:Ai(t)}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx(i.Clock,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Di(t)}),t.lastRunAt?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:["Last run ",x]})]}):null]}),m||d?e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5 text-[12px] leading-[1.5] text-foreground/80",children:[d?e.jsx(o.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground/70"}):e.jsx("span",{className:o.cn("inline-block h-1.5 w-1.5 shrink-0 rounded-full",f)}),e.jsx("span",{className:"truncate",children:d?jr(t):m})]}):null]}),e.jsx("div",{className:"absolute right-3 top-3",children:n?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):s?e.jsx(o.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):e.jsxs(i.DropdownMenu,{children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",onClick:b=>b.stopPropagation(),className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground/70 opacity-60 hover:bg-muted hover:text-foreground/80 focus-visible:opacity-100 group-hover:opacity-100","aria-label":"Briefing actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"w-44",children:[e.jsxs(i.DropdownMenuItem,{onClick:r,children:[e.jsx(i.Pencil,{className:"h-3.5 w-3.5"}),"Edit briefing"]}),e.jsxs(i.DropdownMenuItem,{onClick:b=>{b.preventDefault(),a()},children:[e.jsx(Xt,{className:"h-3.5 w-3.5"}),"Run now"]}),t.scheduleExpr?e.jsx(i.DropdownMenuItem,{onClick:b=>{b.preventDefault(),l()},children:u?e.jsxs(e.Fragment,{children:[e.jsx(i.Play,{className:"h-3.5 w-3.5"}),"Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(vn,{className:"h-3.5 w-3.5"}),"Pause"]})}):null,e.jsx(i.DropdownMenuSeparator,{}),e.jsxs(i.DropdownMenuItem,{onClick:b=>{b.preventDefault(),c()},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete briefing"]})]})]})})]})}const Pi=2e3,Mi=20*6e4;function Bi({briefingId:t,initialRun:s,apiServiceUrl:n,token:r,onTerminal:a,onTimeout:l,onExpand:c}){const[u,d]=h.useState(s),{startRun:m}=Zt({apiServiceUrl:n,token:r,intervalMs:Pi,timeoutMs:Mi,fetchRun:({apiServiceUrl:g,token:f,runId:b})=>ds(g,f,t,b),onRun:g=>{d(g)},onTerminalRun:g=>{a(g)},onTimeout:()=>{l()}}),x=h.useRef(!1);return h.useEffect(()=>{x.current||(x.current=!0,ut(s.status)?m(s):dt(s.status)&&a(s))},[s,a,m]),e.jsx(Xo,{run:u,onExpand:c})}function Vi({dashboardId:t,dashboardTitle:s,apiServiceUrl:n,token:r,disabled:a,className:l,manageBriefingsHref:c,client:u}){const{authToken:d,tokenProps:m}=i.useSemaphorContext(),[x,g]=h.useState(!1),[f,b]=h.useState("list"),[A,S]=h.useState("dashboard"),[N,j]=h.useState([]),[w,y]=h.useState(null),[C,T]=h.useState(!1),[V,D]=h.useState(null),[F,U]=h.useState(null),[G,B]=h.useState(null),[_,$]=h.useState(null),[M,Q]=h.useState(null),[ee,L]=h.useState(null),W=n??(m==null?void 0:m.apiServiceUrl),k=r??(d==null?void 0:d.accessToken),oe=h.useMemo(()=>({...gi,...u}),[u]),Y=yi(s),X=h.useMemo(()=>Ci(N,A,t),[t,N,A]),he=h.useMemo(()=>A==="dashboard"?{source:{type:"dashboard",dashboardId:t},label:Y,detail:vi(Y)}:{source:{type:"project"},label:"This project",detail:"Use any data in this project."},[t,Y,A]),ye=!!(W&&k),ie=h.useCallback(async()=>{if(!(!W||!k)){T(!0),$(null);try{j(await Si({apiClient:oe,apiServiceUrl:W,token:k}))}catch(O){$(O instanceof Error?O.message:"Could not load briefings.")}finally{T(!1)}}},[oe,W,k]);h.useEffect(()=>{!x||f!=="list"||!ye||ie()},[ye,ie,x,f]);const z=()=>{y(null),S("dashboard"),b("list"),g(!0)},Pe=()=>{y(null),b("author")},ve=async O=>{if(!(!W||!k)){D(O),$(null);try{const ne=await oe.getBriefing(W,k,O);y(ne.briefing),b("author")}catch(ne){$(ne instanceof Error?ne.message:"Could not open briefing.")}finally{D(null)}}},ke=async O=>{if(!(!W||!k)){U(O.id);try{await oe.runBriefingNow(W,k,O.id,{requestId:Oi()}),ie()}catch(ne){i.ue.error(ne instanceof Error?ne.message:"Could not start the run.")}finally{U(null)}}},Se=async O=>{if(!(!W||!k)){U(O.id);try{const ne=O.status==="PAUSED"?await oe.resumeBriefing(W,k,O.id):await oe.pauseBriefing(W,k,O.id);i.ue.success(ne.briefing.status==="PAUSED"?"Briefing paused":"Briefing resumed"),ie()}catch(ne){i.ue.error(ne instanceof Error?ne.message:"Could not update the briefing status.")}finally{U(null)}}},q=async()=>{if(!G||!W||!k)return;const O=G;U(O.id);try{await oe.deleteBriefing(W,k,O.id),i.ue.success("Briefing deleted"),B(null),ie()}catch(ne){i.ue.error(ne instanceof Error?ne.message:"Could not delete the briefing.")}finally{U(null)}},Ne=X.length;return e.jsxs(i.Sheet,{open:x,onOpenChange:g,children:[e.jsx(gr,{disabled:a||!ye,briefingCount:Ne,className:l,onClick:z}),e.jsxs(i.SheetContent,{side:"right",hideClose:!0,className:"flex h-full w-full flex-col overflow-hidden p-0 sm:max-w-[560px]",children:[e.jsxs(i.SheetHeader,{className:"sr-only",children:[e.jsx(i.SheetTitle,{children:"Briefings"}),e.jsx(i.SheetDescription,{children:"Manage briefings for this dashboard."})]}),f==="list"?e.jsx(Ti,{briefings:X,dashboardLabel:Y,sourceView:A,error:_,loading:C,onSourceViewChange:S,onClose:()=>g(!1),onEdit:O=>{ve(O)},onNew:Pe,onRunNow:O=>{ke(O)},onTogglePause:O=>{Se(O)},onDelete:O=>B(O),selectingId:V,busyId:F,manageBriefingsHref:c}):e.jsx(fr,{apiServiceUrl:W,token:k,briefing:w,sourceContext:w?void 0:he,title:w?"Edit briefing":"Create briefing",className:"h-full min-h-0 max-w-none border-0 shadow-none",onBack:()=>b("list"),onCancel:()=>g(!1),onDeleted:()=>{i.ue.success("Briefing deleted"),y(null),b("list"),ie()},onRunStarted:()=>{},onSaved:O=>{y(O),ie()},onMinimizeRun:({briefing:O,run:ne})=>{Q({briefing:O,run:ne}),g(!1)}})]}),M&&W&&k?e.jsx(Bi,{briefingId:M.briefing.id,initialRun:M.run,apiServiceUrl:W,token:k,onTerminal:O=>{L({briefing:M.briefing,run:O}),Q(null),ie()},onTimeout:()=>{Q(null),ie()},onExpand:()=>{y(M.briefing),b("author"),Q(null),g(!0)}}):null,ee?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(Qo,{title:ee.run.status==="SUCCESS"?`${ee.briefing.name} is ready`:`${ee.briefing.name} run failed`,durationSeconds:ee.run.startedAt&&ee.run.completedAt?Math.max(0,Math.floor((new Date(ee.run.completedAt).getTime()-new Date(ee.run.startedAt).getTime())/1e3)):null,status:ee.run.status==="SUCCESS"?"success":"failed",onView:()=>{y(ee.briefing),b("author"),L(null),g(!0)},onDismiss:()=>L(null)})}):null,e.jsx(i.AlertDialog,{open:!!G,onOpenChange:O=>{O||B(null)},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:"Delete briefing?"}),e.jsxs(i.AlertDialogDescription,{children:["This permanently deletes ",e.jsx("strong",{children:G==null?void 0:G.name}),". Recipients will stop receiving it."]})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{children:"Cancel"}),e.jsx(i.AlertDialogAction,{className:"bg-destructive/90 hover:bg-destructive",onClick:q,children:"Delete briefing"})]})]})})]})}function Oi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-now-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}exports.AdvancedModeToggle=ha;exports.BriefingAuthor=fr;exports.BriefingsApiError=xt;exports.DashboardBriefingLauncher=Vi;exports.DashboardControlsSettings=Dn;exports.DashboardFilterControlsButton=An;exports.DashboardFilterControlsLauncher=Pa;exports.DocumentControlsSettings=En;exports.ExportNotificationItem=Sn;exports.ExportNotificationList=kn;exports.NotificationBell=Ca;exports.Undo2=Nn;exports.UnsavedChangesAlert=xa;exports.UsersRound=ns;exports.VisualEditingControls=ma;exports.VisualsLibraryDialog=oa;exports.WatchDashboardButton=gr;exports.applyBriefingFormPatch=lt;exports.briefingFormDraftToCreateRequest=Jt;exports.briefingFormDraftToUpdateRequest=sr;exports.briefingToFormDraft=He;exports.cancelBriefingPreviewRun=Vn;exports.cancelBriefingRun=On;exports.createBriefing=Rn;exports.createBriefingFormDraft=tr;exports.deleteBriefing=ls;exports.deleteBriefingRun=Un;exports.getBriefing=as;exports.getBriefingArtifact=Ua;exports.getBriefingEvidence=$a;exports.getBriefingPreviewRun=Bn;exports.getBriefingRun=ds;exports.listBriefingRuns=Oa;exports.listBriefingTenantSummaries=Va;exports.listBriefings=Fn;exports.pauseBriefing=os;exports.polishBriefingText=$n;exports.previewBriefingPlan=Pn;exports.resumeBriefing=is;exports.runBriefingNow=cs;exports.runBriefingPreview=Mn;exports.updateBriefing=ft;exports.useExportPolling=va;exports.useExportRecovery=Na;exports.validateBriefingFormDraft=Yt;