react-semaphor 0.1.376 → 0.1.377

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 (60) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +47 -43
  3. package/dist/brand-studio/index.cjs +4 -4
  4. package/dist/brand-studio/index.js +10 -8
  5. package/dist/chunks/braces-C2uBgj3t.js +6 -0
  6. package/dist/chunks/braces-CkXyWzRh.js +23 -0
  7. package/dist/chunks/{calendar-preferences-dialog-B6fsethx.js → calendar-preferences-dialog-C55VOTIy.js} +6 -5
  8. package/dist/chunks/calendar-preferences-dialog-DAukJOaP.js +1 -0
  9. package/dist/chunks/catalog-field-grounding-BGW0hnB9.js +1 -0
  10. package/dist/chunks/catalog-field-grounding-DHXEI7cW.js +199 -0
  11. package/dist/chunks/{chevrons-up-down-lahj6tQy.js → chevrons-up-down-BnzChFLU.js} +1 -1
  12. package/dist/chunks/{chevrons-up-down-D2fZD4N_.js → chevrons-up-down-W0nzHzx0.js} +1 -1
  13. package/dist/chunks/{dashboard-briefing-launcher-BKCRO7Qw.js → dashboard-briefing-launcher-CUyeiL_T.js} +3153 -2392
  14. package/dist/chunks/dashboard-briefing-launcher-DMKfG_z3.js +111 -0
  15. package/dist/chunks/dashboard-controls-B4hxFc3Q.js +2279 -0
  16. package/dist/chunks/dashboard-controls-D4vI0wvU.js +52 -0
  17. package/dist/chunks/dashboard-json-DQnm6daE.js +1 -0
  18. package/dist/chunks/{dashboard-json-QT0T2ad_.js → dashboard-json-pl1_mFqJ.js} +14 -13
  19. package/dist/chunks/{edit-dashboard-visual-kNoMQRmH.js → edit-dashboard-visual-CF4aSsav.js} +1489 -1488
  20. package/dist/chunks/{edit-dashboard-visual-DNzPgXMh.js → edit-dashboard-visual-CjTXY51a.js} +1 -1
  21. package/dist/chunks/{index-CPpqPJba.js → index-B2kPleRS.js} +4 -4
  22. package/dist/chunks/{index-DX_0OcRv.js → index-Bn866BBY.js} +67 -67
  23. package/dist/chunks/layout-grid-BFmJ7vmH.js +16 -0
  24. package/dist/chunks/layout-grid-CTOW9oTg.js +6 -0
  25. package/dist/chunks/{palette-BcHHAmOU.js → palette-DrhPeer-.js} +1 -1
  26. package/dist/chunks/{palette-2HWSR5wb.js → palette-OFaniMPn.js} +1 -1
  27. package/dist/chunks/{save-MoF1T13_.js → save-BxWBiQv1.js} +1 -1
  28. package/dist/chunks/{save-B-YfAPhu.js → save-Dh6gSC4x.js} +1 -1
  29. package/dist/chunks/{switch-DmE_MY3L.js → switch-C-fGjxjY.js} +1 -1
  30. package/dist/chunks/{switch-CmHP5dT7.js → switch-D5xopzFD.js} +1 -1
  31. package/dist/chunks/{use-create-flow-overlay-state-BLPQgGuz.js → use-create-flow-overlay-state-Dg2ffpCE.js} +2 -2
  32. package/dist/chunks/{use-create-flow-overlay-state-D_Ntx-_C.js → use-create-flow-overlay-state-DrKP0jWE.js} +113 -112
  33. package/dist/chunks/{validation-1V7bWmYw.js → validation-BHFaWDU-.js} +1 -1
  34. package/dist/chunks/{validation-DlrTIf1N.js → validation-bMedDBOo.js} +1 -1
  35. package/dist/dashboard/index.cjs +1 -1
  36. package/dist/dashboard/index.js +1 -1
  37. package/dist/dashboard-authoring/index.cjs +1 -1
  38. package/dist/dashboard-authoring/index.js +1 -1
  39. package/dist/data-app-builder/index.cjs +1 -1
  40. package/dist/data-app-builder/index.js +3 -3
  41. package/dist/data-app-sdk/index.cjs +1 -1
  42. package/dist/data-app-sdk/index.js +22 -21
  43. package/dist/data-app-sdk-validation/index.cjs +1 -1
  44. package/dist/data-app-sdk-validation/index.js +2 -2
  45. package/dist/index.cjs +1 -1
  46. package/dist/index.js +127 -125
  47. package/dist/surfboard/index.cjs +1 -1
  48. package/dist/surfboard/index.js +2 -2
  49. package/dist/types/analytics-protocol.d.ts +84 -0
  50. package/dist/types/main.d.ts +7 -0
  51. package/package.json +1 -1
  52. package/dist/chunks/calendar-preferences-dialog-Dh1b0ytN.js +0 -1
  53. package/dist/chunks/catalog-field-grounding-DoEBOXQd.js +0 -100
  54. package/dist/chunks/catalog-field-grounding-Du6mKDcF.js +0 -1
  55. package/dist/chunks/dashboard-briefing-launcher-Gv1cwT0I.js +0 -111
  56. package/dist/chunks/dashboard-controls-BDJZarV7.js +0 -52
  57. package/dist/chunks/dashboard-controls-CchLBVDv.js +0 -3037
  58. package/dist/chunks/dashboard-json-ZhIEMXN0.js +0 -1
  59. package/dist/chunks/layout-grid-BOTLt36V.js +0 -36
  60. package/dist/chunks/layout-grid-CS6BSCJF.js +0 -11
@@ -0,0 +1,111 @@
1
+ "use strict";const e=require("react/jsx-runtime"),h=require("react"),i=require("./index-B2kPleRS.js"),a=require("./switch-D5xopzFD.js"),Jt=require("./layout-grid-CTOW9oTg.js"),ue=require("./use-create-flow-overlay-state-Dg2ffpCE.js");require("./index-BxM99sFL.js");require("./catalog-field-grounding-BGW0hnB9.js");const qs=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 Xr=a.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 Qr=a.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 Hs=a.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 Jr=a.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 Yr=a.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 vn=a.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 qt=a.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 Zr=a.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 Nn=a.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 wn=a.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 Yt=a.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 Ht=a.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 ea(){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 ta({open:t,onOpenChange:s,onSubmit:n,isCreating:r}){const[o,l]=h.useState(""),[c,u]=h.useState("");h.useEffect(()=>{t||(l(""),u(""))},[t]);const d=()=>{o.trim()&&n({title:o,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(Jt.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(a.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(a.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(a.Label,{htmlFor:"visual-title",className:"text-[12px]",children:"Name"}),e.jsx(a.Input,{id:"visual-title",size:"sm",placeholder:"Untitled visual",value:o,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(a.Label,{htmlFor:"visual-description",className:"text-[12px]",children:"Description"}),e.jsx(a.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(a.Button,{size:"xs",variant:"outline",onClick:()=>m(!1),disabled:r,children:"Cancel"}),e.jsx(a.Button,{size:"xs",onClick:d,disabled:!o.trim()||r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Creating..."]}):"Create library visual"})]})]})})}function Cn(t){return t?new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Unknown"}function Sn(t,s){var r;const n=(r=t.ownership.createdBy)==null?void 0:r.type;return n==="tenant"||n==="organization"&&s}function Zt(t,s){var n,r;return Sn(t,s)?((n=t.ownership.createdBy)==null?void 0:n.name)||((r=t.createdByTenantUserRel)==null?void 0:r.name)||t.lastModifiedBy||"Unknown":"Organization"}function sa(t,s){return Zt(t,s).split(/\s+/).filter(Boolean).slice(0,2).map(r=>r.charAt(0).toUpperCase()).join("")||"?"}function na(t){const s=(t||"").toLowerCase();return s.includes("table")?a.Table2:s.includes("pie")||s.includes("donut")?i.ChartPie:s.includes("line")?i.ChartLine:s.includes("bar")?a.ChartColumn:Jt.LayoutGrid}function ra({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 aa({open:t,onOpenChange:s}){const[n,r]=h.useState(""),[o,l]=h.useState(new Set),[c,u]=h.useState(!1),[d,m]=h.useState(null),[x,g]=h.useState(null),[p,b]=h.useState(!1),[A,N]=h.useState(null),[w,j]=h.useState(null),C=()=>{l(new Set),m(null),g(null),b(!1),N(null)},y=()=>{s(!1),C()},{selectVisual:S}=i.useManagementActions(),{handleAddLibraryVisual:T,handleEditLibraryVisual:V}=ue.useVisualUtils(),{isConsoleMode:D}=i.useDashboardPreferences(),{resources:F,isLoading:U,isError:q,createResource:B,updateResource:_,deleteResourceAsync:$,duplicateResource:P,isCreating:G,isDeleting:Y}=i.useVisualManagement(void 0,E=>{u(!1),E&&(S(E),V(E),y())}),{startUpdating:L,stopUpdating:K,isUpdating:k}=i.useResourceUpdateState(),ae=F,Q=h.useMemo(()=>{const E=n.trim().toLowerCase();return E?ae.filter(z=>{var Z,ve,Me;return((Z=z.title)==null?void 0:Z.toLowerCase().includes(E))||((ve=z.description)==null?void 0:ve.toLowerCase().includes(E))||((Me=z.kind)==null?void 0:Me.toLowerCase().includes(E))}):ae},[n,ae]),X=h.useMemo(()=>ae.filter(E=>o.has(E.id)),[o,ae]),me=X.filter(E=>E.permissions.canDelete),je=X.filter(E=>E.permissions.canShare),oe=Q.length>0&&Q.every(E=>o.has(E.id)),H=Q.some(E=>o.has(E.id)),Re=E=>{const z=new Set(o);E(z),l(z)},ye=E=>{Re(z=>{z.has(E)?z.delete(E):z.add(E)})},Se=()=>{l(E=>{const z=new Set(E);return oe?Q.forEach(Z=>z.delete(Z.id)):Q.forEach(Z=>z.add(Z.id)),z})},Ne=async E=>{(await T(E)).success&&y()},W=async()=>{const E=X;if(E.length===0)return;let z=!1;for(const Z of E)if(!(await T(Z)).success){z=!0;break}z||y()},we=E=>{V(E),y()},O=E=>{j(E),P(E,{onSettled:()=>j(null)})},se=()=>{if(me.length===0){i.ue.error("Select a visual you can delete");return}N(null),b(!0)},ze=async()=>{const E=A?[A]:me;try{for(const z of E)await $(z.id);l(z=>{const Z=new Set(z);return E.forEach(ve=>Z.delete(ve.id)),Z}),b(!1),N(null)}catch{}},Ve=()=>{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:z})=>{if(!x)return;const Z={};if(E!==x.title&&(Z.title=E),(x.description||"")!==z&&(Z.description=z),Object.keys(Z).length===0){g(null);return}const ve=Object.keys(Z),Me=ve.length===1?ve[0]:void 0;L(x.id,Me),_({resourceId:x.id,data:Z},{onSuccess:()=>{K(x.id,Me),g(null)},onError:()=>{K(x.id,Me)}})},M=E=>{s(E),E||C()},xe=A?1:me.length;return e.jsxs(e.Fragment,{children:[e.jsx(i.Dialog,{open:t,onOpenChange:M,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(a.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(a.Button,{size:"xs",variant:"ghost",className:"w-7 px-0 text-muted-foreground hover:text-foreground",onClick:()=>M(!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(i.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(a.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(ea,{})}):q?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"})}):Q.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-12 text-center",children:[e.jsx(Jt.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(oa,{visuals:Q,selectedIds:o,allFilteredSelected:oe,someFilteredSelected:H,onSelectAll:Se,onToggleSelection:ye,onAddVisual:Ne,onOpenVisual:we,onEditDetails:g,onShareVisual:m,onDeleteVisual:E=>{N(E),b(!0)},onDuplicateVisual:O,duplicatingId:w,isDeleting:Y,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:o.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:o.size})," ","selected"]}),e.jsx(a.Button,{size:"xs",variant:"ghost",onClick:()=>l(new Set),children:"Clear"}),e.jsxs(a.Button,{size:"xs",variant:"outline",onClick:Ve,disabled:X.length!==1||je.length!==1,children:[e.jsx(i.Share2,{className:"h-3.5 w-3.5"}),"Share"]}),e.jsxs(a.Button,{size:"xs",variant:"outline",className:"text-destructive hover:text-destructive",onClick:se,disabled:me.length===0,children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete ",me.length||o.size]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Button,{size:"xs",variant:"outline",onClick:()=>M(!1),children:"Close"}),e.jsxs(a.Button,{size:"xs",onClick:W,disabled:o.size===0,children:[e.jsx(a.Check,{className:"h-3.5 w-3.5"}),o.size===0?"Add to dashboard":`Add ${o.size} visual${o.size===1?"":"s"}`]})]})]})]})}),e.jsx(ta,{open:c,onOpenChange:u,onSubmit:B,isCreating:G}),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:p,onOpenChange:E=>{!E&&Y||(b(E),E||N(null))},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsxs(i.AlertDialogTitle,{children:["Delete ",xe," visual",xe===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:Y,children:"Cancel"}),e.jsxs(i.AlertDialogAction,{onClick:E=>{E.preventDefault(),ze()},disabled:Y||xe===0,children:[Y?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),Y?"Deleting...":"Delete"]})]})]})})]})}function oa({visuals:t,selectedIds:s,allFilteredSelected:n,someFilteredSelected:r,onSelectAll:o,onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:p,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:o,"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(N=>e.jsx(ia,{visual:N,selected:s.has(N.id),onToggleSelection:l,onAddVisual:c,onOpenVisual:u,onEditDetails:d,onShareVisual:m,onDeleteVisual:x,onDuplicateVisual:g,duplicatingId:p,isDeleting:b,isConsoleMode:A},N.id))]})}function ia({visual:t,selected:s,onToggleSelection:n,onAddVisual:r,onOpenVisual:o,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g}){var A;const p=na(t.kind),b=()=>{r(t)};return e.jsxs("div",{className:a.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(p,{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:sa(t,g)}),e.jsx("span",{className:"truncate text-muted-foreground",children:Zt(t,g)})]}),e.jsx("span",{className:"text-muted-foreground",children:Cn(t.updatedAt)}),e.jsx(ra,{visual:t}),e.jsx("span",{className:"text-right tabular-nums text-muted-foreground",children:t.ownership.sharedCount>0?t.ownership.sharedCount:"—"}),e.jsx(la,{visual:t,onOpenVisual:o,onEditDetails:l,onShareVisual:c,onDeleteVisual:u,onDuplicateVisual:d,duplicatingId:m,isDeleting:x,isConsoleMode:g})]})}function la({visual:t,onOpenVisual:s,onEditDetails:n,onShareVisual:r,onDeleteVisual:o,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(a.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(a.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(a.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:()=>o(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:[Sn(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:Zt(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:Cn(t.updatedAt)})]})]})]})]})]})}function ca({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:o=!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(),p=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||o||c({name:u.trim(),description:m.trim()||void 0,saveToLibrary:p.saveToLibrary,saveToCurrentDashboard:p.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"}),p.badgeType!=="local"&&e.jsx(ue.VisualBadge,{type:p.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(i.DialogDescription,{children:p.description})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(a.Label,{htmlFor:"name",children:"Name"}),e.jsx(a.Input,{id:"name",value:u,onChange:A=>d(A.target.value),placeholder:"Enter visual name",disabled:o})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(a.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:o})]})]}),e.jsxs(i.DialogFooter,{children:[e.jsx(a.Button,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancel"}),e.jsxs(a.Button,{onClick:b,disabled:!g||o,children:[o&&e.jsx(a.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p.actionLabel]})]})]})})}function da(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[o,l]=h.useState(null),[c,u]=h.useState(null),d=a.useEditorStore(D=>D.frame),m=a.useEditorStore(D=>D.card),x=i.useSelectedVisual(),g=a.useDashboardStore(D=>D.selectedSheetId),p=a.useDashboardStore(D=>D.dashboard),{getUpdatedFrame:b}=ue.useVisualUtils(),{selectVisual:A}=i.useManagementActions(),{addFrame:N,setSelectedFrameId:w,setIsVisualEditing:j}=a.useDashboardActions(),C=i.useResolveExistingFrameSemanticExecutionPayload(),y=!!(d!=null&&d.visualId),S=(()=>{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&&o&&c&&g&&(async()=>{try{const F={...o,id:a.v4(),visualId:D.id};N(g,F,{position:"end",semanticExecutionPayload:c}),w(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=a.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 C(B,{previousFrame:i.findDashboardFrameById(p,B.id)})}catch(P){console.error("Failed to prepare semantic metadata before saving visual:",P),i.ue.error(P instanceof Error?P.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:a.v4(),visualId:void 0};try{const $=await C(B,{previousFrame:i.findDashboardFrameById(p,B.id)});N(g,_,{position:"end",semanticExecutionPayload:$}),w(_.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:S,isSaving:T.isPending}}function ua(t={}){const s=a.useEditorStore(B=>B.frame),n=a.useEditorStore(B=>B.editorContext),r=i.useManagementStore(B=>B.selectedVisual),o=a.useDashboardStore(B=>B.selectedFrameId),l=a.useDashboardStore(B=>B.selectedSheetId),c=a.useDashboardStore(B=>B.dashboard),{setIsVisualEditing:u,updateFrame:d}=a.useDashboardActions(),[m,x]=h.useState(!1),[g,p]=h.useState("both"),b=i.useResolveExistingFrameSemanticExecutionPayload(),A=(n==null?void 0:n.type)==="documentSection",N=!!(s!=null&&s.visualId||r!=null&&r.id),w=!!(s!=null&&s.visualId&&o),j=N&&!w,{saveAsDialogOpen:C,setSaveAsDialogOpen:y,handleSaveAs:S,isLibraryVisual:T,currentVisualName:V,isSaving:D}=da(),{getUpdatedFrame:F}=ue.useVisualUtils();if(A)return e.jsxs(e.Fragment,{children:[e.jsx(ue.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(ue.EditorCancelButton,{})]});const U=async()=>{if(!l){i.ue.error("No sheet selected");return}if(m)return;x(!0);const B=F(),_=a.getDynamicFrameSaveIssue(B);if(_){x(!1),i.ue.error(_);return}const $={...B,visualId:void 0},P=i.findDashboardFrameById(c,$.id);try{const G=await b($,{previousFrame:P});d(l,$,{semanticExecutionPayload:G})}catch(G){console.error("Failed to apply local semantic metadata:",G),x(!1),i.ue.error(G instanceof Error?G.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)},q=B=>{p(B),y(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!N&&e.jsx(ue.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),N&&j&&e.jsx(ue.VisualSaveButton,{className:"!rounded-none",variant:"default"}),N&&w&&e.jsx(ue.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.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(a.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:[w&&e.jsxs(e.Fragment,{children:[e.jsxs(i.DropdownMenuItem,{onClick:U,disabled:m,children:[e.jsx(a.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(i.DropdownMenuSeparator,{})]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>q("local"),disabled:D,children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>q("library"),disabled:D,children:[e.jsx(ue.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>q("both"),disabled:D,children:[e.jsx(ue.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(ue.EditorCancelButton,{}),e.jsx(ca,{open:C,onOpenChange:B=>{D||y(B)},isLibraryVisual:T,currentVisualName:V,isSaving:D,destinationMode:g,onConfirm:S})]})}function ma({className:t}){const s=a.useEditorStore(m=>m.isDevMode),n=a.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=a.useEditorActions(),{config:o}=h.useContext(i.SemaphorContext).tokenProps,l=(o==null?void 0:o.showAdvancedMode)!==!1;if(!n||!l)return null;const c=s?a.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:a.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 ha({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:o,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&&o||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(a.Button,{type:"button",size:"xs",onClick:r,disabled:o,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:o,children:u}),e.jsx(a.Button,{type:"button",size:"xs",onClick:n,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(a.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):m})]})]})})}const xa=1e4,pa=15e3,fa=3e4,ga=3e4,ba=12e4,Ks=2*60*60*1e3;function ja(t){const s=Date.now()-t.getTime();return s<ga?xa:s<ba?pa:fa}function ya(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(p=>p.activeExports),[r,o]=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 p=i.useExportStore.getState().activeExports;return Array.from(p.values()).filter(b=>i.isExportInProgress(b.status))},[]);h.useEffect(()=>{if(typeof document>"u")return;const p=()=>{o(!document.hidden)};return document.addEventListener("visibilitychange",p),()=>{document.removeEventListener("visibilitychange",p)}},[]);const g=h.useCallback(async()=>{if(!d||!m){c.current=!1;return}const p=x();if(p.length===0){c.current=!1;return}const b=Date.now(),A=p.filter(y=>b-y.startedAt.getTime()>Ks);if(A.length>0){const{updateExport:y}=i.useExportStore.getState().actions;for(const S of A)y(S.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const N=p.filter(y=>b-y.startedAt.getTime()<=Ks);if(N.length===0){c.current=!1;return}const w=await Promise.allSettled(N.map(async y=>{try{const S=await i.getExportStatus(d,m,y.id);let T;if(S.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:S.status,progress:S.progress,completedChunks:S.completedChunks,completedAt:S.completedAt?new Date(S.completedAt):void 0,lastUpdatedAt:new Date,fileSize:S.fileSize,error:S.error,downloadUrl:T}}catch(S){return console.error(`[useExportPolling] Failed to poll export ${y.id}:`,S),null}})),{updateExport:j}=i.useExportStore.getState().actions;for(const y of w)y.status==="fulfilled"&&y.value&&j(y.value.id,y.value);const C=x();if(C.length>0&&!document.hidden){const y=C.reduce((T,V)=>V.startedAt<T?V.startedAt:T,C[0].startedAt),S=ja(y);l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{var T;(T=u.current)==null||T.call(u)},S)}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 p=x();r&&p.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 va(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(u=>u.activeExports),{addExport:r}=i.useExportActions(),o=h.useRef(!1),l=s==null?void 0:s.apiServiceUrl,c=t==null?void 0:t.accessToken;h.useEffect(()=>{if(o.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 p={id:m.id,status:m.status,progress:x,title:Na(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(p)}o.current=!0}catch(d){console.error("[useExportRecovery] Failed to recover exports:",d),o.current=!0}})()},[l,c,r,n])}function Na(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 kn({export:t,onRemove:s}){const n=()=>{t.downloadUrl&&window.open(t.downloadUrl,"_blank")},r=u=>{u.stopPropagation(),s==null||s(t.id)},o=()=>{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(Qr,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"});default:return e.jsx(a.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:[o(),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(a.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(a.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:qs.formatDistanceToNow(t.startedAt,{addSuffix:!0})}),t.downloadUrl&&e.jsxs(a.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:qs.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function Dn(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(N=>N.activeExports),{clearCompleted:r,removeExport:o,updateExport:l}=i.useExportActions(),[c,u]=h.useState(!1),[d,m]=h.useState(!1),x=Array.from(n.values()).sort((N,w)=>w.startedAt.getTime()-N.startedAt.getTime()),g=x.some(N=>N.status==="completed"||N.status==="failed"),p=h.useCallback(async()=>{const N=s==null?void 0:s.apiServiceUrl,w=t==null?void 0:t.accessToken;if(!(!N||!w)){u(!0);try{const j=Array.from(n.values());await Promise.all(j.map(async C=>{try{const y=await i.getExportStatus(N,w,C.id);let S;if(y.status==="completed")try{S=await i.getDownloadUrl(N,w,C.id)}catch(T){console.error(`Failed to get download URL for ${C.id}:`,T)}l(C.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:S})}catch(y){console.error(`Failed to refresh export ${C.id}:`,y)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,l]),b=h.useCallback(async()=>{const N=s==null?void 0:s.apiServiceUrl,w=t==null?void 0:t.accessToken;if(!N||!w){r();return}m(!0);try{const j=x.filter(y=>y.status==="completed"||y.status==="failed"),C=await Promise.allSettled(j.map(async y=>(await i.cancelExport(N,w,y.id),y.id)));for(const y of C)y.status==="fulfilled"?o(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,o]),A=h.useCallback(async N=>{const w=s==null?void 0:s.apiServiceUrl,j=t==null?void 0:t.accessToken;if(w&&j)try{await i.cancelExport(w,j,N),o(N);return}catch(C){console.error(`Failed to cancel export ${N}:`,C)}o(N)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,o]);return x.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Hs,{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(Hs,{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(a.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:p,disabled:c,title:"Refresh status",children:e.jsx(i.RefreshCw,{className:`h-4 w-4 ${c?"animate-spin":""}`})}),g&&e.jsx(a.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(N=>e.jsx(kn,{export:N,onRemove:A},N.id))})})]})}function wa({variant:t}){const s=i.useExportStore(d=>d.activeExports),n=i.useInProgressExportsCount(),r=s.size>0,o=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(a.Popover,{children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs(a.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(a.PopoverContent,{className:"w-80 p-0",align:"end",sideOffset:8,children:e.jsx(Dn,{})})]})}function Ca(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 En({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:o="manage"}){const l=o==="create",{forceClose:c,handleOpenChange:u,isCreateFlowActive:d,preventPassiveDismissDuringCreate:m,resolvedOpen:x,setIsCreateFlowActive:g}=ue.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:o==="create",dismissMode:r?"passive":"explicit-only"}),p=a.useDashboardStore(F=>F.dashboard),{setDashboardControlsModel:b}=a.useDashboardActions(),{participants:A}=i.useDashboardStructuralParticipants(a.getDashboardCards(p)),N=Array.from(new Map(A.flatMap(F=>F.fieldChoices.map(U=>{var q;return[U.value,{option:U,target:(q=F.fieldTargetMap)==null?void 0:q[U.value]}]}))).values()),w=Array.from(new Map(A.flatMap(F=>F.metricChoices.map(U=>{var q;return[U.value,{option:U,target:(q=F.metricTargetMap)==null?void 0:q[U.value]}]}))).values()),j=a.collectDashboardControlIds({...p||{},controls:[]}),C=i.buildDashboardStructuralParticipantIdsByControlId(p),y=(F,U,q)=>{b(F,U,Ca(q))},S=h.useCallback(()=>{if(l){c();return}g(!1)},[l,c,g]),T=e.jsx(ue.ControlDefinitionListEditor,{scope:"dashboard",controls:p.controls||[],reservedControlIds:j,defaultValues:p.defaultControlValues||{},usageByControlId:i.buildDashboardControlUsageById(p),availableFieldChoices:N,availableMetricChoices:w,structuralParticipants:A,structuralParticipantIdsByControlId:C,initialCreateFlow:o==="create",onCreateFlowActiveChange:g,onCreateFlowComplete:S,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(a.Popover,{open:x,onOpenChange:u,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:n||e.jsxs(a.Button,{variant:"outline",className:"h-7 px-2",size:"sm",children:[e.jsx(a.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Controls"]})}),e.jsx(a.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 Sa=["enum","multi_enum","text","number","boolean","date"];function An({open:t,onOpenChange:s,initialMode:n="manage"}){var D;const r=n==="create",{forceClose:o,handleOpenChange:l,isCreateFlowActive:c,preventPassiveDismissDuringCreate:u,resolvedOpen:d,setIsCreateFlowActive:m}=ue.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),x=a.useDashboardStore(F=>F.dashboard),g=a.useDashboardStore(F=>F.selectedSheetId),{setDashboardInputs:p}=a.useDashboardActions(),b=(D=x.sheets)==null?void 0:D.find(F=>F.id===g),A=(b==null?void 0:b.kind)==="document"&&!!b.document,N=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]),w=h.useMemo(()=>N.filter(F=>F.kind==="control"),[N]),j=h.useMemo(()=>w.map(F=>F.control),[w]),C=h.useMemo(()=>Da(j),[j]),y=h.useMemo(()=>ka(x),[x]),S=h.useCallback(()=>{if(r){o();return}m(!1)},[r,o,m]),T=h.useCallback((F,U,q)=>{!A||!(b!=null&&b.document)||p(Aa({allInputs:x.inputs||[],documentSheetId:b.id,currentDocumentInputs:N,nextControls:F,nextDefaultValues:U,change:q}))},[x.inputs,N,A,b,p]);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(ue.ControlDefinitionListEditor,{scope:"dashboard",controls:j,reservedControlIds:y,defaultValues:C,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:Sa,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:S,onChange:T,emptyMessage:"No document controls yet."})})]})})}function ka(t){return(t.controls||[]).map(s=>s.id)}function Da(t){const s={};for(const n of t)n.defaultValue!==void 0&&(s[n.id]=n.defaultValue);return s}function Ea(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 Aa({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:o,change:l}){const c=new Map(r.map(p=>[p.id,Ea(p,o)])),u=(l==null?void 0:l.type)==="rename"?{oldId:l.oldId,newId:l.newId}:null,d=new Set,m=[];for(const p of n){if(p.kind!=="control"){m.push(p);continue}const b=c.get(p.control.id)||((u==null?void 0:u.oldId)===p.control.id?c.get(u.newId):void 0);if(!b)continue;d.add(b.id);const A=i.createUniqueDashboardInputVariableNameFromName(b.id,[...t,...m].filter(w=>w.id!==p.id)),N=b.id===A?b:{...b,id:A};m.push({...p,label:N.label,variableName:A,requiredAtExecution:N.requiredAtExecution,control:N})}for(const p of c.values())d.has(p.id)||m.push(i.createDashboardControlInputFromControl({control:p,existingInputs:[...t,...m],sheetId:s}));const x=new Set(n.map(p=>p.id));return[...t.filter(p=>!x.has(p.id)),...m]}function In({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:o="default",className:l,primaryButtonClassName:c,secondaryButtonClassName:u,pickerContentClassName:d,settingsContentClassName:m}){const x=o==="toolbar",[g,p]=h.useState(!1),b=i.useSurfaceAppearance("interactive");return e.jsxs("div",{className:a.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",x?"h-8":"h-7",l),children:[e.jsxs(a.Popover,{open:t,onOpenChange:s,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs(a.Button,{variant:"ghost",size:"xs",className:a.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(Jr,{className:"h-3.5 w-3.5"}):e.jsx(i.Filter,{className:"h-3.5 w-3.5"}),"Filter"]})}),e.jsx(a.PopoverContent,{align:"end",sideOffset:6,className:a.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",d),style:b.contentStyle,children:n})]}),e.jsxs(a.Popover,{open:g,onOpenChange:p,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsx(a.Button,{variant:"ghost",size:"xs",className:a.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(a.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsx(a.PopoverContent,{align:"end",sideOffset:6,className:a.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",m),style:b.contentStyle,children:r(()=>p(!1))})]})]})}function Ia(){ue.useSyncLegacyEditorState();const t=a.useDashboardStore(d=>d.selectedSheetId),s=a.useDashboardStore(d=>d.selectedFrameId),n=a.useDashboardStore(d=>d.dashboard),r=a.useDashboardStore(d=>d.actions.getSelectedFrame),{setSelectedFrameId:o}=a.useDashboardActions(),{setCard:l}=a.useEditorActions(),c=a.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),p=(x=g==null?void 0:g.frames)==null?void 0:x[0];p&&(o(p.id),d=p)}if(d){const g=d.cards.find(p=>p.id===d.activeCardId);g&&l(g)}},[r,t,s,n,o,l]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function Ta(){const t=a.useDashboardStore(d=>d.dashboard),s=a.useDashboardStore(d=>d.semanticExecutionPayload),n=a.useDashboardStore(d=>d.actions.addFilter),{hasEntities:r}=Ia(),{isLoading:o}=i.useFilterableFields(),l=h.useMemo(()=>i.getGlobalDateFilterCoverage(t,s),[t,s]),u=!i.getGlobalDateFilter(t.filters)&&l.hasEligibleCards&&!o;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 Ws=!1;function La({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const o=a.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:l}=a.useDashboardActions();o!=null&&o.displayMode;const c=(o==null?void 0:o.toolbarWrap)??!1;return o==null||o.showDownloadButton,e.jsxs("div",{className:"w-[300px]",children:[e.jsxs("div",{className:"p-1",children:[e.jsx(Mt,{icon:i.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(Mt,{icon:a.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(Mt,{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"}),Ws,e.jsx(Fa,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:c,onCheckedChange:u=>l({toolbarWrap:u===!0})}),Ws]})]})}function Mt({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 Fa({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(a.Label,{htmlFor:t,className:"cursor-pointer text-[12px] font-normal leading-[1.3]",children:s})]})}function Ra({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:l}){var V;const[c,u]=h.useState(null),d=a.useDashboardStore(D=>D.dashboard),m=a.useDashboardStore(D=>D.selectedSheetId),x=a.useDashboardStore(D=>D.showFilters),g=i.useAssistantLayoutStore(D=>D.setPanelOpen),p=a.useDashboardStore(D=>D.actions),{setDocumentInspectorTab:b,setShowFilters:A}=p,N=(V=d.sheets)==null?void 0:V.find(D=>D.id===m),w=a.isDocumentSheet(N),j=h.useCallback(D=>{window.setTimeout(()=>{u(D)},0)},[]),C=h.useCallback(D=>{if(w&&m){D&&b(m,"inputs");return}D&&g("dashboard",!1),A(D)},[w,m,b,g,A]),y=h.useCallback(()=>{C(!0)},[C]),S=h.useCallback(()=>{j("create")},[j]),T=h.useCallback(()=>{j("manage")},[j]);return e.jsxs(e.Fragment,{children:[e.jsx(In,{showFilters:w?!1:x,onShowFiltersChange:C,pickerContent:e.jsx(Ta,{}),settingsContent:D=>e.jsx(La,{onAddFilter:y,onAddControl:S,onManageControls:T,onDismiss:D}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:l}),c?w?e.jsx(An,{open:!0,onOpenChange:D=>{D||u(null)},initialMode:c}):e.jsx(En,{open:!0,onOpenChange:D=>{D||u(null)},showTrigger:!1,initialMode:c}):null]})}class ht extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function Tn(t,s){return`${t.replace(/\/$/,"")}${s}`}function he(t){return encodeURIComponent(t)}function xt(t){const s=new URLSearchParams;Object.entries(t).forEach(([r,o])=>{o!==void 0&&o!==""&&s.set(r,String(o))});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 Ln(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 o=await fetch(Tn(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 o.json().catch(()=>({}));if(!o.ok)throw new ht(Ln(l)||"Briefings API request failed",o.status,l);return l}async function Fn(t,s,n,r){const o=await fetch(Tn(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){const l=await Ma(o);throw new ht(Ln(l)||"Briefing artifact request failed",o.status,l)}return{kind:r,content:await o.text(),contentType:o.headers.get("content-type")??"text/plain",filename:Pa(o.headers.get("content-disposition"))}}function Pa(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function Rn(t,s,n){return pe(t,s,`/v1/briefings${xt({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 Ba(t,s,n){return pe(t,s,`/v1/briefings/tenant-summaries${xt({status:n==null?void 0:n.status})}`)}async function es(t,s,n){return pe(t,s,`/v1/briefings/${he(n)}`)}async function Mn(t,s,n){return pe(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function pt(t,s,n,r){return pe(t,s,`/v1/briefings/${he(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function ts(t,s,n){return pt(t,s,n,{status:"PAUSED"})}async function ss(t,s,n){return pt(t,s,n,{status:"ACTIVE"})}async function ns(t,s,n){return pe(t,s,`/v1/briefings/${he(n)}`,{method:"DELETE"})}async function rs(t,s,n,r){return pe(t,s,`/v1/briefings/${he(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 Bn(t,s,n){return pe(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function Vn(t,s,n){return(await pe(t,s,`/v1/briefings/preview-runs/${he(n)}`)).previewRun}async function Va(t,s,n,r){return pe(t,s,`/v1/briefings/${he(n)}/runs${xt({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function as(t,s,n,r){return(await pe(t,s,`/v1/briefings/${he(n)}/runs/${he(r)}`)).run}async function On(t,s,n,r){return pe(t,s,`/v1/briefings/${he(n)}/runs/${he(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Un(t,s,n,r){return pe(t,s,`/v1/briefings/${he(n)}/runs/${he(r)}`,{method:"DELETE"})}async function Oa(t,s,n,r,o){return Fn(t,s,`/v1/briefings/${he(n)}/runs/${he(r)}/artifact${xt({kind:o})}`,o)}async function Ua(t,s,n,r){return Fn(t,s,`/v1/briefings/${he(n)}/runs/${he(r)}/evidence`,"evidence")}async function $n(t,s,n){var o;const r=await pe(t,s,"/v1/ai/generate",{method:"POST",body:JSON.stringify({type:"polish-text",context:{text:n}})});if(!r.success||!((o=r.result)!=null&&o.polished))throw new ht(r.error||"Polish returned no result",502,r);return r.result.polished}const $a={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},_a={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function De(t){return re(t)}function Gs(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 os(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 za(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 qa(t,s){return _n(t).includes(s)?{...De(t),format:s,settings:Hn(t.settings,s)}:De(t)}function Ha(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...De(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 o=a.getDashboardSheets(n.sheets),l=o.find(d=>d.id===t.selectedSheetId)??o[0];l&&r.push({key:`dashboard_sheet:${s}:${l.id}`,kind:"dashboard_sheet",title:`${Bt(l)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:l.id,formats:["pdf"],defaultFormat:"pdf"});for(const d of n.sheets||[])a.isDocumentSheet(d)&&r.push({key:`document_sheet:${s}:${d.id}`,kind:"document_sheet",title:`${Bt(d)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:d.id,formats:["pdf"],defaultFormat:"pdf"});if(l)for(const d of Wn(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:`${Bt(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 Kt(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Ka({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:Pt(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:Pt(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:Pt(s.cardId),format:n,title:s.title,settings:r}}}function Xs(t){const s=zn(t),n=s.find(l=>l.kind==="dashboard_sheet"),o=s.find(l=>l.kind==="dashboard")??n;return o?[Kt({option:o,runtime:t.runtime})]:[]}function Ka(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=re(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=re(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=re(t.option.tablePreferences))),Wa({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Ya(s.filterValues)),s}function Wa(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Ga({settings:s,option:n,runtime:r});return}const o=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:o,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});s.sheetFilterValues=re(c.filterValues),s.filterValues=re(c.filterValues),s.controlValues=re(c.controlValues),r.controlDefinitions&&(s.controlDefinitions=re(r.controlDefinitions));const u=Xa({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&o==="all"?void 0:l,sheetSelection:o});u&&(s.dashboardInputExecutionSnapshot=re(u))}function Ga(t){var m,x,g;const{settings:s,option:n,runtime:r}=t,o=n.cardId,l=i.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=re(l),!o){s.filterValues=re(l),s.controlValues=re(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=re(r.controlDefinitions));return}const c=((m=r.inlineFilterValuesMap)==null?void 0:m[o])||[];c.length>0&&(s.inlineFilterValues=re(c));const u=i.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:o,interactionStates:r.interactionStates||{},currentDashboardId:(x=r.dashboard)==null?void 0:x.id,semanticExecutionPayload:r.semanticExecutionPayload,filters:r.filters,filterValues:r.filterValues,inlineFilterValuesMap:{...r.inlineFilterValuesMap||{},[o]:c},dashboardControls:r.dashboardControls||r.controlDefinitions,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});u?(s.filterValues=re(u.queryContext.cardFilterValues),s.controlValues=re(u.queryContext.controlValues),s.controlDefinitions=re(u.queryContext.controlDefinitions),s.cardControlDefinitions=re(u.queryContext.cardControlDefinitions),s.controlBindings=re(u.queryContext.controlBindings)):(s.filterValues=re(l),s.controlValues={...r.controlValues||{},...((g=r.cardControlValuesMap)==null?void 0:g[o])||{}},r.controlDefinitions&&(s.controlDefinitions=re(r.controlDefinitions)));const d=Qa({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:c,controlValues:s.controlValues});d&&(s.dashboardInputExecutionSnapshot=re(d))}function Xa(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 o=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:o,timezone:l}).snapshot;const c=t.sheetSelection==="all"?a.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:o,timezone:l}).snapshot}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)||!s.cardId)return;const o=Ja(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:(o==null?void 0:o.sheet.id)||s.sheetId,cardId:s.cardId,sheetKind:"dashboard"}):n.dashboardInputValues;return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:(o==null?void 0:o.sheet.id)||s.sheetId,card:(o==null?void 0:o.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 Ja(t,s,n){const r=t.sheets||[],o=s?r.filter(l=>l.id===s):r;for(const l of o)for(const c of Wn(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 Ya(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"?{..._a,...t}:{...$a,...t}}function Kn(t){return t?i.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function Wn(t){const s=[],n=new Set,r=(o,l)=>{!(o!=null&&o.id)||n.has(o.id)||(n.add(o.id),s.push({card:o,frame:l}))};for(const o of t.cards||[])r(o);for(const o of t.frames||[])for(const l of o.cards||[])r(l,o);return s}function Pt(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function Bt(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function re(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Gn=["markdown"],Za={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Gn],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 eo(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(De),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 to(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 is(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,o)=>(t[o]!==void 0&&(r[o]=t[o]),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 so(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Gn],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 no(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function ro(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 ao(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function oo(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function Vt(t,s,n,r,o){ao(n,r,o)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${o}`})}function tr(t){return it(Za,t??{})}function it(t,s){var c,u,d,m;const n=s.instruction??(s.body?to(s.body):t.instruction),r=Qn(s.body?{...s.body}:{...t.body},n),o=(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{...eo(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(De):t.attachments.map(De),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:o,channelConfigs:l},limits:{...t.limits,...s.limits}}}function qe(t){return{name:t.name,description:t.description??"",instruction:no(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(De),output:so(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:ro(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function Wt(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:is(t),attachments:t.attachments.map(De),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:is(t),attachments:t.attachments.map(De),presentation:Jn(t.output),limits:Yn(t.limits),deliveryConfig:er(t.delivery)}}function Gt(t){var r,o,l,c,u;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=is(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"&&!oo(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=(o=m==null?void 0:m.webhookConfig)==null?void 0:o.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 Vt(s,"maxToolCalls",t.limits.maxToolCalls,1,100),Vt(s,"maxRows",t.limits.maxRows,1,1e5),Vt(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const Ze="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function io({attachment:t,open:s,onOpenChange:n,onChange:r,children:o}){const l=_n(t),c=t.settings||{},u=t.format==="csv",d=m=>{r(Ha(t,m))};return e.jsxs(a.Popover,{open:s,onOpenChange:n,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:o}),e.jsxs(a.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:a.cn(Ze,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:os(t)})]}),l.length>1?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Ze,"mb-1 block"),children:"Format"}),e.jsxs(a.Select,{value:t.format,onValueChange:m=>r(qa(t,m)),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:l.map(m=>e.jsx(a.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(co,{settings:c,onChange:d}):e.jsx(lo,{settings:c,onChange:d})]})]})}function lo({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:a.cn(Ze,"mb-1 block"),children:"Page size"}),e.jsxs(a.Select,{value:t.pageSize||"letter",onValueChange:n=>s({pageSize:n}),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsxs(a.SelectContent,{children:[e.jsx(a.SelectItem,{value:"letter",children:"Letter"}),e.jsx(a.SelectItem,{value:"legal",children:"Legal"}),e.jsx(a.SelectItem,{value:"a4",children:"A4"}),e.jsx(a.SelectItem,{value:"a3",children:"A3"}),e.jsx(a.SelectItem,{value:"tabloid",children:"Tabloid"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Ze,"mb-1 block"),children:"Orientation"}),e.jsxs(a.Select,{value:t.orientation||"portrait",onValueChange:n=>s({orientation:n}),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsxs(a.SelectContent,{children:[e.jsx(a.SelectItem,{value:"portrait",children:"Portrait"}),e.jsx(a.SelectItem,{value:"landscape",children:"Landscape"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(lt,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(lt,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function co({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Ze,"mb-1 block"),children:"Delimiter"}),e.jsxs(a.Select,{value:t.delimiter||",",onValueChange:n=>s({delimiter:n}),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsxs(a.SelectContent,{children:[e.jsx(a.SelectItem,{value:",",children:"Comma"}),e.jsx(a.SelectItem,{value:";",children:"Semicolon"}),e.jsx(a.SelectItem,{value:" ",children:"Tab"})]})]})]}),e.jsxs("div",{className:"space-y-1.5 border-t border-border/60 pt-2.5",children:[e.jsx(lt,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(lt,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function lt({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 uo({attachments:t,onChange:s,onAdd:n,disabled:r}){const o=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":o?"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"}),o?"Attach":null]}),t.map((l,c)=>e.jsx(mo,{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}:${os(l)}`)),o?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 mo({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[o,l]=h.useState(!1),c=os(t),u=za(t),d=t.format.toUpperCase();return e.jsxs("span",{className:a.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",o&&"border-ring "),title:u?`${c} · ${u}`:c,children:[e.jsx(io,{attachment:t,open:o,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(ho,{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(a.X,{className:"h-2.5 w-2.5"})})]})}function ho({format:t,className:s}){const n=t==="csv"?i.FileSpreadsheet:i.FileText;return e.jsx(n,{className:a.cn(s)})}const xo="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function po({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:o,runtime:l,selectedAttachments:c,onSubmit:u}){const d=h.useMemo(()=>zn({source:n,dashboard:r,selectedSheetId:o}),[n,r,o]),[m,x]=h.useState([]);h.useEffect(()=>{if(!t)return;const T=[];for(const V of c){const D=Gs(V),F=d.find(U=>U.formats.some(q=>{const B=Kt({option:U,format:q,runtime:l});return Gs(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]),p=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))},N=()=>{const T=[];for(const V of m){const D=d.find(F=>F.key===V.optionKey);D&&T.push(Kt({option:D,format:V.format,runtime:l}))}u(T),s(!1)},w=()=>s(!1),j=h.useMemo(()=>d.filter(T=>T.kind==="dashboard"||T.kind==="dashboard_sheet"),[d]),C=h.useMemo(()=>d.filter(T=>T.kind==="document_sheet"),[d]),y=h.useMemo(()=>d.filter(T=>T.kind==="card"),[d]),S=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(Ot,{label:"Dashboard",options:j,selectedOptionKeys:g,formatByOptionKey:p,onToggle:b,onFormatChange:A}),e.jsx(Ot,{label:"Paginated reports",options:C,selectedOptionKeys:g,formatByOptionKey:p,onToggle:b,onFormatChange:A,emptyText:"No paginated report sheets are available."}),e.jsx(Ot,{label:"Current sheet cards",options:y,selectedOptionKeys:g,formatByOptionKey:p,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:S===0?"Nothing selected":`${S} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Button,{type:"button",variant:"outline",size:"xs",onClick:w,children:"Cancel"}),e.jsx(a.Button,{type:"button",size:"xs",onClick:N,disabled:n.type!=="dashboard",children:S>0?`Add ${S} ${S===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function Ot({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:o,onFormatChange:l,emptyText:c}){return e.jsxs("section",{children:[e.jsx("div",{className:a.cn(xo,"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:a.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:()=>o(u.key,u.defaultFormat),className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[e.jsx(fo,{selected:d}),e.jsx(go,{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(a.Select,{value:m,onValueChange:x=>l(u.key,x),children:[e.jsx(a.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:x=>x.stopPropagation(),children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:u.formats.map(x=>e.jsx(a.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 fo({selected:t}){return e.jsx("span",{"aria-hidden":!0,className:a.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(a.Check,{className:"h-2.5 w-2.5 text-primary-foreground",strokeWidth:3}):null})}function go({kind:t,format:s,cardType:n,className:r}){const o=s==="csv"?i.FileSpreadsheet:t==="dashboard"?i.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?ue.Rows3:a.ChartColumn:i.FileText;return e.jsx(o,{className:r})}const bo=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,jo=250;function Qe(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 yo(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function vo(t){return t.type==="group"?t.groupId:null}function Je(t){return(t==null?void 0:t.trim().toLowerCase())||null}function Qs(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function Js(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function Ys({value:t,onChange:s,className:n,disabled:r=!1,prefix:o,placeholder:l}){const c=h.useRef(null),[u,d]=h.useState(!1),[m,x]=h.useState(""),[g,p]=h.useState(0),[b,A]=h.useState(()=>new Map),[N,w]=h.useState(()=>new Map),[j,C]=h.useState("people"),y=i.useDebounce(m,jo),{currentUser:S}=i.useCurrentUserInfo(),T=(S==null?void 0:S.type)==="tenant",{users:V,isLoading:D}=i.useUnifiedUsers({search:y,active:!0,type:T?"tenant":"all",tenantId:T?S.tenantId:void 0,limit:25}),{groups:F,isLoading:U}=i.useGroups({search:y,type:T?"TENANT_GROUP":"all",tenantId:T?S.tenantId:void 0,limit:25}),q=h.useMemo(()=>new Set(t.map(Qe)),[t]),B=h.useMemo(()=>new Set(t.map(yo).filter(I=>!!I)),[t]),_=h.useMemo(()=>new Set(t.map(vo).filter(I=>!!I)),[t]),$=h.useMemo(()=>{const I=new Map(b);return V.forEach(M=>{I.set(M.id,Qs(M))}),S!=null&&S.id&&I.set(S.id,{kind:"user",id:S.id,name:S.name||S.email||"User",email:S.email||"",type:S.type}),I},[b,V,S]),P=h.useMemo(()=>{const I=new Set;return t.forEach(M=>{var z;if(M.type==="email"){const Z=Je(M.address);Z&&I.add(Z);return}if(M.type==="group")return;const xe=M.type==="tenant_user"?M.tenantUserId:M.userId,E=Je((z=$.get(xe))==null?void 0:z.email);E&&I.add(E)}),I},[$,t]),G=h.useMemo(()=>{const I=new Map(N);return F.forEach(M=>{I.set(M.id,Js(M))}),I},[N,F]),Y=h.useMemo(()=>V.filter(I=>{if(B.has(I.id))return!1;const M=Je(I.email);return M&&P.has(M)?!1:T?I.type==="tenant"&&I.tenantId===(S==null?void 0:S.tenantId):!0}).map(Qs),[V,B,P,T,S==null?void 0:S.tenantId]),L=h.useMemo(()=>Y.filter(I=>I.type==="organization"),[Y]),K=h.useMemo(()=>Y.filter(I=>I.type==="tenant"),[Y]),k=h.useMemo(()=>F.filter(I=>_.has(I.id)?!1:(S==null?void 0:S.type)==="tenant"?I.type==="TENANT_GROUP"&&I.tenantId===S.tenantId:!0).map(Js),[F,_,S==null?void 0:S.type,S==null?void 0:S.tenantId]),ae=h.useMemo(()=>T?[{key:"people",label:"People",count:K.length},{key:"groups",label:"Groups",count:k.length}]:[{key:"people",label:"People",count:L.length},{key:"tenant_users",label:"Tenant users",count:K.length},{key:"groups",label:"Groups",count:k.length}],[k.length,T,L.length,K.length]),Q=h.useMemo(()=>j==="groups"?[]:j==="tenant_users"||T?K:L,[j,T,L,K]),X=h.useMemo(()=>j==="groups"?k:[],[j,k]),me=h.useMemo(()=>[...Q,...X],[Q,X]),je=me.length===0?0:Math.min(g,me.length-1),oe=m.trim(),H=bo.test(oe),Re=Je(oe),ye=Re?P.has(Re):!1,Se=D||U,Ne=I=>{q.has(Qe(I))||(s([...t,I]),x(""),p(0))},W=I=>{s(t.filter(M=>Qe(M)!==I))},we=()=>{!H||ye||Ne({type:"email",address:oe})},O=I=>{const M=Je(I.email);M&&P.has(M)||(A(xe=>{const E=new Map(xe);return E.set(I.id,I),E}),Ne(I.type==="tenant"?{type:"tenant_user",tenantUserId:I.id}:{type:"user",userId:I.id}))},se=I=>{w(M=>{const xe=new Map(M);return xe.set(I.id,I),xe}),Ne({type:"group",groupId:I.id})},ze=I=>{if(I.key==="Enter"){if(I.preventDefault(),H&&!ye){we();return}const M=me[je];if((M==null?void 0:M.kind)==="user"){O(M);return}if((M==null?void 0:M.kind)==="group"){se(M);return}}else if(I.key==="ArrowDown")I.preventDefault(),p(M=>Math.min(M+1,Math.max(me.length-1,0)));else if(I.key==="ArrowUp")I.preventDefault(),p(M=>Math.max(M-1,0));else if(I.key==="Escape")d(!1);else if(I.key==="Backspace"&&m.length===0){const M=t[t.length-1];M&&W(Qe(M))}},Ve=t.map(I=>{const M=Qe(I);if(I.type==="email")return{key:M,label:I.name||I.address,icon:e.jsx(i.AtSign,{className:"h-3 w-3"}),onRemove:()=>W(M)};if(I.type==="group"){const z=G.get(I.groupId);return{key:M,label:(z==null?void 0:z.name)||"Group",icon:e.jsx(Yt,{className:"h-3 w-3"}),onRemove:()=>W(M)}}const xe=I.type==="tenant_user"?I.tenantUserId:I.userId,E=$.get(xe);return{key:M,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:()=>W(M)}});return e.jsx("div",{className:a.cn("relative",n),children:e.jsxs(a.Popover,{open:u&&!r,onOpenChange:d,children:[e.jsx(a.Anchor2,{asChild:!0,children:e.jsxs("div",{className:a.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:[o?e.jsx("span",{className:"inline-flex shrink-0 items-center text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o}):null,Ve.map(I=>e.jsx(No,{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),p(0),d(!0)},onFocus:()=>d(!0),onKeyDown:ze})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:I=>I.preventDefault(),className:a.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(wo,{activeIndex:je,activeFilter:j,emailAlreadyAdded:ye,filters:ae,groupSuggestions:X,loading:Se,onAddEmail:we,onFilterChange:I=>{C(I),p(0)},onGroupClick:se,onUserClick:O,orderedSuggestions:me,query:oe,queryIsEmail:H,userSuggestions:Q,viewerType:S==null?void 0:S.type})})]})})}function No({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(a.X,{className:"h-2.5 w-2.5"})})]})}function wo({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:o,loading:l,onAddEmail:c,onFilterChange:u,onGroupClick:d,onUserClick:m,orderedSuggestions:x,query:g,queryIsEmail:p,userSuggestions:b,viewerType:A}){const N=!l&&x.length===0&&!(p&&!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(w=>e.jsxs("button",{type:"button",onClick:()=>u(w.key),className:a.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===w.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:w.label}),e.jsx("span",{className:a.cn("tabular-nums",s===w.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:w.count})]},w.key))}),l?e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-[12px] text-muted-foreground",children:[e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Searching"]}):null,b.length>0?e.jsx(Zs,{heading:"People",children:b.map(w=>{var C;const j=x.indexOf(w);return e.jsx(en,{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:(C=(w.name||w.email||"?")[0])==null?void 0:C.toUpperCase()}),detail:w.name?w.email:void 0,tag:w.type==="organization"?"Org user":"Tenant user",viewerType:A,title:w.name||w.email,onClick:()=>m(w)},w.id)})}):null,o.length>0?e.jsx(Zs,{heading:"Groups",children:o.map(w=>{const j=x.indexOf(w);return e.jsx(en,{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(Yt,{className:"h-3 w-3"})}),detail:w.memberCount!==void 0?`${w.memberCount} member${w.memberCount===1?"":"s"}`:w.description??void 0,tag:w.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:A,title:w.name,onClick:()=>d(w)},w.id)})}):null,p&&!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(vn,{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,N?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 Zs({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 en({active:t,avatar:s,detail:n,onClick:r,tag:o,title:l,viewerType:c}){return e.jsxs("button",{type:"button",onClick:r,className:a.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:o}):null]})}function ct(t){return t==="SUCCESS"||t==="FAILED"}function dt(t){return t==="QUEUED"||t==="RUNNING"}function Xt({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:o,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}){const[m,x]=h.useState(null),[g,p]=h.useState("idle"),b=h.useRef(null),A=h.useRef({fetchRun:o,onRun:l,onTerminalRun:c,onError:u,onTimeout:d});h.useEffect(()=>{A.current={fetchRun:o,onRun:l,onTerminalRun:c,onError:u,onTimeout:d}},[o,u,l,c,d]);const N=h.useCallback(()=>{x(null),p("idle")},[]),w=h.useCallback(()=>{b.current=null},[]),j=h.useCallback(y=>{var S,T;if(A.current.onRun(y),ct(y.status)){b.current=y.id,x(null),p("terminal"),(T=(S=A.current).onTerminalRun)==null||T.call(S,y);return}if(dt(y.status)){b.current=null,x(y.id),p("polling");return}x(null),p("idle")},[]),C=h.useCallback(y=>{b.current!==y&&(x(y),p("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(b.current===m){x(null),p("terminal");return}let y=!1,S=!1,T=null;const V=Date.now(),D=async()=>{var F,U,q,B,_,$;if(!(y||S)){if(Date.now()-V>r){x(P=>P===m?null:P),p("timed_out"),(U=(F=A.current).onTimeout)==null||U.call(F,m);return}S=!0;try{const P=await A.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(y)return;if(A.current.onRun(P),ct(P.status)){b.current=P.id,x(G=>G===P.id?null:G),p("terminal"),(B=(q=A.current).onTerminalRun)==null||B.call(q,P);return}if(!dt(P.status)){x(G=>G===P.id?null:G),p("idle");return}T=window.setTimeout(D,n)}catch(P){y||(p("error"),($=(_=A.current).onError)==null||$.call(_,P))}finally{S=!1}}};return p("polling"),D(),()=>{y=!0,T&&window.clearTimeout(T)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&g==="polling",resetTerminalRun:w,startRun:j,startRunId:C,status:g,stop:N}}function tn({label:t,description:s,checked:n,onSelect:r,name:o}){return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5",children:[e.jsx("input",{type:"radio",name:o,checked:n,onChange:r,className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:a.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 Co({includeEvidence:t,includeSql:s,includeHtml:n,onChange:r}){const o=[t,s,n].filter(Boolean).length;return e.jsxs(a.Popover,{children:[e.jsx(a.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:["· ",o,"/3"]}),e.jsx(a.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(a.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(Ut,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:l=>r("evidence",l)}),e.jsx(Ut,{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(Ut,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:l=>r("html",l)})]})]})]})}function Ut({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:o=>r(o.target.checked),className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:a.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(a.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 Qt=`Tell me what changed in the business and what is driving it.
62
+
63
+ Watch:
64
+ - Top-line movement versus the previous period
65
+ - Largest positive and negative drivers
66
+ - Any segment, product, region, or account that explains the change
67
+
68
+ Don't bother me unless:
69
+ - The movement is meaningful enough for the team to act on
70
+ - A single driver explains a large share of the movement
71
+
72
+ Include in the briefing:
73
+ - Executive summary in plain English
74
+ - KPI comparison with current, previous, delta, and percent change
75
+ - Driver table or chart when useful
76
+ - 2-3 recommended next actions
77
+ - Evidence link rather than raw SQL in the main body`,sn=`Watch this dashboard for unusual movement.
78
+
79
+ Focus on:
80
+ - Spikes or drops versus recent history
81
+ - Outliers by segment, product, region, or customer
82
+ - Changes that are likely to need follow-up
83
+
84
+ Include in the briefing:
85
+ - What changed
86
+ - Why it looks unusual
87
+ - The most likely drivers
88
+ - What the team should check next`,nn=`Hi team,
89
+
90
+ Sharing this dashboard. The PDF below has the selected dashboard view and current filters applied.
91
+
92
+ Reply if you have questions.`,rn=`Track customer health across the top accounts. Surface accounts that crossed a risk threshold, with the leading signal that flagged them.
93
+
94
+ Watch:
95
+ - Health score drops > 10 points in the last 14 days
96
+ - Accounts within 5 points of the at-risk threshold
97
+ - Resolution-time regressions on enterprise tickets
98
+
99
+ Audience:
100
+ Customer Success leads. Action-oriented — every at-risk row needs an owner.`,an=`Short Slack-friendly digest. One headline, three bullets, no PDFs. Use emoji sparingly. Skip the analysis appendix — link to the dashboard.
101
+
102
+ Watch:
103
+ - Top-line movement WoW
104
+ - The single biggest driver
105
+ - Anything urgent the team should act on today
106
+
107
+ Format:
108
+ - Headline (≤ 12 words)
109
+ - Three bullets max
110
+ - Link to the full dashboard`;function So(t,s,n){const r=t.includes("markdown")?t.filter(o=>o!==s):["markdown"];return n?Array.from(new Set([...r,s])):r}const at=[{label:"Email report",description:"Email body with dashboard attachments",seedsDashboardAttachment:!0,available:t=>t.type==="dashboard",draft:(t,s)=>({name:"Dashboard Email Report",instruction:nn,body:{type:"custom_message",message:nn},attachments:t.type==="dashboard"?(s==null?void 0:s.attachments)??[]:void 0,output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["EMAIL"]}})},{label:"Business review",description:"Weekly executive movement and drivers",draft:()=>({name:"Weekly Business Briefing",instruction:Qt,body:{type:"generated_analysis",instruction:Qt},output:{includeEvidence:!0,includeSql:!1}})},{label:"Anomaly watch",description:"Only surface unusual movement",draft:()=>({name:"Anomaly Watch Briefing",instruction:sn,body:{type:"generated_analysis",instruction:sn},output:{includeEvidence:!0,includeSql:!1}})},{label:"Customer health",description:"Daily watch on at-risk accounts",draft:()=>({name:"Customer Health Watch",instruction:rn,body:{type:"generated_analysis",instruction:rn},output:{includeEvidence:!0,includeSql:!1}})},{label:"Slack digest",description:"Short Slack-friendly digest, no PDFs",draft:()=>({name:"Slack Digest",instruction:an,body:{type:"generated_analysis",instruction:an},output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["SLACK"]}})}],ne="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Ye="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",Fe="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",$t="z-[70]";function ko({scheduleExpr:t,timezone:s,onScheduleChange:n}){const r=h.useMemo(()=>i.parseScheduleExpr(t),[t]),[o,l]=h.useState(()=>ut()),[c,u]=h.useState(null),d=i.buildSchedulePreview(r,s,ln(o),c?cn(c):null),[m,x]=h.useState(!1),g=j=>{n({scheduleExpr:i.buildScheduleExpr(j),timezone:s})},p=j=>{const C=j==="weekly"&&r.weekdays.length===0?[1,2,3,4,5]:r.weekdays;g({...r,repeats:j,weekdays:C})},b=(j,C)=>{g({...r,hour:j,minute:C})},A=j=>{g({...r,weekdays:j})},N=`${String(r.hour).padStart(2,"0")}:${String(r.minute).padStart(2,"0")}`,w=h.useMemo(()=>Do(),[]);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:ne,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:a.cn(ne,"mb-1 block"),children:"Repeats"}),e.jsxs(a.Select,{value:r.repeats,onValueChange:j=>p(j),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsxs(a.SelectContent,{className:$t,children:[e.jsx(a.SelectItem,{value:"daily",children:"Daily"}),e.jsx(a.SelectItem,{value:"weekly",children:"Weekly"}),e.jsx(a.SelectItem,{value:"biweekly",children:"Every two weeks"}),e.jsx(a.SelectItem,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(ne,"mb-1 block"),children:"Time"}),e.jsxs(a.Select,{value:N,onValueChange:j=>{const[C,y]=j.split(":").map(S=>parseInt(S,10));b(C,y)},children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{className:a.cn($t,"max-h-[280px]"),children:w.map(({value:j,label:C})=>e.jsx(a.SelectItem,{value:j,children:C},j))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(a.Popover,{open:m,onOpenChange:x,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-expanded":m,className:a.cn(Ye,"h-6 px-1.5 text-[11px]"),children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"More options",e.jsx(a.ChevronDown,{className:a.cn("h-3 w-3 text-muted-foreground/70 transition-transform",m&&"rotate-180")})]})}),e.jsxs(a.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:ne,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(a.X,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(ne,"mb-1 block"),children:"First occurrence"}),e.jsx(dn,{icon:e.jsx(i.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:o,placeholder:"Pick a start date",disabledBefore:ut(),onChange:j=>{j&&l(j)},renderLabel:j=>j?ln(j):"Today"})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(ne,"mb-1 block"),children:"Timezone"}),e.jsxs(a.Select,{value:s,onValueChange:j=>n({scheduleExpr:i.buildScheduleExpr(r),timezone:j}),children:[e.jsx(a.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(a.SelectValue,{})})]})}),e.jsx(a.SelectContent,{className:a.cn($t,"max-h-[280px]"),children:i.COMMON_TIMEZONES.map(j=>e.jsx(a.SelectItem,{value:j,children:Eo(j)},j))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(ne,"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:o,onChange:u,renderLabel:j=>j?cn(j):"No end date"})]}),r.repeats==="weekly"?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(ne,"mb-1 block"),children:"On these days"}),e.jsx("div",{className:"flex gap-1",children:["S","M","T","W","T","F","S"].map((j,C)=>{const y=r.weekdays.includes(C);return e.jsx("button",{type:"button",onClick:()=>{A(y?r.weekdays.filter(S=>S!==C):[...r.weekdays,C].sort())},className:a.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},C)})})]}):null]})]})})]})}function Do(){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 Eo(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 ut(){const t=new Date;return t.setHours(0,0,0,0),t}function Ao(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function ln(t){return Ao(t,ut())?"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:o,disabledBefore:l,onChange:c,renderLabel:u}){const[d,m]=h.useState(!1),x=u(t),g=!t;return e.jsxs(a.Popover,{open:d,onOpenChange:m,children:[e.jsx(a.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:a.cn("truncate",g&&"text-muted-foreground/70"),children:g?n??x:x})]}),e.jsx(a.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"})]})}),e.jsxs(a.PopoverContent,{align:"start",className:"z-[60] w-auto p-0",onOpenAutoFocus:p=>p.preventDefault(),children:[e.jsx(i.Calendar$1,{mode:"single",selected:t??void 0,defaultMonth:t??l??ut(),onSelect:p=>{c(p??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:o??"Clear"})}):null]})]})}function Io({source:t,resolvedSourceContext:s,sourceDetail:n,onChange:r}){const[o,l]=h.useState(!1),c=h.useRef(null),u=s.source.type==="dashboard"?s.source:null,d=u!==null;h.useEffect(()=>{if(!o)return;const w=j=>{const C=j.target;c.current&&!c.current.contains(C)&&!(C instanceof Element&&C.closest("[data-scope-popover]"))&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[o]);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,p="This project",b="Use any data in this project.",A=m?p:x,N=m?b:g;return d?e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:c,type:"button",onClick:()=>l(w=>!w),"aria-expanded":o,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}),N?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:N})]}):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(a.ChevronDown,{className:a.cn("h-3 w-3 transition-transform",o&&"rotate-180")})]})]}),o?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:p,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})]}),N?e.jsx("div",{className:"mt-0.5 pl-5 text-[11px] text-muted-foreground",children:N}):null]})}function un({active:t,label:s,detail:n,description:r,onSelect:o,isLast:l}){return e.jsxs("button",{type:"button",onClick:o,className:a.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:a.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 To({channels:t,selectedChannelId:s,onChange:n,destinationKind:r,onDestinationKindChange:o,loading:l,disabled:c,className:u}){const d=h.useRef(null),[m,x]=h.useState(!1),[g,p]=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(C=>C.name.toLowerCase().includes(j)):t},[t,g]),N=r==="dm",w=c||N;return e.jsx("div",{className:a.cn("relative",u),children:e.jsxs(a.Popover,{open:m&&!w,onOpenChange:x,children:[e.jsx(a.Anchor2,{asChild:!0,children:e.jsxs("div",{className:a.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",w&&"cursor-not-allowed opacity-60"),onClick:()=>{var j;w||((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:()=>o==null?void 0:o("channel"),className:a.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(Lo,{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:w,placeholder:N?"DM delivery coming in V2":b?"Change channel…":l?"Loading channels…":"Search channels…",onChange:j=>{p(j.target.value),x(!0)},onFocus:()=>x(!0)})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:j=>j.preventDefault(),className:a.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 C=j.id===s;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{n(j.id),p(""),x(!1)},className:a.cn("flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left",C?"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 Lo({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(a.X,{className:"h-2.5 w-2.5"})})]})}const nr=ct,_e=dt;function Fo(t){var r,o;const s=(r=t==null?void 0:t.email)==null?void 0:r.trim();if(!s)return null;const n=(o=t==null?void 0:t.name)==null?void 0:o.trim();return{type:"email",address:s,...n&&n!==s?{name:n}:{}}}function rr(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 o=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(o)},[s]),s===null?null:Math.max(0,Math.floor((n-s)/1e3))}function ls(t){const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ro(t){if(!ce(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=>!ce(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=>!ce(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,o=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||!o||!l?null:{subject:s,body:n,...typeof t.bodyHtml=="string"&&t.bodyHtml.trim()?{bodyHtml:t.bodyHtml}:{},recipients:r,channels:o,attachments:l,...typeof t.attachmentNotice=="string"?{attachmentNotice:t.attachmentNotice}:{}}}function Mo(t){if(!ce(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(ce):null;if(!s||!n||!r)return null;const o=ce(t.thread)?{text:typeof t.thread.text=="string"?t.thread.text:"",blocks:Array.isArray(t.thread.blocks)?t.thread.blocks.filter(ce):[],reply_broadcast:!1}:void 0;return{channel:s,text:n,blocks:r,unfurl_links:!1,unfurl_media:!1,...o?{thread:o}:{}}}function Po(t){if(!ce(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 ar(t){if(!ce(t.result))return null;const s=ce(t.result.deliveryReadiness)?t.result.deliveryReadiness:null,n=s&&ce(s.intent)?s.intent:null,r=ce(t.result.deliveryPackage)?t.result.deliveryPackage:null,o=ce(t.result.deliveryResult)?t.result.deliveryResult:null,l=ce(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(p=>{const b=Po(p);return b?[b]:[]}):[],x=Array.isArray(n==null?void 0:n.channels)?n.channels.filter(p=>typeof p=="string"):typeof(o==null?void 0:o.channel)=="string"?[o.channel]:[],g=Array.isArray(l==null?void 0:l.attachments)?l.attachments.flatMap(p=>ce(p)?typeof p.label=="string"?[p.label]:typeof p.title=="string"?[p.title]:typeof p.filename=="string"?[p.filename]:[]:[]):[];return{subject:c,body:u,...d?{bodyHtml:d}:{},recipients:m,channels:x,attachments:g}}function or({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:a.cn("h-[760px] w-full rounded-card border border-border bg-background ",n)})}const te={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 Bo(t){return t.status==="SUCCESS"?"Complete":t.status==="FAILED"?"Failed":t.status==="RUNNING"?"Running":"Queued"}function cs(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,o=mn(r.email,"EMAIL"),l=mn(r.slack,"SLACK"),c=[o,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,p)=>g+p.sentCount,0),failedCount:c.reduce((g,p)=>g+p.failedCount,0),attemptedCount:c.reduce((g,p)=>g+p.attemptedCount,0),attachmentCount:c.reduce((g,p)=>g+p.attachmentCount,0),message:x,channels:{email:o??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 Vo(t){var s,n,r,o;if(t.channel==="BRIEFING"||t.channels){const l=(n=(s=t.channels)==null?void 0:s.email)==null?void 0:n.status,c=(o=(r=t.channels)==null?void 0:r.slack)==null?void 0:o.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 Oo(t){return t.status==="SENT"?te.success.surface:t.status==="FAILED"||t.status==="PARTIAL"?te.danger.surface:te.warning.surface}function ir(t){return t.status==="SUCCESS"?e.jsx(a.Check,{className:a.cn("h-3 w-3",te.success.icon)}):t.status==="FAILED"?e.jsx(a.X,{className:a.cn("h-3 w-3",te.danger.icon)}):t.status==="RUNNING"?e.jsx(a.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 Uo=[{pattern:/^plan preview/i,label:"Plan preview"},{pattern:/^analysis preview/i,label:"Analysis preview"}];function $o(t){const s=t.runtime.split(/;\s*/).map(o=>o.trim()).filter(Boolean),n=t.toolCalls.split(/;\s*/).map(o=>o.trim()).filter(Boolean),r=[];for(const{pattern:o,label:l}of Uo){const c=hn(s.find(d=>o.test(d))),u=hn(n.find(d=>o.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 _o({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:ne,children:"What I understood from your brief"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ke,{field:"Datasets",value:e.jsx(oi,{plan:t})}),e.jsx(ke,{field:"Investigate",value:t.understood.investigation}),e.jsx(ke,{field:"Threshold",value:t.understood.threshold}),e.jsx(ke,{field:"Audience",value:t.understood.audience}),e.jsx(ke,{field:"Format",value:t.understood.format,isLast:!0})]})]}),t.scope.grounding?e.jsx(zo,{plan:t}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"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:ne,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:ne,children:"Estimate"}),(()=>{var c;const o=$o(t.estimate).find(u=>u.label.toLowerCase().includes("analysis")),l=(o==null?void 0:o.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(a.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&&!_e(s.status)?e.jsx(lr,{run:s,labelPrefix:"Preview"}):null]})}function zo({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:ne,children:"What I'll analyze"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ke,{field:"Metric",value:s.metric??"Not selected yet"}),e.jsx(ke,{field:"Dataset",value:n}),e.jsx(ke,{field:"Time field",value:s.dateField??"Not selected yet"}),e.jsx(ke,{field:"Breakdown",value:r}),e.jsx(ke,{field:"Confidence",value:`${s.confidence} · ${s.reason}`,isLast:!0})]})]})}function lr({run:t,labelPrefix:s}){const n=t.progress??null,r=n?(n.recentEvents??[]).filter(d=>d.label!==n.label||d.updatedAt!==n.updatedAt).slice(-4).reverse():[],o=_e(t.status),l=n?mt(n.label):`${s?`${s} `:""}${Bo(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:[o?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):ir(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(a.Check,{className:"mt-0.5 h-3 w-3 shrink-0 text-border"}),e.jsx("span",{children:ur(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 cr({run:t,onRetryRun:s,retryDisabled:n,retryDisabledReason:r,onDeleteRun:o,deletePending:l}){const[c,u]=h.useState(!1),[d,m]=h.useState(!1),x=dr(t.completedAt??t.startedAt??t.scheduledFor),p=(t.error?/cancel/i.test(t.error):!1)?"Run cancelled":"Run failed";return e.jsxs("div",{className:a.cn("rounded-card border px-3 py-2.5",te.danger.surface),role:"alert","aria-label":p,children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:a.cn("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full",te.danger.iconBg),children:e.jsx(a.X,{className:a.cn("h-3 w-3",te.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:a.cn("font-medium",te.danger.icon),children:p}),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,o?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]})]}),o?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(),o()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[l?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.Trash2,{className:"h-3 w-3"}),"Delete run"]})]})]})}):null]})}function qo({run:t}){const s=cs(t);return!nr(t.status)||!s||s.status==="SKIPPED"?null:e.jsxs("div",{className:a.cn("rounded-card border px-3 py-2 text-[12px]",Oo(s)),"aria-label":"Email delivery status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ue.SendHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Vo(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 dr(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 Ho(t){const s=cs(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 Ko({run:t,onViewOutput:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,deletePending:c}){const u=cs(t),d=dr(t.completedAt??t.startedAt??t.scheduledFor);if(t.status==="FAILED"||(u==null?void 0:u.status)==="FAILED")return e.jsx(cr,{run:t,onRetryRun:r,retryDisabled:o,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:a.cn("rounded-card border px-3 py-2",te.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:a.cn("flex items-center gap-1.5 text-[12px] font-medium",te.success.label),children:[ir(t),e.jsx("span",{children:Ho(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:Fe,onClick:s,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})})]})})}function mt(t){return t.replace(/\s+(started|completed)$/i,"")}function ur(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}`}const pn=4;function fn({run:t}){const s=t.progress??null,n=s?Wo(s.recentEvents??[],s.label).slice(-pn).reverse():[],r=s!=null&&s.detail&&s.detail!==s.label?s.detail:null,o=mr(t),l=[...n];for(;l.length<pn;)l.push(null);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,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:l.map((c,u)=>e.jsx("li",{className:"flex items-start gap-2 text-[11px] leading-[1.45] text-muted-foreground",children:c?e.jsxs(e.Fragment,{children:[e.jsx(a.Check,{className:"mt-0.5 h-3 w-3 shrink-0 text-border"}),e.jsx("span",{children:ur(c.label)})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mt-1.5 inline-block h-px w-3 shrink-0 bg-border"}),e.jsx("span",{className:"text-border",children:"·"})]})},c?`${c.updatedAt}-${c.label}-${u}`:`slot-${u}`))})]}),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,o.length>0?e.jsx("p",{className:"mt-2 text-[11px] leading-[1.55] text-muted-foreground",children:o.join(" ")}):null]})}function Wo(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(),o=new Set;for(const u of r){const d=/^(.*)\s+completed$/i.exec(u.label.trim());d&&o.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!o.has(m)}),c=new Map;for(const u of l)c.set(u.label.trim().toLowerCase(),u);return Array.from(c.values())}function Go(){return e.jsx("div",{className:a.cn("border-b px-4 py-2 text-[12px] leading-[1.5]",te.info.surface),role:"note",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(a.Info,{className:a.cn("mt-0.5 h-3 w-3 shrink-0",te.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 o;const n=rr(t.startedAt),r=(o=t.progress)!=null&&o.label?mt(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(a.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:ls(n)}):"Starting…"})]}),e.jsx(i.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:o}){const l=n==="success";return e.jsx("div",{className:a.cn("border-b px-4 py-2.5",l?te.success.surface:te.danger.surface),role:"status",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:a.cn("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full",l?te.success.iconBg:te.danger.iconBg),children:l?e.jsx(a.Check,{className:a.cn("h-3 w-3",te.success.icon)}):e.jsx(a.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 ",ls(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:o,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(a.X,{className:"h-3 w-3"})})]})})}function Jo({run:t}){const s=rr(t==null?void 0:t.startedAt);return s===null?null:e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",ls(s)]})}function Yo({pendingAction:t,previewRun:s,savedActiveRun:n,onShowDetails:r,onCancelSavedRun:o,onMinimizeRun:l,detailsVisible:c}){var N,w,j,C;const u=s&&_e(s.status)?s:null,d=n;let m=null,x=null,g=!1;if(t==="plan"?(m="Reviewing your brief",x="Reading the brief and planning the analysis…"):t==="preview"?(m="Starting preview run",x="Starting the preview…"):t==="run"?(m="Starting briefing run",x="Preparing the run…"):u?(m=(N=u.progress)!=null&&N.label?mt(u.progress.label):"Running preview",x=((w=u.progress)==null?void 0:w.detail)??null,g=!!u.progress):d&&(m=(j=d.progress)!=null&&j.label?mt(d.progress.label):"Running",x=((C=d.progress)==null?void 0:C.detail)??null,g=!!d.progress),!m)return null;const p=!c&&x,b=d??u,A=!!(d&&l)&&t!=="cancelRun";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(a.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:m}),e.jsx(Jo,{run:b}),p?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:x})]}):null,e.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[g?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":c,"aria-label":c?"Hide details":"Show details",title:c?"Hide details":"Show details",children:e.jsx(a.ChevronDown,{className:a.cn("h-3 w-3 transition-transform",c&&"rotate-180")})}):null,A&&l?e.jsxs("button",{type:"button",onClick:l,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(i.Minimize2,{className:"h-3 w-3"}),"Run in background"]}):null,d&&o?e.jsx("button",{type:"button",onClick:o,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(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(a.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:a.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(a.ChevronDown,{className:"ml-1.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(i.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:ne,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:a.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 ds({preview:t,onExpand:s}){var l;const[n,r]=h.useState("rendered"),o=!!((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]})]}),o||s?e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o?e.jsx(a.Tabs,{value:n,onValueChange:c=>r(c==="html"?"html":"rendered"),children:e.jsxs(a.TabsList,{size:"xs",children:[e.jsx(a.TabsTrigger,{value:"rendered",children:"Rendered"}),e.jsx(a.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(i.Maximize2,{className:"h-3.5 w-3.5"})}):null]}):null]}),n==="html"&&o?e.jsx(or,{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(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:t.attachmentNotice})]}):null]}):null]})}function He(t){if(!ce(t))return null;const s=t.text;return typeof s=="string"?s:null}function ti(t){return t.type==="header"||t.type==="section"?He(t.text):t.type==="context"&&Array.isArray(t.elements)&&t.elements.map(n=>ce(n)?He(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(!ce(n))return[];const r=He(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 _t({size:t=6}){const s=t===5?"h-5 w-5":"h-6 w-6";return e.jsx("div",{className:a.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 o=ni(t.blocks),l=o.header?He(o.header.text):null,c=o.context?ti(o.context):null,u=o.sections.map(g=>He(g.text)).filter(g=>!!g),d=o.actions?si([o.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(qt,{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(i.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(_t,{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,p)=>e.jsx("p",{className:"whitespace-pre-line",children:g},`section-${p}`))}):null,d.length>0?e.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:d.map((g,p)=>e.jsx("button",{type:"button",tabIndex:-1,className:a.cn("inline-flex h-7 items-center gap-1.5 rounded-control px-2.5 text-[11.5px] font-medium",p===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(_t,{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(_t,{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:a.cn(ne,"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 ke({field:t,value:s,isLast:n}){return e.jsxs("div",{className:a.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(a.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[o,l]=h.useState(!1);return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:a.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:a.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:a.cn("whitespace-pre-wrap break-words",!o&&`line-clamp-${xn}`),style:o?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:o?"Show less":"Show all fields"}):null]}):null]})]})}function gn({previewRun:t,onExpand:s,fullWidth:n}){var m,x,g,p,b;const r=t.result,o=(m=r==null?void 0:r.artifactPreview)==null?void 0:m.markdown,l=(x=r==null?void 0:r.artifactPreview)==null?void 0:x.html,c=Zo(t),u=c?Ro((g=r==null?void 0:r.limits)==null?void 0:g.emailPreview):null,d=((p=r==null?void 0:r.limits)==null?void 0:p.previewKind)==="slack_message"?Mo(r.limits.slackPreview):null;return e.jsxs("div",{className:a.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:a.cn("inline-flex items-center gap-1",te.success.label),children:[e.jsx("span",{className:a.cn("h-1.5 w-1.5 rounded-full",te.success.dot)}),"Complete"]}),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:a.cn(Ye,"h-6 px-1.5 text-[11px]"),"aria-label":"Expand preview to a larger view",children:[e.jsx(i.Maximize2,{className:"h-3 w-3"}),"Expand"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:ne,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)??"Briefing preview"}),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(ds,{preview:u,onExpand:s}):d?e.jsx(ai,{preview:d,onExpand:s,trustLine:"Runs with your permissions on this dashboard's data"}):o?e.jsx("article",{className:a.cn("rounded-card border border-border px-4 py-3",c&&"bg-background "),children:e.jsx(xr,{markdown:o})}):l?e.jsx(or,{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."}),(b=r==null?void 0:r.warnings)!=null&&b.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(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:r.warnings.join(" ")})]})}):null]})}function bn({run:t,onExpand:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,deletePending:c}){const u=ar(t),d=t.status==="FAILED";return e.jsxs("div",{className:"space-y-4","aria-label":"Briefing run result",children:[d?e.jsx(cr,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,onDeleteRun:n,deletePending:c}):null,u?e.jsxs("div",{children:[e.jsx("div",{className:ne,children:"Email"}),e.jsx("div",{className:"mt-2",children:e.jsx(ds,{preview:u,onExpand:s})})]}):null,!u&&ce(t.result)&&typeof t.result.summary=="string"?e.jsxs("div",{children:[e.jsx("div",{className:ne,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(qo,{run:t}),e.jsx(lr,{run:t,labelPrefix:"Run"})]})}function li({previewRun:t,isStale:s,onViewOutput:n}){var o,l;const r=((o=t.result)==null?void 0:o.title)??((l=t.result)==null?void 0:l.summary)??"Generated briefing preview";return e.jsx("div",{className:a.cn("rounded-card border px-3 py-2",te.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:a.cn("flex items-center gap-1.5 text-[11px] font-medium",te.success.label),children:[e.jsx(a.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:Fe,onClick:n,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})]})})}function ot(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:Mn,updateBriefing:pt,pauseBriefing:ts,resumeBriefing:ss,deleteBriefing:ns,getBriefing:es,runBriefingNow:rs,getBriefingRun:as,cancelBriefingRun:On,deleteBriefingRun:Un,previewBriefingPlan:Pn,runBriefingPreview:Bn,getBriefingPreviewRun:Vn,polishBriefingText:$n},jn=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 zt(t,s,n,r){const o=await fetch(xi(t,n),{cache:"no-store",...r,headers:{...(r==null?void 0:r.headers)??{},Authorization:`Bearer ${s}`}}),l=await o.json().catch(()=>({}));if(!o.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 yn(t){if(t.briefing)return qe(t.briefing);const s=pr(t.briefing,t.sourceContext);return tr({source:s.source,name:s.source.type==="dashboard"?"Dashboard Briefing":"Project Briefing",instruction:Qt,...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:o="Briefing",className:l,client:c,generateRequestId:u=hi,onSaved:d,onDeleted:m,onRunStarted:x,onCancel:g,onBack:p,onMinimizeRun:b}){var Rs,Ms,Ps,Bs,Vs,Os,Us,$s,_s;const{authToken:A,tokenProps:N}=i.useSemaphorContext(),w=((Ms=(Rs=N.config)==null?void 0:Rs.projectFeatures)==null?void 0:Ms.features.aiWritingHelpers)!==!1,{currentUser:j}=i.useCurrentUserInfo(),C=a.useDashboardStore(f=>f.dashboard),y=a.useDashboardStore(f=>f.theme),S=a.useDashboardStore(f=>f.selectedSheetId),T=a.useDashboardStore(f=>f.filterValues),V=a.useDashboardStore(f=>f.controlValues),D=a.useDashboardStore(f=>f.semanticExecutionPayload),F=a.useDashboardStore(f=>f.cardControlValuesMap),U=a.useDashboardStore(f=>f.inlineFilterValuesMap),q=a.useDashboardStore(f=>f.dashboardInputValues),B=a.useInteractionStore(f=>f.interactionStates),_=t??(N==null?void 0:N.apiServiceUrl),$=s??(A==null?void 0:A.accessToken),P=h.useMemo(()=>({...di,...c}),[c]),G=h.useMemo(()=>pr(n,r),[n,r]),Y=h.useMemo(()=>Fo(j),[j]),[L,K]=h.useState(n??null),[k,ae]=h.useState(()=>yn({briefing:n,sourceContext:G,defaultRecipient:Y})),[Q,X]=h.useState(null),[me,je]=h.useState([]),[oe,H]=h.useState(null),[Re,ye]=h.useState(null),[Se,Ne]=h.useState(null),[W,we]=h.useState(null),[O,se]=h.useState(0),[ze,Ve]=h.useState(null),[I,M]=h.useState(!1),[xe,E]=h.useState("edit"),[z,Z]=h.useState(0),[ve,Me]=h.useState(!1),[yr,ft]=h.useState("EMAIL"),[vr,gt]=h.useState(!1),[us,bt]=h.useState(null),[Nr,jt]=h.useState(!1),[de,wr]=h.useState(null),[yt,ms]=h.useState([]),[et,hs]=h.useState(!1),[xs,ps]=h.useState(null),[Cr,Sr]=h.useState(0),[Oe,tt]=h.useState(null),[kr,vt]=h.useState(!1),[Nt,fs]=h.useState(!1),[gs,bs]=h.useState(null),[Ke,wt]=h.useState(null);h.useEffect(()=>{if(!Ke)return;const f=window.setTimeout(()=>wt(null),12e3);return()=>window.clearTimeout(f)},[Ke]);const js=h.useRef(void 0),{activeRunId:Dr,resetTerminalRun:ys,startRun:Ct,stop:St}=Xt({apiServiceUrl:_,token:$,intervalMs:jn,timeoutMs:mi,fetchRun:({apiServiceUrl:f,token:v,runId:R})=>{if(!(L!=null&&L.id))throw new Error("Missing saved Briefing id for run polling.");return P.getBriefingRun(f,v,L.id,R)},onRun:f=>{ye(f)},onTerminalRun:f=>{E("result"),H(null)},onError:f=>{H(`Unable to refresh briefing run status: ${Ce(f)}`)},onTimeout:()=>{H("Briefing run status refresh timed out. Refresh the run to check the latest status.")}}),{activeRunId:Er,startRun:Ar,stop:vs}=Xt({apiServiceUrl:_,token:$,intervalMs:jn,timeoutMs:ui,fetchRun:({apiServiceUrl:f,token:v,runId:R})=>P.getBriefingPreviewRun(f,v,R),onRun:f=>{we(f),f.status==="SUCCESS"&&Ve(v=>v??O)},onTerminalRun:f=>{f.status==="FAILED"?H(f.error||"Briefing preview failed."):(H(null),E("result"))},onError:f=>{H(`Unable to refresh briefing preview status: ${Ce(f)}`)},onTimeout:f=>{we(v=>(v==null?void 0:v.id)===f?{...v,status:"FAILED",completedAt:v.completedAt??new Date().toISOString(),error:v.error||"Briefing preview status refresh timed out."}:v),H("Briefing preview status refresh timed out.")}}),le=!!(L!=null&&L.id),kt=(L==null?void 0:L.status)==="PAUSED"||k.schedule.status==="PAUSED",Ir=le&&!!(L!=null&&L.scheduleExpr||k.schedule.enabled),Ue=Re??(L==null?void 0:L.latestRun)??null,fe=Ue&&_e(Ue.status)&&Dr===Ue.id?Ue:null,be=Ue&&nr(Ue.status)?Ue:null,ge=xe==="result"&&((W==null?void 0:W.status)==="SUCCESS"||be)?"result":xe==="plan"&&Se?"plan":"edit",Tr=G.detail??(k.source.type==="dashboard"?(C==null?void 0:C.title)??null:"All project data available to this token"),Ns=(L==null?void 0:L.status)??k.schedule.status,Dt=W!==null&&_e(W.status)&&Er===W.id||fe!==null,Pe=Q!==null||Dt,Lr=ge==="edit"&&be!==null&&!Dt,Et=(W==null?void 0:W.status)==="SUCCESS"&&W.result?W:null,Fr=Et!==null&&ze!==null&&ze!==O,We=us==="preview"?W:null,Ee=us==="saved"?be:null,Ge=Ee?ar(Ee):null,Rr=((Ps=We==null?void 0:We.result)==null?void 0:Ps.title)??(Ge==null?void 0:Ge.subject)??(ce(Ee==null?void 0:Ee.result)&&typeof Ee.result.title=="string"?Ee.result.title:null)??(L==null?void 0:L.name)??"Briefing preview",st=h.useMemo(()=>({dashboard:C,theme:y||"light",filters:C==null?void 0:C.filters,selectedSheetId:S,filterValues:T,inlineFilterValuesMap:U,controlValues:V,controlDefinitions:(C==null?void 0:C.controls)||[],dashboardControls:(C==null?void 0:C.controls)||[],cardControlValuesMap:F,dashboardInputValues:q,semanticExecutionPayload:D,interactionStates:B}),[F,V,C,q,T,B,U,D,S,y]);h.useEffect(()=>{const f=(n==null?void 0:n.id)??null;if(js.current===f)return;js.current=f,ys(),St(),vs(),K(n??null);let v=yn({briefing:n,sourceContext:G,defaultRecipient:Y}),R=null;if(!n){const zs=at.findIndex(Le=>Le.label==="Business review"&&(!Le.available||Le.available(v.source))),Gr=at.findIndex(Le=>!Le.available||Le.available(v.source)),Rt=zs!==-1?zs:Gr;if(Rt!==-1){const Le=at[Rt];v=it(v,Le.draft(v.source,{attachments:Le.seedsDashboardAttachment?Xs({source:v.source,dashboard:C,selectedSheetId:S,runtime:st}):void 0})),R=Rt}}ae(v),Z(R),ye(null),Ne(null),we(null),Ve(null);const ee=(n==null?void 0:n.latestRun)??null;H(null),E("edit"),ee&&_e(ee.status)&&Ct(ee)},[st,n,C,Y,ys,G,S,Ct,vs,St]);const At=k.delivery.channels.includes("EMAIL"),Ae=k.delivery.channels.includes("SLACK"),nt=At&&Ae,J=(Vs=(Bs=k.delivery.channelConfigs)==null?void 0:Bs.SLACK)==null?void 0:Vs.slackConfig,ws=((Os=J==null?void 0:J.destination)==null?void 0:Os.type)==="channel"?J.destination.channelId??"":"",Ie=yt.find(f=>f.id===ws),rt=(J==null?void 0:J.threadMentions)??[],Cs=rt.length>0,Ss=JSON.stringify({recipients:rt}),It=Ae&&!At?"SLACK":At&&!Ae?"EMAIL":yr,Tt=It==="EMAIL"?"SLACK":"EMAIL";h.useEffect(()=>{if(!_||!$||!Ae)return;let f=!1;return hs(!0),ps(null),Promise.all([zt(_,$,"/v1/integrations/SLACK/status"),zt(_,$,"/v1/integrations/slack/channels").catch(v=>{if(v instanceof Error&&/not configured/i.test(v.message))return{channels:[]};throw v})]).then(([v,R])=>{f||(wr(v),ms(R.channels))}).catch(v=>{f||(ps(Ce(v)),ms([]))}).finally(()=>{f||hs(!1)}),()=>{f=!0}},[Ae,_,$,Cr]),h.useEffect(()=>{if(!_||!$||!Ae){tt(null);return}if(!Cs||!(de!=null&&de.installed)){tt(null);return}let f=!1;return zt(_,$,"/v1/integrations/slack/mention-status",{method:"POST",headers:{"Content-Type":"application/json"},body:Ss}).then(v=>{f||tt(v)}).catch(()=>{f||tt(null)}),()=>{f=!0}},[Ae,Cs,_,$,de==null?void 0:de.installed,Ss]);const ie=f=>{ae(v=>it(v,f)),je([]),H(null),L!=null&&L.id||(Ne(null),se(v=>v+1),E("edit"))},Te=()=>!_||!$?(H("Missing Semaphor API credentials."),null):{apiServiceUrl:_,token:$},Mr=async f=>{const v=Gt(k);if(je(v.issues),H(null),!v.valid)return null;const R=Te();if(!R)return null;f!=null&&f.pendingAction&&X(f.pendingAction);try{const ee=L!=null&&L.id?await P.updateBriefing(R.apiServiceUrl,R.token,L.id,sr(k)):await P.createBriefing(R.apiServiceUrl,R.token,Wt(k));return K(ee.briefing),ae(qe(ee.briefing)),d==null||d(ee.briefing),ee.briefing}catch(ee){return H(Ce(ee)),null}finally{f!=null&&f.pendingAction&&X(null)}},Pr=async()=>Mr({pendingAction:"save"}),ks=()=>{const f=Gt(k);return je(f.issues),H(null),f.valid?Wt(k):null},Ds=async f=>{const v=Te();if(!v)return null;const R=ks();if(!R)return null;X("plan");try{const ee=await P.previewBriefingPlan(v.apiServiceUrl,v.token,R);return Ne(ee.plan),f!=null&&f.silent||E("plan"),ee.plan}catch(ee){return H(Ce(ee)),null}finally{X(null)}},Br=async()=>{const f=Te();if(!f)return;const v=ks();if(v)try{const R=Se??await Ds({silent:!0});if(!R)return;X("preview");const ee=await P.runBriefingPreview(f.apiServiceUrl,f.token,{draft:v,planId:R.id,requestId:u()});Ve(O),Ar(ee.previewRun)}catch(R){H(Ce(R))}finally{X(null)}},Lt=async()=>{const f=Te();if(f){if(!(L!=null&&L.id)){await Br();return}if($e){H("Save your changes before running this briefing.");return}X("run"),H(null),we(null);try{const v=await P.runBriefingNow(f.apiServiceUrl,f.token,L.id,{requestId:u()});Ct(v.run),x==null||x(v)}catch(v){H(Ce(v))}finally{X(null)}}},Es=async()=>{if(!(L!=null&&L.id))return null;const f=Te();if(!f)return null;const v=await P.getBriefing(f.apiServiceUrl,f.token,L.id);return K(v.briefing),ae(qe(v.briefing)),d==null||d(v.briefing),v.briefing},Vr=async()=>{if(!(L!=null&&L.id)||!(fe!=null&&fe.id))return;const f=Te();if(f){X("cancelRun"),H(null);try{const v=await P.cancelBriefingRun(f.apiServiceUrl,f.token,L.id,fe.id);St(),ye(v.run),E("result"),await Es().catch(()=>null)}catch(v){H(Ce(v))}finally{X(null)}}},Or=()=>{!L||!fe||b==null||b({briefing:{...L,latestRun:fe},run:fe})},Ur=async()=>{if(!k.instruction.trim())return;const v=Te();if(v){fs(!0),bs(null);try{const R=await P.polishBriefingText(v.apiServiceUrl,v.token,k.instruction),ee=k.instruction;ie({instruction:R}),wt({previousText:ee})}catch(R){bs(Ce(R))}finally{fs(!1)}}},$r=()=>{Ke&&(ie({instruction:Ke.previousText}),wt(null))},As=async f=>{if(!(L!=null&&L.id))return;const v=Te();if(v){X("deleteRun"),H(null);try{await P.deleteBriefingRun(v.apiServiceUrl,v.token,L.id,f);const R=await Es().catch(()=>null),ee=(R==null?void 0:R.latestRun)??null;ye(ee),ee||E("edit")}catch(R){H(Ce(R))}finally{X(null)}}},_r=async f=>{if(!(L!=null&&L.id))return;const v=Te();if(v){X(f==="PAUSED"?"pause":"resume"),H(null);try{const R=f==="PAUSED"?await P.pauseBriefing(v.apiServiceUrl,v.token,L.id):await P.resumeBriefing(v.apiServiceUrl,v.token,L.id);K(R.briefing),ae(qe(R.briefing)),d==null||d(R.briefing)}catch(R){H(Ce(R))}finally{X(null)}}},zr=k.instruction.split(`
111
+ `).map(f=>f.trim()).find(f=>f.length>0),Is=h.useMemo(()=>L?qe(L):null,[L]),$e=!!Is&&JSON.stringify(k)!==JSON.stringify(Is),Be=k.body.type==="custom_message",Ft=Be?"Note":"Analysis",Xe=Be?"Email body":"What should this briefing investigate?",Ts=Be?"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.",Ls=Be?"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.",Fs=f=>{var v,R;if(ft(f),f==="EMAIL"){ie({delivery:{channels:ot(k.delivery.channels,"EMAIL")}});return}ie({delivery:{channels:ot(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((v=k.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...J??{},destination:((R=J==null?void 0:J.destination)==null?void 0:R.type)==="channel"?J.destination:{type:"channel",channelId:""},postThreadDetail:(J==null?void 0:J.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},qr=()=>{if(nt){ie({delivery:{channels:ci(k.delivery.channels,Tt)}});return}Fs(Tt)},Hr=f=>{var R;const v=yt.find(ee=>ee.id===f);ft("SLACK"),ie({delivery:{channels:ot(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((R=k.delivery.channelConfigs)==null?void 0:R.SLACK)??{},formatProfile:"concise",slackConfig:{...J??{},destination:{type:"channel",channelId:f,...v?{channelName:v.name}:{},...v?{isPrivate:v.isPrivate}:{}},postThreadDetail:(J==null?void 0:J.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Kr=f=>{var v,R;ft("SLACK"),ie({delivery:{channels:ot(k.delivery.channels,"SLACK"),channelConfigs:{...k.delivery.channelConfigs??{},SLACK:{...((v=k.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...J??{},destination:((R=J==null?void 0:J.destination)==null?void 0:R.type)==="channel"?J.destination:{type:"channel",channelId:""},threadMentions:f,postThreadDetail:(J==null?void 0:J.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Wr=h.useMemo(()=>{const f=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"}`,ee=Ie?`#${Ie.name}`:"Slack channel";return nt?`${f} · ${R} · ${ee}`:Ae?`${f} · ${Ie?`#${Ie.name}`:"Slack channel"}`:`${f} · ${R}`},[k.delivery.recipients.length,k.schedule.enabled,k.schedule.scheduleExpr,nt,Ae,Ie]);return e.jsxs("section",{className:a.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:[p?e.jsxs("button",{type:"button",onClick:p,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(i.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:o})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[le?e.jsx("span",{className:a.cn("inline-flex items-center rounded-control px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.06em]",fi(Ns)),children:Ns}):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(a.X,{className:"h-3.5 w-3.5"})}):null]})]}),ge!=="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:zr||k.name||"Untitled briefing"}),e.jsx("div",{className:"mt-0.5 truncate text-[10px] text-muted-foreground",children:Wr})]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:["Edit brief",e.jsx(a.ChevronDown,{className:"h-3 w-3 rotate-180"})]})]}):null,fe?e.jsx(Go,{}):null,e.jsx(Yo,{pendingAction:Q,previewRun:W,savedActiveRun:fe,detailsVisible:ve,onShowDetails:()=>Me(f=>!f),onCancelSavedRun:fe?Vr:void 0,onMinimizeRun:fe&&b?Or:void 0}),ve&&W&&_e(W.status)?e.jsx(fn,{run:W}):ve&&fe?e.jsx(fn,{run:fe}):null,e.jsx("div",{className:"flex-1 space-y-5 overflow-y-auto px-4 py-4",children:ge==="edit"?e.jsxs(e.Fragment,{children:[le?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"mb-2"),children:"Start from"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:at.map((f,v)=>{if(f.available&&!f.available(k.source))return null;const R=z===v;return e.jsx("button",{type:"button",onClick:()=>{Z(v),ie(f.draft(k.source,{attachments:f.seedsDashboardAttachment?Xs({source:k.source,dashboard:C,selectedSheetId:S,runtime:st}):void 0}))},className:a.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":`${f.label} preset — ${f.description}`,children:f.label},f.label)})})]}),Et?e.jsx(li,{previewRun:Et,isStale:Fr,onViewOutput:()=>E("result")}):null,Lr&&be?e.jsx(Ko,{run:be,onViewOutput:()=>E("result"),onDeleteRun:be.status==="FAILED"?()=>As(be.id):void 0,onRetryRun:be.status==="FAILED"&&le?()=>{Lt()}:void 0,retryDisabled:Pe||le&&$e,retryDisabledReason:le&&$e?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:Q==="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:ne,children:Ft}),e.jsx("button",{type:"button",onClick:()=>vt(!0),"aria-label":`Expand ${Ft.toLowerCase()}`,title:`Expand ${Ft.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(i.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:f=>{Z(null),ie({name:f.target.value})},placeholder:"Weekly revenue briefing"}),e.jsx("label",{htmlFor:"briefing-instruction",className:"sr-only",children:Xe}),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:f=>{Z(null),ie({instruction:f.target.value})},placeholder:Ts,"aria-label":Xe}),e.jsx("p",{className:"mt-2 text-[11px] leading-[1.5] text-muted-foreground",children:Ls})]}),Be?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:Pe,onClick:()=>jt(!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(Co,{includeEvidence:k.output.includeEvidence,includeSql:k.output.includeSql,includeHtml:k.output.artifactFormats.includes("html"),onChange:(f,v)=>{ie(f==="evidence"?{output:{includeEvidence:v}}:f==="sql"?{output:{includeSql:v}}:{output:{artifactFormats:So(k.output.artifactFormats,"html",v)}})}})]})]}),e.jsx(i.Dialog,{open:kr,onOpenChange:vt,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:Xe}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:Ls})]}),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:Xe}),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:f=>{Z(null),ie({instruction:f.target.value})},placeholder:Ts,"aria-label":Xe})]}),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:gs?e.jsx("span",{className:"text-destructive",children:gs}):Ke?e.jsxs("button",{type:"button",onClick:$r,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(wn,{className:"h-3 w-3"}),"Revert polish"]}):null}),w?e.jsxs("button",{type:"button",onClick:Ur,disabled:Nt||!k.instruction.trim()||!_||!$,title:"Fix typos, grammar, and minor wording without changing your meaning",className:Fe,children:[Nt?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.Sparkles,{className:"h-3 w-3"}),Nt?"Polishing…":"Polish"]}):null,e.jsx("button",{type:"button",onClick:()=>vt(!1),className:Fe,children:"Done"})]})]})}),k.source.type==="dashboard"?e.jsxs("div",{children:[k.attachments.length>0?e.jsx(uo,{attachments:k.attachments,disabled:Pe,onAdd:()=>jt(!0),onChange:f=>ie({attachments:f.map(De)})}):null,e.jsx(po,{open:Nr,onOpenChange:jt,source:k.source,dashboard:C,selectedSheetId:S,runtime:st,selectedAttachments:k.attachments,onSubmit:f=>ie({attachments:f})})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"mb-2"),children:"When"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(tn,{label:"On demand only",description:"Save the briefing and run it manually when needed.",checked:!k.schedule.enabled,onSelect:()=>ie({schedule:{enabled:!1}}),name:"briefing-schedule-mode"}),e.jsx(tn,{label:"Scheduled",description:"Store the cadence so the runner picks it up later.",checked:k.schedule.enabled,onSelect:()=>ie({schedule:{enabled:!0}}),name:"briefing-schedule-mode"})]}),k.schedule.enabled?e.jsx("div",{className:"mt-3 pl-6",children:e.jsx(ko,{scheduleExpr:k.schedule.scheduleExpr||i.buildScheduleExpr(i.DEFAULT_SCHEDULE_VM),timezone:k.schedule.timezone||"UTC",onScheduleChange:f=>ie({schedule:{scheduleExpr:f.scheduleExpr,timezone:f.timezone}})})}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"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(f=>{const v=k.delivery.channels.includes(f),R=It===f;return e.jsxs("button",{type:"button",onClick:()=>Fs(f),"aria-pressed":v,className:a.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:[f==="EMAIL"?e.jsx(vn,{className:"h-3 w-3"}):e.jsx(qt,{className:"h-3 w-3"}),f==="EMAIL"?"Email":"Slack"]},f)})}),e.jsxs("button",{type:"button",onClick:qr,className:a.cn(Ye,"h-6 px-1.5 text-[11px]"),children:[nt?"- Remove":"+ Also send"," ",Tt==="EMAIL"?"Email":"Slack"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"mb-2"),children:"Recipients"}),It==="EMAIL"?e.jsx(Ys,{value:k.delivery.recipients,onChange:f=>ie({delivery:{recipients:f}})}):de===null&&et?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(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Loading Slack workspace…"]}):de!=null&&de.installed?e.jsxs("div",{className:"space-y-2",children:[e.jsx(To,{channels:yt,selectedChannelId:ws,onChange:Hr,destinationKind:"channel",onDestinationKindChange:()=>{},loading:et}),e.jsx(Ys,{value:rt,onChange:Kr,prefix:"Thread @",placeholder:rt.length>0?"Add more…":"Mention people in the thread reply"}),Oe&&Oe.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(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{children:[Oe.unlinkedCount," of"," ",Oe.linkedCount+Oe.unlinkedCount," ",Oe.linkedCount+Oe.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:((_s=de==null?void 0:de.workspace)==null?void 0:_s.teamName)??"Slack"}),Ie?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{children:Ie.isMember?`Bot in #${Ie.name}`:`Can post to #${Ie.name}`})]}):null]}),xs?e.jsx("p",{className:"text-[11px] text-destructive",children:xs}):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(qt,{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:(Us=de==null?void 0:de.capabilities)!=null&&Us.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:[($s=de==null?void 0:de.capabilities)!=null&&$s.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(f=>f+1),disabled:et,className:Fe,children:[et?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.RefreshCw,{className:"h-3 w-3"}),"Refresh"]})]})]})]}),Be?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(ne,"mb-2"),children:"Scope"}),e.jsx(Io,{source:k.source,resolvedSourceContext:G,sourceDetail:Tr,onChange:f=>ie({source:f})})]})]}):ge==="plan"&&Se?e.jsx(_o,{previewPlan:Se,previewRun:W&&W.status!=="SUCCESS"?W:null,scopeLabel:G.source.type==="dashboard"?(C==null?void 0:C.title)??G.label:G.label}):ge==="result"&&W?e.jsx(gn,{previewRun:W,onExpand:()=>{bt("preview"),gt(!0)}}):ge==="result"&&be?e.jsx(bn,{run:be,onExpand:()=>{bt("saved"),gt(!0)},onDeleteRun:be.status==="FAILED"?()=>As(be.id):void 0,onRetryRun:be.status==="FAILED"&&le?()=>{Lt()}:void 0,retryDisabled:Pe||le&&$e,retryDisabledReason:le&&$e?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:Q==="deleteRun"}):null}),me.length>0||oe?e.jsxs("div",{className:"shrink-0 space-y-2 border-t border-destructive/30 bg-destructive/10 px-4 py-2.5",children:[me.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(a.Info,{className:"h-3 w-3"}),"Fix these before saving:"]}),e.jsx("ul",{className:"space-y-0.5 pl-4",children:me.map(f=>e.jsx("li",{className:"list-disc marker:text-destructive/60",children:f.message},`${f.field}:${f.message}`))})]}):null,oe?e.jsxs("div",{role:"alert",className:"flex items-start gap-1.5 text-[12px] leading-[1.55] text-destructive",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:oe})]}):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:le&&Ir?e.jsxs("button",{type:"button",className:Fe,disabled:Pe,onClick:()=>_r(kt?"ACTIVE":"PAUSED"),children:[Q==="pause"||Q==="resume"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):kt?e.jsx(i.Play,{className:"h-3 w-3"}):e.jsx(Nn,{className:"h-3 w-3"}),kt?"Resume":"Pause"]}):!le&&(ge==="plan"||ge==="result")?e.jsxs("button",{type:"button",className:Ye,onClick:()=>E("edit"),children:[e.jsx(i.ChevronRight,{className:"h-3 w-3 rotate-180"}),ge==="result"?"Edit brief":"Tweak brief"]}):!le&&g&&!p?e.jsx("button",{type:"button",className:Ye,onClick:g,children:"Discard"}):null}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!le&&ge==="edit"&&!Be?e.jsxs("button",{type:"button",className:Fe,disabled:Pe,onClick:()=>{Ds()},children:[Q==="plan"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(Yr,{className:"h-3 w-3"}),"Show plan"]}):null,le||!Be?e.jsxs("button",{type:"button",className:Fe,disabled:Pe||le&&$e,onClick:Lt,title:le&&$e?"Save your changes before running — Run now uses the saved briefing.":void 0,children:[Q==="run"||Q==="preview"||Dt?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):ge==="result"?e.jsx(i.RefreshCw,{className:"h-3 w-3"}):ge==="plan"?e.jsx(Ht,{className:"h-3 w-3"}):le?e.jsx(i.Send,{className:"h-3 w-3"}):e.jsx(Ht,{className:"h-3 w-3"}),le?"Run now":ge==="plan"?"Run plan":ge==="result"?"Run again":"Dry run"]}):null,e.jsxs("button",{type:"button",className:le?Fe:on,disabled:Pe,onClick:Pr,children:[Q==="save"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(a.Check,{className:"h-3 w-3"}),le?"Save changes":"Create briefing"]})]})]})}),e.jsx(i.Dialog,{open:vr,onOpenChange:f=>{gt(f),f||bt(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:Rr}),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(gn,{previewRun:We,fullWidth:!0}):Ge?e.jsx(ds,{preview:Ge}):Ee?e.jsx(bn,{run:Ee}):null})]})})]})}function gr({disabled:t,briefingCount:s,className:n,onClick:r}){const o=typeof s=="number"&&s>0;return e.jsxs(a.Button,{type:"button",size:"xs",variant:"outline",disabled:t,className:a.cn("gap-1.5",n),onClick:r,"aria-label":"Briefings",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Briefings",o?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:Rn,getBriefing:es,pauseBriefing:ts,resumeBriefing:ss,deleteBriefing:ns,runBriefingNow:rs},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 o=[];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(o.push(...m),c+=m.length,u=d.total,m.length===0||c>=u)break;l+=1}return o}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 o=Math.round(r/60);if(o<24)return`${o}h ago`;const l=Math.round(o/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:a.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:o,onSourceViewChange:l,onClose:c,onEdit:u,onNew:d,onRunNow:m,onTogglePause:x,onDelete:g,selectingId:p,busyId:b,manageBriefingsHref:A}){const N=t.length,w=t.filter(y=>y.status==="ACTIVE").length,j=t.find(y=>y.hasActiveRun)??null,C=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:C})]}),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(a.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:o&&N===0?e.jsx("span",{children:"Loading briefings…"}):N===0?e.jsx("span",{children:"No briefings yet"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[N," watching"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[w," active"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[o?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,N>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(a.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,!o&&t.length===0&&!r?e.jsx(Li,{onNew:d}):null,t.map(y=>e.jsx(Ri,{briefing:y,isOpening:p===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:a.cn(ji,"h-6 px-1 text-[11px]"),children:["Manage all briefings",e.jsx(Xr,{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:a.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:o,onTogglePause:l,onDelete:c}){const u=t.status==="PAUSED",d=t.hasActiveRun,m=Ei(t),x=ki(t.lastRunAt),g=t.lastRunStatus,p=g==="SUCCESS"?te.success.dot:g==="FAILED"?te.danger.dot:g?te.warning.dot:te.neutral.dot;return e.jsxs("div",{className:a.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(a.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground/70"}):e.jsx("span",{className:a.cn("inline-block h-1.5 w-1.5 shrink-0 rounded-full",p)}),e.jsx("span",{className:"truncate",children:d?jr(t):m})]}):null]}),e.jsx("div",{className:"absolute right-3 top-3",children:n?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):s?e.jsx(a.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(),o()},children:[e.jsx(Ht,{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(Nn,{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 Mi=2e3,Pi=20*6e4;function Bi({briefingId:t,initialRun:s,apiServiceUrl:n,token:r,onTerminal:o,onTimeout:l,onExpand:c}){const[u,d]=h.useState(s),{startRun:m}=Xt({apiServiceUrl:n,token:r,intervalMs:Mi,timeoutMs:Pi,fetchRun:({apiServiceUrl:g,token:p,runId:b})=>as(g,p,t,b),onRun:g=>{d(g)},onTerminalRun:g=>{o(g)},onTimeout:()=>{l()}}),x=h.useRef(!1);return h.useEffect(()=>{x.current||(x.current=!0,dt(s.status)?m(s):ct(s.status)&&o(s))},[s,o,m]),e.jsx(Xo,{run:u,onExpand:c})}function Vi({dashboardId:t,dashboardTitle:s,apiServiceUrl:n,token:r,disabled:o,className:l,manageBriefingsHref:c,client:u}){const{authToken:d,tokenProps:m}=i.useSemaphorContext(),[x,g]=h.useState(!1),[p,b]=h.useState("list"),[A,N]=h.useState("dashboard"),[w,j]=h.useState([]),[C,y]=h.useState(null),[S,T]=h.useState(!1),[V,D]=h.useState(null),[F,U]=h.useState(null),[q,B]=h.useState(null),[_,$]=h.useState(null),[P,G]=h.useState(null),[Y,L]=h.useState(null),K=n??(m==null?void 0:m.apiServiceUrl),k=r??(d==null?void 0:d.accessToken),ae=h.useMemo(()=>({...gi,...u}),[u]),Q=yi(s),X=h.useMemo(()=>Ci(w,A,t),[t,w,A]),me=h.useMemo(()=>A==="dashboard"?{source:{type:"dashboard",dashboardId:t},label:Q,detail:vi(Q)}:{source:{type:"project"},label:"This project",detail:"Use any data in this project."},[t,Q,A]),je=!!(K&&k),oe=h.useCallback(async()=>{if(!(!K||!k)){T(!0),$(null);try{j(await Si({apiClient:ae,apiServiceUrl:K,token:k}))}catch(O){$(O instanceof Error?O.message:"Could not load briefings.")}finally{T(!1)}}},[ae,K,k]);h.useEffect(()=>{!x||p!=="list"||!je||oe()},[je,oe,x,p]);const H=()=>{y(null),N("dashboard"),b("list"),g(!0)},Re=()=>{y(null),b("author")},ye=async O=>{if(!(!K||!k)){D(O),$(null);try{const se=await ae.getBriefing(K,k,O);y(se.briefing),b("author")}catch(se){$(se instanceof Error?se.message:"Could not open briefing.")}finally{D(null)}}},Se=async O=>{if(!(!K||!k)){U(O.id);try{await ae.runBriefingNow(K,k,O.id,{requestId:Oi()}),oe()}catch(se){i.ue.error(se instanceof Error?se.message:"Could not start the run.")}finally{U(null)}}},Ne=async O=>{if(!(!K||!k)){U(O.id);try{const se=O.status==="PAUSED"?await ae.resumeBriefing(K,k,O.id):await ae.pauseBriefing(K,k,O.id);i.ue.success(se.briefing.status==="PAUSED"?"Briefing paused":"Briefing resumed"),oe()}catch(se){i.ue.error(se instanceof Error?se.message:"Could not update the briefing status.")}finally{U(null)}}},W=async()=>{if(!q||!K||!k)return;const O=q;U(O.id);try{await ae.deleteBriefing(K,k,O.id),i.ue.success("Briefing deleted"),B(null),oe()}catch(se){i.ue.error(se instanceof Error?se.message:"Could not delete the briefing.")}finally{U(null)}},we=X.length;return e.jsxs(i.Sheet,{open:x,onOpenChange:g,children:[e.jsx(gr,{disabled:o||!je,briefingCount:we,className:l,onClick:H}),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."})]}),p==="list"?e.jsx(Ti,{briefings:X,dashboardLabel:Q,sourceView:A,error:_,loading:S,onSourceViewChange:N,onClose:()=>g(!1),onEdit:O=>{ye(O)},onNew:Re,onRunNow:O=>{Se(O)},onTogglePause:O=>{Ne(O)},onDelete:O=>B(O),selectingId:V,busyId:F,manageBriefingsHref:c}):e.jsx(fr,{apiServiceUrl:K,token:k,briefing:C,sourceContext:C?void 0:me,title:C?"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"),oe()},onRunStarted:()=>{},onSaved:O=>{y(O),oe()},onMinimizeRun:({briefing:O,run:se})=>{G({briefing:O,run:se}),g(!1)}})]}),P&&K&&k?e.jsx(Bi,{briefingId:P.briefing.id,initialRun:P.run,apiServiceUrl:K,token:k,onTerminal:O=>{L({briefing:P.briefing,run:O}),G(null),oe()},onTimeout:()=>{G(null),oe()},onExpand:()=>{y(P.briefing),b("author"),G(null),g(!0)}}):null,Y?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(Qo,{title:Y.run.status==="SUCCESS"?`${Y.briefing.name} is ready`:`${Y.briefing.name} run failed`,durationSeconds:Y.run.startedAt&&Y.run.completedAt?Math.max(0,Math.floor((new Date(Y.run.completedAt).getTime()-new Date(Y.run.startedAt).getTime())/1e3)):null,status:Y.run.status==="SUCCESS"?"success":"failed",onView:()=>{y(Y.briefing),b("author"),L(null),g(!0)},onDismiss:()=>L(null)})}):null,e.jsx(i.AlertDialog,{open:!!q,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:q==null?void 0:q.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:W,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=ma;exports.BriefingAuthor=fr;exports.BriefingsApiError=ht;exports.DashboardBriefingLauncher=Vi;exports.DashboardControlsSettings=En;exports.DashboardFilterControlsButton=In;exports.DashboardFilterControlsLauncher=Ra;exports.DocumentControlsSettings=An;exports.ExportNotificationItem=kn;exports.ExportNotificationList=Dn;exports.NotificationBell=wa;exports.Undo2=wn;exports.UnsavedChangesAlert=ha;exports.UsersRound=Yt;exports.VisualEditingControls=ua;exports.VisualsLibraryDialog=aa;exports.WatchDashboardButton=gr;exports.applyBriefingFormPatch=it;exports.briefingFormDraftToCreateRequest=Wt;exports.briefingFormDraftToUpdateRequest=sr;exports.briefingToFormDraft=qe;exports.cancelBriefingRun=On;exports.createBriefing=Mn;exports.createBriefingFormDraft=tr;exports.deleteBriefing=ns;exports.deleteBriefingRun=Un;exports.getBriefing=es;exports.getBriefingArtifact=Oa;exports.getBriefingEvidence=Ua;exports.getBriefingPreviewRun=Vn;exports.getBriefingRun=as;exports.listBriefingRuns=Va;exports.listBriefingTenantSummaries=Ba;exports.listBriefings=Rn;exports.pauseBriefing=ts;exports.polishBriefingText=$n;exports.previewBriefingPlan=Pn;exports.resumeBriefing=ss;exports.runBriefingNow=rs;exports.runBriefingPreview=Bn;exports.updateBriefing=pt;exports.useExportPolling=ya;exports.useExportRecovery=va;exports.validateBriefingFormDraft=Gt;