react-semaphor 0.1.321 → 0.1.323

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 (35) hide show
  1. package/dist/brand-studio/index.js +4 -4
  2. package/dist/chunks/{braces-Cy5NEBa8.js → braces-ZjRH2Kl7.js} +1 -1
  3. package/dist/chunks/{calendar-preferences-dialog-D-0W76fR.js → calendar-preferences-dialog-B9Hz3pTH.js} +3 -3
  4. package/dist/chunks/{calendar-preferences-dialog-CzoSmQNw.js → calendar-preferences-dialog-CLXaVo3h.js} +1 -1
  5. package/dist/chunks/{chevrons-up-down-DZTs1oVD.js → chevrons-up-down-CA-XvN1o.js} +1 -1
  6. package/dist/chunks/{dashboard-briefing-launcher-Cqm8NnVb.js → dashboard-briefing-launcher-COLpvReF.js} +13 -13
  7. package/dist/chunks/{dashboard-briefing-launcher-D5z1kf6J.js → dashboard-briefing-launcher-CUEn7cr6.js} +6 -5
  8. package/dist/chunks/dashboard-controls-CLShFyUq.js +2258 -0
  9. package/dist/chunks/dashboard-controls-DH8gdpOc.js +52 -0
  10. package/dist/chunks/{dashboard-json-BRx9CbrK.js → dashboard-json-Db0DpTMw.js} +2 -2
  11. package/dist/chunks/{dashboard-json-ezFjz7Fc.js → dashboard-json-eGBWfSN1.js} +1 -1
  12. package/dist/chunks/{edit-dashboard-visual-Cw0KmT4i.js → edit-dashboard-visual-Cc3xpTNQ.js} +1 -1
  13. package/dist/chunks/{edit-dashboard-visual-sI6ds8MP.js → edit-dashboard-visual-DmMKWtln.js} +616 -616
  14. package/dist/chunks/{index-DX6Krdga.js → index-CMS4bp9G.js} +194 -194
  15. package/dist/chunks/{index-BZg7rVe-.js → index-PTx7430W.js} +21344 -21136
  16. package/dist/chunks/{palette-Bc-vOLSt.js → palette-D96DOM7E.js} +1 -1
  17. package/dist/chunks/{resource-management-panel-pN81x7Gw.js → resource-management-panel-C1mbF-2a.js} +18 -18
  18. package/dist/chunks/{resource-management-panel-CRRUcnVu.js → resource-management-panel-DR7Ku6sa.js} +1 -1
  19. package/dist/chunks/{save-CXa6cKaY.js → save-DxkSzUTZ.js} +1 -1
  20. package/dist/chunks/{switch-DdTUsWgd.js → switch-Deo2Ltmj.js} +6 -6
  21. package/dist/chunks/{use-create-flow-overlay-state-B9ujZUon.js → use-create-flow-overlay-state-B65gg2oB.js} +4 -4
  22. package/dist/chunks/{use-create-flow-overlay-state-BfV5187a.js → use-create-flow-overlay-state-CmxTpqeg.js} +1 -1
  23. package/dist/chunks/{use-visual-utils-D_uHFfTn.js → use-visual-utils-51Nsy8cj.js} +1 -1
  24. package/dist/chunks/{use-visual-utils-PxijRlpS.js → use-visual-utils-Diuguy3D.js} +20 -20
  25. package/dist/dashboard/index.cjs +1 -1
  26. package/dist/dashboard/index.js +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.js +131 -130
  29. package/dist/style.css +1 -1
  30. package/dist/surfboard/index.cjs +1 -1
  31. package/dist/surfboard/index.js +2 -2
  32. package/dist/types/main.d.ts +145 -0
  33. package/package.json +1 -1
  34. package/dist/chunks/dashboard-controls-CRIwHD59.js +0 -1999
  35. package/dist/chunks/dashboard-controls-DSt7iwFC.js +0 -52
@@ -1,4 +1,4 @@
1
- "use strict";const e=require("react/jsx-runtime"),a=require("./switch-BXICAlvS.js"),l=require("./index-DX6Krdga.js"),oe=require("./use-create-flow-overlay-state-BfV5187a.js"),h=require("react"),hn=require("./use-visual-utils-D_uHFfTn.js"),Ms=require("./date-formatter-D9Bvw5Qk.js");require("./index-DRlMUglg.js");require("react-dom");/**
1
+ "use strict";const e=require("react/jsx-runtime"),a=require("./switch-BXICAlvS.js"),l=require("./index-CMS4bp9G.js"),oe=require("./use-create-flow-overlay-state-CmxTpqeg.js"),h=require("react"),xn=require("./use-visual-utils-51Nsy8cj.js"),Bs=require("./date-formatter-D9Bvw5Qk.js");require("./index-DRlMUglg.js");require("react-dom");/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const Bs=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"}]]);/**
11
+ */const Vs=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"}]]);/**
12
12
  * @license lucide-react v0.453.0 - ISC
13
13
  *
14
14
  * This source code is licensed under the ISC license.
@@ -23,7 +23,7 @@
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */const xn=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"}]]);/**
26
+ */const pn=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"}]]);/**
27
27
  * @license lucide-react v0.453.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
@@ -38,22 +38,22 @@
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const pn=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"}]]);/**
41
+ */const fn=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"}]]);/**
42
42
  * @license lucide-react v0.453.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const fn=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"}]]);/**
46
+ */const gn=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"}]]);/**
47
47
  * @license lucide-react v0.453.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const gn=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"}]]);/**
51
+ */const Wt=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"}]]);/**
52
52
  * @license lucide-react v0.453.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const $t=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 Kr({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:o=!1,destinationMode:i="both",onConfirm:c}){const[u,d]=h.useState(n&&r?`Copy of ${r}`:r||""),[m,f]=h.useState("");h.useEffect(()=>{t&&(d(n&&r?`Copy of ${r}`:r||""),f(""))},[t,n,r]);const g=!!u.trim(),p=i==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:i==="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"},y=()=>{!g||o||c({name:u.trim(),description:m.trim()||void 0,saveToLibrary:p.saveToLibrary,saveToCurrentDashboard:p.saveToCurrentDashboard})};return e.jsx(l.Dialog,{open:t,onOpenChange:s,children:e.jsxs(l.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(l.DialogHeader,{children:[e.jsxs(l.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),p.badgeType!=="local"&&e.jsx(oe.VisualBadge,{type:p.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(l.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:I=>d(I.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(l.Textarea,{id:"description",value:m,onChange:I=>f(I.target.value),placeholder:"Enter visual description",rows:3,disabled:o})]})]}),e.jsxs(l.DialogFooter,{children:[e.jsx(a.Button,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancel"}),e.jsxs(a.Button,{onClick:y,disabled:!g||o,children:[o&&e.jsx(a.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p.actionLabel]})]})]})})}function Wr(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[o,i]=h.useState(null),[c,u]=h.useState(null),d=a.useEditorStore(D=>D.frame),m=a.useEditorStore(D=>D.card),f=l.useSelectedVisual(),g=a.useDashboardStore(D=>D.selectedSheetId),p=a.useDashboardStore(D=>D.dashboard),y=a.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:I}=hn.useVisualUtils(),{selectVisual:S}=l.useManagementActions(),{addFrame:N,setSelectedFrameId:b,setIsVisualEditing:T}=a.useDashboardActions(),j=l.useResolveExistingFrameSemanticExecutionPayload(),C=!!(d!=null&&d.visualId),A=(()=>{var D,R;return((D=d==null?void 0:d.cards)==null?void 0:D.length)===1&&((R=d.cards[0])!=null&&R.title)?d.cards[0].title:f!=null&&f.title?f.title:(m==null?void 0:m.title)||"Untitled Visual"})(),V=l.useCreateVisualWithFrame(D=>{D!=null&&D.id&&(S(D),n&&o&&c&&g&&(async()=>{try{const R={...o,id:a.v4(),visualId:D.id};N(g,R,{position:"end",semanticExecutionPayload:c}),b(R.id),r(!1),i(null),u(null),T(!1)}catch(R){console.error("Failed to promote semantic metadata for saved visual:",R),l.ue.error(R instanceof Error?R.message:"Failed to prepare semantic metadata for the saved visual")}})(),y(!0),s(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:s,handleSaveAs:async D=>{if(!g){l.ue.error("No sheet selected");return}const R=I(),_=a.getDynamicFrameSaveIssue(R);if(_){l.ue.error(_);return}const z=R.cards.length===1?{...R,cards:R.cards.map(U=>({...U,title:D.name}))}:R;if(D.saveToLibrary){let U=null;if(D.saveToCurrentDashboard)try{U=await j(z,{previousFrame:l.findDashboardFrameById(p,z.id)})}catch(W){console.error("Failed to prepare semantic metadata before saving visual:",W),l.ue.error(W instanceof Error?W.message:"Failed to prepare semantic metadata for the saved visual");return}r(D.saveToCurrentDashboard),i(z),u(U);const B={title:D.name,description:D.description,frameObject:z,isPrivate:!1};V.mutate(B)}else if(D.saveToCurrentDashboard){const U={...z,id:a.v4(),visualId:void 0};try{const B=await j(z,{previousFrame:l.findDashboardFrameById(p,z.id)});N(g,U,{position:"end",semanticExecutionPayload:B}),b(U.id),l.ue.success("Visual saved to dashboard"),s(!1),T(!1)}catch(B){console.error("Failed to save visual to dashboard:",B),l.ue.error(B instanceof Error?B.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:C,currentVisualName:A,isSaving:V.isPending}}function Gr(t={}){const s=a.useEditorStore(M=>M.frame),n=a.useEditorStore(M=>M.editorContext),r=l.useManagementStore(M=>M.selectedVisual),o=a.useDashboardStore(M=>M.selectedFrameId),i=a.useDashboardStore(M=>M.selectedSheetId),c=a.useDashboardStore(M=>M.dashboard),{setIsVisualEditing:u,updateFrame:d}=a.useDashboardActions(),[m,f]=h.useState(!1),[g,p]=h.useState("both"),y=l.useResolveExistingFrameSemanticExecutionPayload(),I=(n==null?void 0:n.type)==="documentSection",S=!!(s!=null&&s.visualId||r!=null&&r.id),N=!!(s!=null&&s.visualId&&o),b=S&&!N,{saveAsDialogOpen:T,setSaveAsDialogOpen:j,handleSaveAs:C,isLibraryVisual:A,currentVisualName:V,isSaving:L}=Wr(),{getUpdatedFrame:D}=hn.useVisualUtils();if(I)return e.jsxs(e.Fragment,{children:[e.jsx(oe.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(oe.EditorCancelButton,{})]});const R=async()=>{if(!i){l.ue.error("No sheet selected");return}if(m)return;f(!0);const M=D(),z=a.getDynamicFrameSaveIssue(M);if(z){f(!1),l.ue.error(z);return}const U={...M,visualId:void 0},B=l.findDashboardFrameById(c,U.id);try{const W=await y(U,{previousFrame:B});d(i,U,{semanticExecutionPayload:W})}catch(W){console.error("Failed to apply local semantic metadata:",W),f(!1),l.ue.error(W instanceof Error?W.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{f(!1),l.ue.success("Changes applied. Visual is now local to this dashboard"),u(!1)},300)},_=M=>{p(M),j(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(oe.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&b&&e.jsx(oe.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&N&&e.jsx(oe.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(l.DropdownMenu,{modal:!1,children:[e.jsx(l.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:L||m,children:e.jsx(a.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(l.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[N&&e.jsxs(e.Fragment,{children:[e.jsxs(l.DropdownMenuItem,{onClick:R,disabled:m,children:[e.jsx(a.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(l.DropdownMenuSeparator,{})]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("local"),disabled:L,children:[e.jsx(l.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("library"),disabled:L,children:[e.jsx(oe.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("both"),disabled:L,children:[e.jsx(oe.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(oe.EditorCancelButton,{}),e.jsx(Kr,{open:T,onOpenChange:M=>{L||j(M)},isLibraryVisual:A,currentVisualName:V,isSaving:L,destinationMode:g,onConfirm:C})]})}function Xr({className:t}){const s=a.useEditorStore(m=>m.isDevMode),n=a.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=a.useEditorActions(),{config:o}=h.useContext(l.SemaphorContext).tokenProps,i=(o==null?void 0:o.showAdvancedMode)!==!1;if(!n||!i)return null;const c=s?a.SlidersHorizontal:l.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 Jr({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:o,title:i="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 f=g=>{!g&&o||s(g)};return e.jsx(l.AlertDialog,{open:t,onOpenChange:f,children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:i}),e.jsx(l.AlertDialogDescription,{children:c})]}),e.jsxs(l.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(l.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 Qr=1e4,Yr=15e3,Zr=3e4,ea=3e4,ta=12e4,Vs=2*60*60*1e3;function sa(t){const s=Date.now()-t.getTime();return s<ea?Qr:s<ta?Yr:Zr}function na(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(p=>p.activeExports),[r,o]=h.useState(typeof document<"u"?!document.hidden:!0),i=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,f=h.useCallback(()=>{const p=l.useExportStore.getState().activeExports;return Array.from(p.values()).filter(y=>l.isExportInProgress(y.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=f();if(p.length===0){c.current=!1;return}const y=Date.now(),I=p.filter(j=>y-j.startedAt.getTime()>Vs);if(I.length>0){const{updateExport:j}=l.useExportStore.getState().actions;for(const C of I)j(C.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const S=p.filter(j=>y-j.startedAt.getTime()<=Vs);if(S.length===0){c.current=!1;return}const N=await Promise.allSettled(S.map(async j=>{try{const C=await l.getExportStatus(d,m,j.id);let A;if(C.status==="completed")try{A=await l.getDownloadUrl(d,m,j.id)}catch(V){console.error(`[useExportPolling] Failed to get download URL for ${j.id}:`,V)}return{id:j.id,status:C.status,progress:C.progress,completedChunks:C.completedChunks,completedAt:C.completedAt?new Date(C.completedAt):void 0,lastUpdatedAt:new Date,fileSize:C.fileSize,error:C.error,downloadUrl:A}}catch(C){return console.error(`[useExportPolling] Failed to poll export ${j.id}:`,C),null}})),{updateExport:b}=l.useExportStore.getState().actions;for(const j of N)j.status==="fulfilled"&&j.value&&b(j.value.id,j.value);const T=f();if(T.length>0&&!document.hidden){const j=T.reduce((A,V)=>V.startedAt<A?V.startedAt:A,T[0].startedAt),C=sa(j);i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{var A;(A=u.current)==null||A.call(u)},C)}else c.current=!1},[d,m,f]);return h.useEffect(()=>{u.current=g},[g]),h.useEffect(()=>{var y;f().length>0&&r&&!c.current&&(c.current=!0,(y=u.current)==null||y.call(u))},[n,r,f]),h.useEffect(()=>{var y;const p=f();r&&p.length>0&&!c.current&&(c.current=!0,(y=u.current)==null||y.call(u))},[r,f]),h.useEffect(()=>{!r&&i.current&&(clearTimeout(i.current),i.current=null,c.current=!1)},[r]),h.useEffect(()=>()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),{isPolling:c.current,isTabVisible:r,inProgressCount:f().length}}function ra(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(u=>u.activeExports),{addExport:r}=l.useExportActions(),o=h.useRef(!1),i=s==null?void 0:s.apiServiceUrl,c=t==null?void 0:t.accessToken;h.useEffect(()=>{if(o.current||!i||!c)return;(async()=>{try{const{exports:d}=await l.getExports(i,c,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const m of d){if(n.has(m.id))continue;const f=m.totalChunks?Math.round(m.completedChunks/m.totalChunks*100):0;let g;if(m.status==="completed")try{g=await l.getDownloadUrl(i,c,m.id)}catch(y){console.error(`[useExportRecovery] Failed to get download URL for ${m.id}:`,y)}const p={id:m.id,status:m.status,progress:f,title:aa(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}})()},[i,c,r,n])}function aa(t){return t.title?t.title:l.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function bn({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(l.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(oe.CircleX,{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"})}},i=l.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:l.formatFileSize(t.fileSize)})]})]}),i&&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:Ms.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(l.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),i&&e.jsxs("div",{children:[e.jsx(l.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:Ms.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function yn(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(S=>S.activeExports),{clearCompleted:r,removeExport:o,updateExport:i}=l.useExportActions(),[c,u]=h.useState(!1),[d,m]=h.useState(!1),f=Array.from(n.values()).sort((S,N)=>N.startedAt.getTime()-S.startedAt.getTime()),g=f.some(S=>S.status==="completed"||S.status==="failed"),p=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!(!S||!N)){u(!0);try{const b=Array.from(n.values());await Promise.all(b.map(async T=>{try{const j=await l.getExportStatus(S,N,T.id);let C;if(j.status==="completed")try{C=await l.getDownloadUrl(S,N,T.id)}catch(A){console.error(`Failed to get download URL for ${T.id}:`,A)}i(T.id,{status:j.status,progress:j.progress,completedChunks:j.completedChunks,completedAt:j.completedAt?new Date(j.completedAt):void 0,lastUpdatedAt:new Date,fileSize:j.fileSize,error:j.error,downloadUrl:C})}catch(j){console.error(`Failed to refresh export ${T.id}:`,j)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,i]),y=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!S||!N){r();return}m(!0);try{const b=f.filter(j=>j.status==="completed"||j.status==="failed"),T=await Promise.allSettled(b.map(async j=>(await l.cancelExport(S,N,j.id),j.id)));for(const j of T)j.status==="fulfilled"?o(j.value):console.error("Failed to delete export:",j.reason)}finally{m(!1)}},[f,s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,r,o]),I=h.useCallback(async S=>{const N=s==null?void 0:s.apiServiceUrl,b=t==null?void 0:t.accessToken;if(N&&b)try{await l.cancelExport(N,b,S),o(S);return}catch(T){console.error(`Failed to cancel export ${S}:`,T)}o(S)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,o]);return f.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Bs,{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(Bs,{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(l.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:y,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:f.map(S=>e.jsx(bn,{export:S,onRemove:I},S.id))})})]})}function oa({variant:t}){const s=l.useExportStore(d=>d.activeExports),n=l.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(l.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(yn,{})})]})}function ia(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 jn({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:o="manage"}){const i=o==="create",{forceClose:c,handleOpenChange:u,isCreateFlowActive:d,preventPassiveDismissDuringCreate:m,resolvedOpen:f,setIsCreateFlowActive:g}=oe.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:o==="create",dismissMode:r?"passive":"explicit-only"}),p=a.useDashboardStore(D=>D.dashboard),{setDashboardControlsModel:y}=a.useDashboardActions(),{participants:I}=l.useDashboardStructuralParticipants(a.getDashboardCards(p)),S=Array.from(new Map(I.flatMap(D=>D.fieldChoices.map(R=>{var _;return[R.value,{option:R,target:(_=D.fieldTargetMap)==null?void 0:_[R.value]}]}))).values()),N=Array.from(new Map(I.flatMap(D=>D.metricChoices.map(R=>{var _;return[R.value,{option:R,target:(_=D.metricTargetMap)==null?void 0:_[R.value]}]}))).values()),b=a.collectDashboardControlIds({...p||{},controls:[]}),T=l.buildDashboardStructuralParticipantIdsByControlId(p),j=(D,R,_)=>{y(D,R,ia(_))},C=h.useCallback(()=>{if(i){c();return}g(!1)},[i,c,g]),A=e.jsx(oe.ControlDefinitionListEditor,{scope:"dashboard",controls:p.controls||[],reservedControlIds:b,defaultValues:p.defaultControlValues||{},usageByControlId:l.buildDashboardControlUsageById(p),availableFieldChoices:S,availableMetricChoices:N,structuralParticipants:I,structuralParticipantIdsByControlId:T,initialCreateFlow:o==="create",onCreateFlowActiveChange:g,onCreateFlowComplete:C,onChange:j,emptyMessage:"No dashboard controls yet."}),V=d?"Add dashboard control":"Dashboard Controls",L=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."})]}),A]});return r?e.jsxs(a.Popover,{open:f,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:L})]}):e.jsx(l.Dialog,{open:f,onOpenChange:u,children:e.jsxs(l.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:m,onPointerDownOutside:m,children:[e.jsxs(l.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(l.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(l.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:A})]})})}const la=["enum","multi_enum","text","number","boolean","date"];function vn({open:t,onOpenChange:s,initialMode:n="manage"}){var L;const r=n==="create",{forceClose:o,handleOpenChange:i,isCreateFlowActive:c,preventPassiveDismissDuringCreate:u,resolvedOpen:d,setIsCreateFlowActive:m}=oe.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),f=a.useDashboardStore(D=>D.dashboard),g=a.useDashboardStore(D=>D.selectedSheetId),{setDashboardInputs:p}=a.useDashboardActions(),y=(L=f.sheets)==null?void 0:L.find(D=>D.id===g),I=(y==null?void 0:y.kind)==="document"&&!!y.document,S=h.useMemo(()=>I&&(y!=null&&y.document)?l.getDocumentSheetDashboardInputs(f,y.id):[],[f,I,y==null?void 0:y.document,y==null?void 0:y.id]),N=h.useMemo(()=>S.filter(D=>D.kind==="control"),[S]),b=h.useMemo(()=>N.map(D=>D.control),[N]),T=h.useMemo(()=>da(b),[b]),j=h.useMemo(()=>ca(f),[f]),C=h.useCallback(()=>{if(r){o();return}m(!1)},[r,o,m]),A=h.useCallback((D,R,_)=>{!I||!(y!=null&&y.document)||p(ma({allInputs:f.inputs||[],documentSheetId:y.id,currentDocumentInputs:S,nextControls:D,nextDefaultValues:R,change:_}))},[f.inputs,S,I,y,p]);if(!I||!(y!=null&&y.document))return null;const V=c?"Add document control":"Document Controls";return e.jsx(l.Dialog,{open:d,onOpenChange:i,children:e.jsxs(l.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs(l.DialogHeader,{className:c?"space-y-0":void 0,children:[e.jsx(l.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(l.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(oe.ControlDefinitionListEditor,{scope:"dashboard",controls:b,reservedControlIds:j,defaultValues:T,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:la,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:C,onChange:A,emptyMessage:"No document controls yet."})})]})})}function ca(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 ua(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 ma({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:o,change:i}){const c=new Map(r.map(p=>[p.id,ua(p,o)])),u=(i==null?void 0:i.type)==="rename"?{oldId:i.oldId,newId:i.newId}:null,d=new Set,m=[];for(const p of n){if(p.kind!=="control"){m.push(p);continue}const y=c.get(p.control.id)||((u==null?void 0:u.oldId)===p.control.id?c.get(u.newId):void 0);if(!y)continue;d.add(y.id);const I=l.createUniqueDashboardInputVariableNameFromName(y.id,[...t,...m].filter(N=>N.id!==p.id)),S=y.id===I?y:{...y,id:I};m.push({...p,label:S.label,variableName:I,requiredAtExecution:S.requiredAtExecution,control:S})}for(const p of c.values())d.has(p.id)||m.push(l.createDashboardControlInputFromControl({control:p,existingInputs:[...t,...m],sheetId:s}));const f=new Set(n.map(p=>p.id));return[...t.filter(p=>!f.has(p.id)),...m]}function Nn({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:o="default",className:i,primaryButtonClassName:c,secondaryButtonClassName:u,pickerContentClassName:d,settingsContentClassName:m}){const f=o==="toolbar",[g,p]=h.useState(!1),y=l.useSurfaceAppearance("interactive");return e.jsxs("div",{className:a.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",f?"h-8":"h-7",i),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(zr,{className:"h-3.5 w-3.5"}):e.jsx(l.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:y.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:y.contentStyle,children:r(()=>p(!1))})]})]})}function ha(){oe.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:i}=a.useEditorActions(),c=a.useEditorStore(d=>d.card.dataSource);return h.useEffect(()=>{var m,f;let d=r();if(!d){const g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(y=>y.id===t),p=(f=g==null?void 0:g.frames)==null?void 0:f[0];p&&(o(p.id),d=p)}if(d){const g=d.cards.find(p=>p.id===d.activeCardId);g&&i(g)}},[r,t,s,n,o,i]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function xa(){const t=a.useDashboardStore(u=>u.dashboard),s=a.useDashboardStore(u=>u.semanticExecutionPayload),n=a.useDashboardStore(u=>u.actions.addFilter),{hasEntities:r}=ha(),o=h.useMemo(()=>l.getGlobalDateFilterCoverage(t,s),[t,s]),c=!l.getGlobalDateFilter(t.filters)&&o.hasEligibleCards;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[c&&e.jsxs("div",{className:"border-b border-border/60 p-2",children:[e.jsxs("p",{className:"mb-1 flex items-center gap-1 px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(l.Sparkles,{className:"h-2.5 w-2.5"}),"Suggested"]}),e.jsxs("button",{type:"button",onClick:()=>n(l.createDefaultGlobalDateFilter()),title:`Eligible: ${o.eligibleCardCount} of ${o.totalCardCount} 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(l.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:"Global date filter"}),e.jsx("span",{className:"text-[11px] leading-[1.4] text-muted-foreground",children:"One date range, applied across every date-aware card on the dashboard."})]})]})]}),!r&&e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(l.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(l.FilterableFieldsPanel,{context:"filter"})})]})}const Os=!1;function pa({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const o=a.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:i}=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(Lt,{icon:l.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(Lt,{icon:a.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(Lt,{icon:l.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"}),Os,e.jsx(fa,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:c,onCheckedChange:u=>i({toolbarWrap:u===!0})}),Os]})]})}function Lt({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(l.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 ga({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:i}){var V;const[c,u]=h.useState(null),d=a.useDashboardStore(L=>L.dashboard),m=a.useDashboardStore(L=>L.selectedSheetId),f=a.useDashboardStore(L=>L.showFilters),g=l.useAssistantLayoutStore(L=>L.setPanelOpen),p=a.useDashboardStore(L=>L.actions),{setDocumentInspectorTab:y,setShowFilters:I}=p,S=(V=d.sheets)==null?void 0:V.find(L=>L.id===m),N=a.isDocumentSheet(S),b=h.useCallback(L=>{window.setTimeout(()=>{u(L)},0)},[]),T=h.useCallback(L=>{if(N&&m){L&&y(m,"inputs");return}L&&g("dashboard",!1),I(L)},[N,m,y,g,I]),j=h.useCallback(()=>{T(!0)},[T]),C=h.useCallback(()=>{b("create")},[b]),A=h.useCallback(()=>{b("manage")},[b]);return e.jsxs(e.Fragment,{children:[e.jsx(Nn,{showFilters:N?!1:f,onShowFiltersChange:T,pickerContent:e.jsx(xa,{}),settingsContent:L=>e.jsx(pa,{onAddFilter:j,onAddControl:C,onManageControls:A,onDismiss:L}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:i}),c?N?e.jsx(vn,{open:!0,onOpenChange:L=>{L||u(null)},initialMode:c}):e.jsx(jn,{open:!0,onOpenChange:L=>{L||u(null)},showTrigger:!1,initialMode:c}):null]})}class ut extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function wn(t,s){return`${t.replace(/\/$/,"")}${s}`}function ie(t){return encodeURIComponent(t)}function mt(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 ba(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 Cn(t){if(!t||typeof t!="object")return null;const s=t;return typeof s.error=="string"?s.error:null}async function le(t,s,n,r){const o=await fetch(wn(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)||{}}}),i=await o.json().catch(()=>({}));if(!o.ok)throw new ut(Cn(i)||"Briefings API request failed",o.status,i);return i}async function Sn(t,s,n,r){const o=await fetch(wn(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){const i=await ba(o);throw new ut(Cn(i)||"Briefing artifact request failed",o.status,i)}return{kind:r,content:await o.text(),contentType:o.headers.get("content-type")??"text/plain",filename:ya(o.headers.get("content-disposition"))}}function ya(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function kn(t,s,n){return le(t,s,`/v1/briefings${mt({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 ja(t,s,n){return le(t,s,`/v1/briefings/tenant-summaries${mt({status:n==null?void 0:n.status})}`)}async function Wt(t,s,n){return le(t,s,`/v1/briefings/${ie(n)}`)}async function Dn(t,s,n){return le(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function ht(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Gt(t,s,n){return ht(t,s,n,{status:"PAUSED"})}async function Xt(t,s,n){return ht(t,s,n,{status:"ACTIVE"})}async function Jt(t,s,n){return le(t,s,`/v1/briefings/${ie(n)}`,{method:"DELETE"})}async function Qt(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs`,{method:"POST",body:JSON.stringify(r)})}async function En(t,s,n){return le(t,s,"/v1/briefings/preview-plan",{method:"POST",body:JSON.stringify({draft:n})})}async function In(t,s,n){return le(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function An(t,s,n){return(await le(t,s,`/v1/briefings/preview-runs/${ie(n)}`)).previewRun}async function va(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs${mt({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function Yt(t,s,n,r){return(await le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`)).run}async function Tn(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Ln(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`,{method:"DELETE"})}async function Na(t,s,n,r,o){return Sn(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}/artifact${mt({kind:o})}`,o)}async function wa(t,s,n,r){return Sn(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}/evidence`,"evidence")}async function Fn(t,s,n){var o;const r=await le(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 ut(r.error||"Polish returned no result",502,r);return r.result.polished}const Ca={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},Sa={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function Ne(t){return Z(t)}function Us(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 Zt(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 ka(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 Rn(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 Vn(n)}}}function Da(t,s){return Rn(t).includes(s)?{...Ne(t),format:s,settings:Bn(t.settings,s)}:Ne(t)}function Ea(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...Ne(t),settings:n}}function Pn(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),i=o.find(d=>d.id===t.selectedSheetId)??o[0];i&&r.push({key:`dashboard_sheet:${s}:${i.id}`,kind:"dashboard_sheet",title:`${Rt(i)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:i.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:`${Rt(d)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:d.id,formats:["pdf"],defaultFormat:"pdf"});if(i)for(const d of On(i)){if(d.card.type==="text")continue;const m=Vn(d.card.type);r.push({key:`card:${s}:${d.card.id}`,kind:"card",title:d.card.title||"Untitled card",detail:`${Rt(i)} · ${d.card.type}`,dashboardId:s,sheetId:i.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:l.getDefaultExportFormat(d.card.type)})}return r}function _t(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Ia({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:Ft(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:Ft(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:Ft(s.cardId),format:n,title:s.title,settings:r}}}function $s(t){const s=Pn(t),n=s.find(i=>i.kind==="dashboard_sheet"),o=s.find(i=>i.kind==="dashboard")??n;return o?[_t({option:o,runtime:t.runtime})]:[]}function Ia(t){const s={...Bn(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=Z(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=Z(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=Z(t.option.tablePreferences))),Aa({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Pa(s.filterValues)),s}function Aa(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Ta({settings:s,option:n,runtime:r});return}const o=n.kind==="dashboard"?"all":"current",i=n.kind==="dashboard"?r.selectedSheetId:n.sheetId,c=l.buildDashboardExecutionSnapshot({dashboard:r.dashboard||void 0,filterValues:r.filterValues,selectedSheetId:i,sheetSelection:o,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});s.sheetFilterValues=Z(c.filterValues),s.filterValues=Z(c.filterValues),s.controlValues=Z(c.controlValues),r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions));const u=La({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&o==="all"?void 0:i,sheetSelection:o});u&&(s.dashboardInputExecutionSnapshot=Z(u))}function Ta(t){var m,f,g;const{settings:s,option:n,runtime:r}=t,o=n.cardId,i=l.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=Z(i),!o){s.filterValues=Z(i),s.controlValues=Z(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions));return}const c=((m=r.inlineFilterValuesMap)==null?void 0:m[o])||[];c.length>0&&(s.inlineFilterValues=Z(c));const u=l.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:o,interactionStates:r.interactionStates||{},currentDashboardId:(f=r.dashboard)==null?void 0:f.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=Z(u.queryContext.cardFilterValues),s.controlValues=Z(u.queryContext.controlValues),s.controlDefinitions=Z(u.queryContext.controlDefinitions),s.cardControlDefinitions=Z(u.queryContext.cardControlDefinitions),s.controlBindings=Z(u.queryContext.controlBindings)):(s.filterValues=Z(i),s.controlValues={...r.controlValues||{},...((g=r.cardControlValuesMap)==null?void 0:g[o])||{}},r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions)));const d=Fa({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:c,controlValues:s.controlValues});d&&(s.dashboardInputExecutionSnapshot=Z(d))}function La(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(),i=Mn();if(s.kind==="document_sheet"&&s.sheetId)return l.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:i}).snapshot;const c=t.sheetSelection==="all"?a.getDashboardSheets(r.sheets).map(d=>d.id):t.selectedSheetId?[t.selectedSheetId]:[];if(c.length!==0)return l.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:i}).snapshot}function Fa(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=Ra(r,s.sheetId,s.cardId),i=t.inlineFilterValues!==void 0?{...n.inlineFilterValuesMap||{},[s.cardId]:t.inlineFilterValues}:n.inlineFilterValuesMap,c=t.filterValues!==void 0?l.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 l.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:i,cardControlValuesMap:n.cardControlValuesMap},generatedAt:new Date().toISOString(),timezone:Mn()}).snapshot}function Ra(t,s,n){const r=t.sheets||[],o=s?r.filter(i=>i.id===s):r;for(const i of o)for(const c of On(i))if(c.card.id===n)return{sheet:i,card:c.card}}function Mn(){return typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Pa(t){if(!Array.isArray(t))return"";const s=t.filter(n=>!!n&&typeof n=="object"&&typeof n.name=="string");return l.formatFilterLine(s)}function Bn(t,s){return s==="csv"?{...Sa,...t}:{...Ca,...t}}function Vn(t){return t?l.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function On(t){const s=[],n=new Set,r=(o,i)=>{!(o!=null&&o.id)||n.has(o.id)||(n.add(o.id),s.push({card:o,frame:i}))};for(const o of t.cards||[])r(o);for(const o of t.frames||[])for(const i of o.cards||[])r(i,o);return s}function Ft(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function Rt(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function Z(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Un=["markdown"],Ma={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Un],includeEvidence:!0,includeSql:!0},schedule:{enabled:!1,scheduleExpr:"",timezone:"UTC",status:"ACTIVE"},delivery:{enabled:!1,recipients:[],channels:[],subject:"",message:""},limits:{}};function $n(t){const s=t.trim();return s.length>0?s:void 0}function Ba(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ne),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 Va(t){return t.type==="generated_analysis"?t.instruction:t.type==="custom_message"?t.message:""}function _n(t,s){return t.type==="custom_message"?{type:"custom_message",message:s}:t.type==="none"?{type:"none"}:{type:"generated_analysis",instruction:s}}function es(t){return _n(t.body,t.instruction.trim())}function zn(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 qn(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 Hn(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 Kn(t){return t.recipients.length===0&&t.channels.length===0?null:{recipients:t.recipients.map(s=>({...s})),channels:[...t.channels],channelConfigs:Hn(t.channelConfigs,t.channels)}}function Oa(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Un],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 Ua(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function $a(t){return{enabled:!0,recipients:(t==null?void 0:t.recipients.map(s=>({...s})))??[],channels:t!=null&&t.channels?[...t.channels]:[],subject:"",message:"",channelConfigs:Hn(t==null?void 0:t.channelConfigs,(t==null?void 0:t.channels)??[])}}function _a(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function za(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function Pt(t,s,n,r,o){_a(n,r,o)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${o}`})}function Wn(t){return at(Ma,t??{})}function at(t,s){var c,u,d,m;const n=s.instruction??(s.body?Va(s.body):t.instruction),r=_n(s.body?{...s.body}:{...t.body},n),o=(c=s.delivery)!=null&&c.channels?[...s.delivery.channels]:[...t.delivery.channels],i=((u=s.delivery)==null?void 0:u.channelConfigs)??t.delivery.channelConfigs;return{...Ba(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(Ne):t.attachments.map(Ne),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(f=>({...f})):t.delivery.recipients.map(f=>({...f})),channels:o,channelConfigs:i},limits:{...t.limits,...s.limits}}}function Ue(t){return{name:t.name,description:t.description??"",instruction:Ua(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ne),output:Oa(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:$a(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function zt(t){return{name:t.name.trim(),description:$n(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:es(t),attachments:t.attachments.map(Ne),presentation:zn(t.output),limits:qn(t.limits),deliveryConfig:Kn(t.delivery)}}function Gn(t){return{name:t.name.trim(),description:$n(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:es(t),attachments:t.attachments.map(Ne),presentation:zn(t.output),limits:qn(t.limits),deliveryConfig:Kn(t.delivery)}}function qt(t){var r,o,i,c,u;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=es(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,f)=>{m.type==="email"&&!za(m.address)&&s.push({field:`delivery.recipients.${f}.address`,message:"Email recipient address is invalid"})}),t.delivery.channels.includes("WEBHOOK")){const m=(r=t.delivery.channelConfigs)==null?void 0:r.WEBHOOK;(i=(o=m==null?void 0:m.webhookConfig)==null?void 0:o.url)!=null&&i.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 Pt(s,"maxToolCalls",t.limits.maxToolCalls,1,100),Pt(s,"maxRows",t.limits.maxRows,1,1e5),Pt(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const Qe="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function qa({attachment:t,open:s,onOpenChange:n,onChange:r,children:o}){const i=Rn(t),c=t.settings||{},u=t.format==="csv",d=m=>{r(Ea(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(Qe,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:Zt(t)})]}),i.length>1?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Qe,"mb-1 block"),children:"Format"}),e.jsxs(a.Select,{value:t.format,onValueChange:m=>r(Da(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:i.map(m=>e.jsx(a.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(Ka,{settings:c,onChange:d}):e.jsx(Ha,{settings:c,onChange:d})]})]})}function Ha({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(Qe,"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(Qe,"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(ot,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(ot,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function Ka({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Qe,"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(ot,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(ot,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function ot({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-foreground/80",children:[e.jsx(l.Checkbox,{checked:s,onCheckedChange:r=>n(r===!0)}),e.jsx("span",{children:t})]})}function Wa({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(l.Paperclip,{className:"h-3 w-3"}),o?"Attach":null]}),t.map((i,c)=>e.jsx(Ga,{attachment:i,disabled:r,onUpdate:u=>{const d=[...t];d[c]=u,s(d)},onRemove:()=>s(t.filter((u,d)=>d!==c))},`${i.type}:${c}:${Zt(i)}`)),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(l.Plus,{className:"h-3 w-3"}),"Add"]})]})}function Ga({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[o,i]=h.useState(!1),c=Zt(t),u=ka(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(qa,{attachment:t,open:o,onOpenChange:i,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(Xa,{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 Xa({format:t,className:s}){const n=t==="csv"?l.FileSpreadsheet:l.FileText;return e.jsx(n,{className:a.cn(s)})}const Ja="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Qa({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:o,runtime:i,selectedAttachments:c,onSubmit:u}){const d=h.useMemo(()=>Pn({source:n,dashboard:r,selectedSheetId:o}),[n,r,o]),[m,f]=h.useState([]);h.useEffect(()=>{if(!t)return;const A=[];for(const V of c){const L=Us(V),D=d.find(R=>R.formats.some(_=>{const M=_t({option:R,format:_,runtime:i});return Us(M)===L}));D&&A.push({optionKey:D.key,format:V.format??D.defaultFormat})}f(A)},[t,d,c,i]);const g=h.useMemo(()=>new Set(m.map(A=>A.optionKey)),[m]),p=h.useMemo(()=>{const A={};for(const V of m)A[V.optionKey]=V.format;return A},[m]),y=(A,V)=>{f(L=>L.some(R=>R.optionKey===A)?L.filter(R=>R.optionKey!==A):[...L,{optionKey:A,format:V}])},I=(A,V)=>{f(L=>L.map(D=>D.optionKey===A?{...D,format:V}:D))},S=()=>{const A=[];for(const V of m){const L=d.find(D=>D.key===V.optionKey);L&&A.push(_t({option:L,format:V.format,runtime:i}))}u(A),s(!1)},N=()=>s(!1),b=h.useMemo(()=>d.filter(A=>A.kind==="dashboard"||A.kind==="dashboard_sheet"),[d]),T=h.useMemo(()=>d.filter(A=>A.kind==="document_sheet"),[d]),j=h.useMemo(()=>d.filter(A=>A.kind==="card"),[d]),C=m.length;return e.jsx(l.Dialog,{open:t,onOpenChange:s,children:e.jsxs(l.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(l.DialogHeader,{className:"border-b border-border px-4 py-3 text-left",children:[e.jsx(l.DialogTitle,{className:"text-[14px] font-semibold leading-5",children:"Add attachments"}),e.jsx(l.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(Mt,{label:"Dashboard",options:b,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I}),e.jsx(Mt,{label:"Paginated reports",options:T,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I,emptyText:"No paginated report sheets are available."}),e.jsx(Mt,{label:"Current sheet cards",options:j,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I,emptyText:"No exportable cards are available on the current dashboard sheet."})]})}),e.jsxs(l.DialogFooter,{className:"flex flex-row items-center justify-between gap-2 border-t border-border px-4 py-3 sm:justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:C===0?"Nothing selected":`${C} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Button,{type:"button",variant:"outline",size:"xs",onClick:N,children:"Cancel"}),e.jsx(a.Button,{type:"button",size:"xs",onClick:S,disabled:n.type!=="dashboard",children:C>0?`Add ${C} ${C===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function Mt({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:o,onFormatChange:i,emptyText:c}){return e.jsxs("section",{children:[e.jsx("div",{className:a.cn(Ja,"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(Ya,{selected:d}),e.jsx(Za,{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:f=>i(u.key,f),children:[e.jsx(a.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:f=>f.stopPropagation(),children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:u.formats.map(f=>e.jsx(a.SelectItem,{value:f,children:f.toUpperCase()},f))})]}):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 Ya({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 Za({kind:t,format:s,cardType:n,className:r}){const o=s==="csv"?l.FileSpreadsheet:t==="dashboard"?l.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?oe.Rows3:a.ChartColumn:l.FileText;return e.jsx(o,{className:r})}const eo=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,to=250;function Ge(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 so(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function no(t){return t.type==="group"?t.groupId:null}function Xe(t){return(t==null?void 0:t.trim().toLowerCase())||null}function _s(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function zs(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function qs({value:t,onChange:s,className:n,disabled:r=!1,prefix:o,placeholder:i}){const c=h.useRef(null),[u,d]=h.useState(!1),[m,f]=h.useState(""),[g,p]=h.useState(0),[y,I]=h.useState(()=>new Map),[S,N]=h.useState(()=>new Map),[b,T]=h.useState("people"),j=l.useDebounce(m,to),{currentUser:C}=l.useCurrentUserInfo(),A=(C==null?void 0:C.type)==="tenant",{users:V,isLoading:L}=l.useUnifiedUsers({search:j,active:!0,type:A?"tenant":"all",tenantId:A?C.tenantId:void 0,limit:25}),{groups:D,isLoading:R}=l.useGroups({search:j,type:A?"TENANT_GROUP":"all",tenantId:A?C.tenantId:void 0,limit:25}),_=h.useMemo(()=>new Set(t.map(Ge)),[t]),M=h.useMemo(()=>new Set(t.map(so).filter(k=>!!k)),[t]),z=h.useMemo(()=>new Set(t.map(no).filter(k=>!!k)),[t]),U=h.useMemo(()=>{const k=new Map(y);return V.forEach(P=>{k.set(P.id,_s(P))}),C!=null&&C.id&&k.set(C.id,{kind:"user",id:C.id,name:C.name||C.email||"User",email:C.email||"",type:C.type}),k},[y,V,C]),B=h.useMemo(()=>{const k=new Set;return t.forEach(P=>{var xe;if(P.type==="email"){const Oe=Xe(P.address);Oe&&k.add(Oe);return}if(P.type==="group")return;const se=P.type==="tenant_user"?P.tenantUserId:P.userId,ce=Xe((xe=U.get(se))==null?void 0:xe.email);ce&&k.add(ce)}),k},[U,t]),W=h.useMemo(()=>{const k=new Map(S);return D.forEach(P=>{k.set(P.id,zs(P))}),k},[S,D]),E=h.useMemo(()=>V.filter(k=>{if(M.has(k.id))return!1;const P=Xe(k.email);return P&&B.has(P)?!1:A?k.type==="tenant"&&k.tenantId===(C==null?void 0:C.tenantId):!0}).map(_s),[V,M,B,A,C==null?void 0:C.tenantId]),me=h.useMemo(()=>E.filter(k=>k.type==="organization"),[E]),w=h.useMemo(()=>E.filter(k=>k.type==="tenant"),[E]),q=h.useMemo(()=>D.filter(k=>z.has(k.id)?!1:(C==null?void 0:C.type)==="tenant"?k.type==="TENANT_GROUP"&&k.tenantId===C.tenantId:!0).map(zs),[D,z,C==null?void 0:C.type,C==null?void 0:C.tenantId]),te=h.useMemo(()=>A?[{key:"people",label:"People",count:w.length},{key:"groups",label:"Groups",count:q.length}]:[{key:"people",label:"People",count:me.length},{key:"tenant_users",label:"Tenant users",count:w.length},{key:"groups",label:"Groups",count:q.length}],[q.length,A,me.length,w.length]),Q=h.useMemo(()=>b==="groups"?[]:b==="tenant_users"||A?w:me,[b,A,me,w]),be=h.useMemo(()=>b==="groups"?q:[],[b,q]),pe=h.useMemo(()=>[...Q,...be],[Q,be]),ye=pe.length===0?0:Math.min(g,pe.length-1),O=m.trim(),Le=eo.test(O),we=Xe(O),je=we?B.has(we):!1,Fe=L||R,H=k=>{_.has(Ge(k))||(s([...t,k]),f(""),p(0))},fe=k=>{s(t.filter(P=>Ge(P)!==k))},Ae=()=>{!Le||je||H({type:"email",address:O})},$=k=>{const P=Xe(k.email);P&&B.has(P)||(I(se=>{const ce=new Map(se);return ce.set(k.id,k),ce}),H(k.type==="tenant"?{type:"tenant_user",tenantUserId:k.id}:{type:"user",userId:k.id}))},Y=k=>{N(P=>{const se=new Map(P);return se.set(k.id,k),se}),H({type:"group",groupId:k.id})},_e=k=>{if(k.key==="Enter"){if(k.preventDefault(),Le&&!je){Ae();return}const P=pe[ye];if((P==null?void 0:P.kind)==="user"){$(P);return}if((P==null?void 0:P.kind)==="group"){Y(P);return}}else if(k.key==="ArrowDown")k.preventDefault(),p(P=>Math.min(P+1,Math.max(pe.length-1,0)));else if(k.key==="ArrowUp")k.preventDefault(),p(P=>Math.max(P-1,0));else if(k.key==="Escape")d(!1);else if(k.key==="Backspace"&&m.length===0){const P=t[t.length-1];P&&fe(Ge(P))}},rs=t.map(k=>{const P=Ge(k);if(k.type==="email")return{key:P,label:k.name||k.address,icon:e.jsx(l.AtSign,{className:"h-3 w-3"}),onRemove:()=>fe(P)};if(k.type==="group"){const xe=W.get(k.groupId);return{key:P,label:(xe==null?void 0:xe.name)||"Group",icon:e.jsx(gn,{className:"h-3 w-3"}),onRemove:()=>fe(P)}}const se=k.type==="tenant_user"?k.tenantUserId:k.userId,ce=U.get(se);return{key:P,label:(ce==null?void 0:ce.name)||(ce==null?void 0:ce.email)||"User",icon:e.jsx(l.User,{className:"h-3 w-3"}),onRemove:()=>fe(P)}});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 k;r||((k=c.current)==null||k.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,rs.map(k=>e.jsx(ro,{icon:k.icon,label:k.label,onRemove:k.onRemove},k.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:i??(t.length>0?"Add more...":"Add people, emails, or groups"),onChange:k=>{f(k.target.value),p(0),d(!0)},onFocus:()=>d(!0),onKeyDown:_e})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:k=>k.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(ao,{activeIndex:ye,activeFilter:b,emailAlreadyAdded:je,filters:te,groupSuggestions:be,loading:Fe,onAddEmail:Ae,onFilterChange:k=>{T(k),p(0)},onGroupClick:Y,onUserClick:$,orderedSuggestions:pe,query:O,queryIsEmail:Le,userSuggestions:Q,viewerType:C==null?void 0:C.type})})]})})}function ro({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 ao({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:o,loading:i,onAddEmail:c,onFilterChange:u,onGroupClick:d,onUserClick:m,orderedSuggestions:f,query:g,queryIsEmail:p,userSuggestions:y,viewerType:I}){const S=!i&&f.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(N=>e.jsxs("button",{type:"button",onClick:()=>u(N.key),className:a.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===N.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:N.label}),e.jsx("span",{className:a.cn("tabular-nums",s===N.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:N.count})]},N.key))}),i?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,y.length>0?e.jsx(Hs,{heading:"People",children:y.map(N=>{var T;const b=f.indexOf(N);return e.jsx(Ks,{active:b===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:(T=(N.name||N.email||"?")[0])==null?void 0:T.toUpperCase()}),detail:N.name?N.email:void 0,tag:N.type==="organization"?"Org user":"Tenant user",viewerType:I,title:N.name||N.email,onClick:()=>m(N)},N.id)})}):null,o.length>0?e.jsx(Hs,{heading:"Groups",children:o.map(N=>{const b=f.indexOf(N);return e.jsx(Ks,{active:b===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(gn,{className:"h-3 w-3"})}),detail:N.memberCount!==void 0?`${N.memberCount} member${N.memberCount===1?"":"s"}`:N.description??void 0,tag:N.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:I,title:N.name,onClick:()=>d(N)},N.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(xn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13px] text-foreground",children:["Send to ",e.jsx("span",{className:"font-medium",children:g})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Add as external email"})]}),e.jsx("span",{className:"ml-auto shrink-0 rounded-control border border-border bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"Enter"})]})}):null,S?e.jsx("div",{className:"px-2.5 py-6 text-center text-[12px] text-muted-foreground",children:g?"No people or groups match. Enter a valid email to add an external recipient.":"Pick a category above or type to search people, groups, or external emails."}):null]})}function Hs({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 Ks({active:t,avatar:s,detail:n,onClick:r,tag:o,title:i,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:i}),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 it(t){return t==="SUCCESS"||t==="FAILED"}function lt(t){return t==="QUEUED"||t==="RUNNING"}function Ht({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d}){const[m,f]=h.useState(null),[g,p]=h.useState("idle"),y=h.useRef(null),I=h.useRef({fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d});h.useEffect(()=>{I.current={fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d}},[o,u,i,c,d]);const S=h.useCallback(()=>{f(null),p("idle")},[]),N=h.useCallback(()=>{y.current=null},[]),b=h.useCallback(j=>{var C,A;if(I.current.onRun(j),it(j.status)){y.current=j.id,f(null),p("terminal"),(A=(C=I.current).onTerminalRun)==null||A.call(C,j);return}if(lt(j.status)){y.current=null,f(j.id),p("polling");return}f(null),p("idle")},[]),T=h.useCallback(j=>{y.current!==j&&(f(j),p("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(y.current===m){f(null),p("terminal");return}let j=!1,C=!1,A=null;const V=Date.now(),L=async()=>{var D,R,_,M,z,U;if(!(j||C)){if(Date.now()-V>r){f(B=>B===m?null:B),p("timed_out"),(R=(D=I.current).onTimeout)==null||R.call(D,m);return}C=!0;try{const B=await I.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(j)return;if(I.current.onRun(B),it(B.status)){y.current=B.id,f(W=>W===B.id?null:W),p("terminal"),(M=(_=I.current).onTerminalRun)==null||M.call(_,B);return}if(!lt(B.status)){f(W=>W===B.id?null:W),p("idle");return}A=window.setTimeout(L,n)}catch(B){j||(p("error"),(U=(z=I.current).onError)==null||U.call(z,B))}finally{C=!1}}};return p("polling"),L(),()=>{j=!0,A&&window.clearTimeout(A)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&g==="polling",resetTerminalRun:N,startRun:b,startRunId:T,status:g,stop:S}}function Ws({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 oo({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(l.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(Bt,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:i=>r("evidence",i)}),e.jsx(Bt,{label:"Include SQL in evidence",description:"Show the SQL the briefing ran. Useful for debugging or for a technical audience.",checked:s,onChange:i=>r("sql",i)}),e.jsx(Bt,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:i=>r("html",i)})]})]})]})}function Bt({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 Kt=`Tell me what changed in the business and what is driving it.
56
+ */const $t=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 Kr({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:o=!1,destinationMode:i="both",onConfirm:c}){const[u,d]=h.useState(n&&r?`Copy of ${r}`:r||""),[m,f]=h.useState("");h.useEffect(()=>{t&&(d(n&&r?`Copy of ${r}`:r||""),f(""))},[t,n,r]);const g=!!u.trim(),p=i==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:i==="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"},y=()=>{!g||o||c({name:u.trim(),description:m.trim()||void 0,saveToLibrary:p.saveToLibrary,saveToCurrentDashboard:p.saveToCurrentDashboard})};return e.jsx(l.Dialog,{open:t,onOpenChange:s,children:e.jsxs(l.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(l.DialogHeader,{children:[e.jsxs(l.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),p.badgeType!=="local"&&e.jsx(oe.VisualBadge,{type:p.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(l.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:I=>d(I.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(l.Textarea,{id:"description",value:m,onChange:I=>f(I.target.value),placeholder:"Enter visual description",rows:3,disabled:o})]})]}),e.jsxs(l.DialogFooter,{children:[e.jsx(a.Button,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancel"}),e.jsxs(a.Button,{onClick:y,disabled:!g||o,children:[o&&e.jsx(a.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p.actionLabel]})]})]})})}function Wr(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[o,i]=h.useState(null),[c,u]=h.useState(null),d=a.useEditorStore(D=>D.frame),m=a.useEditorStore(D=>D.card),f=l.useSelectedVisual(),g=a.useDashboardStore(D=>D.selectedSheetId),p=a.useDashboardStore(D=>D.dashboard),y=a.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:I}=xn.useVisualUtils(),{selectVisual:S}=l.useManagementActions(),{addFrame:N,setSelectedFrameId:b,setIsVisualEditing:T}=a.useDashboardActions(),j=l.useResolveExistingFrameSemanticExecutionPayload(),C=!!(d!=null&&d.visualId),A=(()=>{var D,R;return((D=d==null?void 0:d.cards)==null?void 0:D.length)===1&&((R=d.cards[0])!=null&&R.title)?d.cards[0].title:f!=null&&f.title?f.title:(m==null?void 0:m.title)||"Untitled Visual"})(),V=l.useCreateVisualWithFrame(D=>{D!=null&&D.id&&(S(D),n&&o&&c&&g&&(async()=>{try{const R={...o,id:a.v4(),visualId:D.id};N(g,R,{position:"end",semanticExecutionPayload:c}),b(R.id),r(!1),i(null),u(null),T(!1)}catch(R){console.error("Failed to promote semantic metadata for saved visual:",R),l.ue.error(R instanceof Error?R.message:"Failed to prepare semantic metadata for the saved visual")}})(),y(!0),s(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:s,handleSaveAs:async D=>{if(!g){l.ue.error("No sheet selected");return}const R=I(),_=a.getDynamicFrameSaveIssue(R);if(_){l.ue.error(_);return}const z=R.cards.length===1?{...R,cards:R.cards.map(U=>({...U,title:D.name}))}:R;if(D.saveToLibrary){let U=null;if(D.saveToCurrentDashboard)try{U=await j(z,{previousFrame:l.findDashboardFrameById(p,z.id)})}catch(W){console.error("Failed to prepare semantic metadata before saving visual:",W),l.ue.error(W instanceof Error?W.message:"Failed to prepare semantic metadata for the saved visual");return}r(D.saveToCurrentDashboard),i(z),u(U);const B={title:D.name,description:D.description,frameObject:z,isPrivate:!1};V.mutate(B)}else if(D.saveToCurrentDashboard){const U={...z,id:a.v4(),visualId:void 0};try{const B=await j(z,{previousFrame:l.findDashboardFrameById(p,z.id)});N(g,U,{position:"end",semanticExecutionPayload:B}),b(U.id),l.ue.success("Visual saved to dashboard"),s(!1),T(!1)}catch(B){console.error("Failed to save visual to dashboard:",B),l.ue.error(B instanceof Error?B.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:C,currentVisualName:A,isSaving:V.isPending}}function Gr(t={}){const s=a.useEditorStore(M=>M.frame),n=a.useEditorStore(M=>M.editorContext),r=l.useManagementStore(M=>M.selectedVisual),o=a.useDashboardStore(M=>M.selectedFrameId),i=a.useDashboardStore(M=>M.selectedSheetId),c=a.useDashboardStore(M=>M.dashboard),{setIsVisualEditing:u,updateFrame:d}=a.useDashboardActions(),[m,f]=h.useState(!1),[g,p]=h.useState("both"),y=l.useResolveExistingFrameSemanticExecutionPayload(),I=(n==null?void 0:n.type)==="documentSection",S=!!(s!=null&&s.visualId||r!=null&&r.id),N=!!(s!=null&&s.visualId&&o),b=S&&!N,{saveAsDialogOpen:T,setSaveAsDialogOpen:j,handleSaveAs:C,isLibraryVisual:A,currentVisualName:V,isSaving:L}=Wr(),{getUpdatedFrame:D}=xn.useVisualUtils();if(I)return e.jsxs(e.Fragment,{children:[e.jsx(oe.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(oe.EditorCancelButton,{})]});const R=async()=>{if(!i){l.ue.error("No sheet selected");return}if(m)return;f(!0);const M=D(),z=a.getDynamicFrameSaveIssue(M);if(z){f(!1),l.ue.error(z);return}const U={...M,visualId:void 0},B=l.findDashboardFrameById(c,U.id);try{const W=await y(U,{previousFrame:B});d(i,U,{semanticExecutionPayload:W})}catch(W){console.error("Failed to apply local semantic metadata:",W),f(!1),l.ue.error(W instanceof Error?W.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{f(!1),l.ue.success("Changes applied. Visual is now local to this dashboard"),u(!1)},300)},_=M=>{p(M),j(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(oe.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&b&&e.jsx(oe.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&N&&e.jsx(oe.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(l.DropdownMenu,{modal:!1,children:[e.jsx(l.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:L||m,children:e.jsx(a.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(l.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[N&&e.jsxs(e.Fragment,{children:[e.jsxs(l.DropdownMenuItem,{onClick:R,disabled:m,children:[e.jsx(a.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(l.DropdownMenuSeparator,{})]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("local"),disabled:L,children:[e.jsx(l.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("library"),disabled:L,children:[e.jsx(oe.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(l.DropdownMenuItem,{onClick:()=>_("both"),disabled:L,children:[e.jsx(oe.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(oe.EditorCancelButton,{}),e.jsx(Kr,{open:T,onOpenChange:M=>{L||j(M)},isLibraryVisual:A,currentVisualName:V,isSaving:L,destinationMode:g,onConfirm:C})]})}function Xr({className:t}){const s=a.useEditorStore(m=>m.isDevMode),n=a.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=a.useEditorActions(),{config:o}=h.useContext(l.SemaphorContext).tokenProps,i=(o==null?void 0:o.showAdvancedMode)!==!1;if(!n||!i)return null;const c=s?a.SlidersHorizontal:l.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 Jr({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:o,title:i="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 f=g=>{!g&&o||s(g)};return e.jsx(l.AlertDialog,{open:t,onOpenChange:f,children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:i}),e.jsx(l.AlertDialogDescription,{children:c})]}),e.jsxs(l.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(l.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 Qr=1e4,Yr=15e3,Zr=3e4,ea=3e4,ta=12e4,Os=2*60*60*1e3;function sa(t){const s=Date.now()-t.getTime();return s<ea?Qr:s<ta?Yr:Zr}function na(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(p=>p.activeExports),[r,o]=h.useState(typeof document<"u"?!document.hidden:!0),i=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,f=h.useCallback(()=>{const p=l.useExportStore.getState().activeExports;return Array.from(p.values()).filter(y=>l.isExportInProgress(y.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=f();if(p.length===0){c.current=!1;return}const y=Date.now(),I=p.filter(j=>y-j.startedAt.getTime()>Os);if(I.length>0){const{updateExport:j}=l.useExportStore.getState().actions;for(const C of I)j(C.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const S=p.filter(j=>y-j.startedAt.getTime()<=Os);if(S.length===0){c.current=!1;return}const N=await Promise.allSettled(S.map(async j=>{try{const C=await l.getExportStatus(d,m,j.id);let A;if(C.status==="completed")try{A=await l.getDownloadUrl(d,m,j.id)}catch(V){console.error(`[useExportPolling] Failed to get download URL for ${j.id}:`,V)}return{id:j.id,status:C.status,progress:C.progress,completedChunks:C.completedChunks,completedAt:C.completedAt?new Date(C.completedAt):void 0,lastUpdatedAt:new Date,fileSize:C.fileSize,error:C.error,downloadUrl:A}}catch(C){return console.error(`[useExportPolling] Failed to poll export ${j.id}:`,C),null}})),{updateExport:b}=l.useExportStore.getState().actions;for(const j of N)j.status==="fulfilled"&&j.value&&b(j.value.id,j.value);const T=f();if(T.length>0&&!document.hidden){const j=T.reduce((A,V)=>V.startedAt<A?V.startedAt:A,T[0].startedAt),C=sa(j);i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{var A;(A=u.current)==null||A.call(u)},C)}else c.current=!1},[d,m,f]);return h.useEffect(()=>{u.current=g},[g]),h.useEffect(()=>{var y;f().length>0&&r&&!c.current&&(c.current=!0,(y=u.current)==null||y.call(u))},[n,r,f]),h.useEffect(()=>{var y;const p=f();r&&p.length>0&&!c.current&&(c.current=!0,(y=u.current)==null||y.call(u))},[r,f]),h.useEffect(()=>{!r&&i.current&&(clearTimeout(i.current),i.current=null,c.current=!1)},[r]),h.useEffect(()=>()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),{isPolling:c.current,isTabVisible:r,inProgressCount:f().length}}function ra(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(u=>u.activeExports),{addExport:r}=l.useExportActions(),o=h.useRef(!1),i=s==null?void 0:s.apiServiceUrl,c=t==null?void 0:t.accessToken;h.useEffect(()=>{if(o.current||!i||!c)return;(async()=>{try{const{exports:d}=await l.getExports(i,c,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const m of d){if(n.has(m.id))continue;const f=m.totalChunks?Math.round(m.completedChunks/m.totalChunks*100):0;let g;if(m.status==="completed")try{g=await l.getDownloadUrl(i,c,m.id)}catch(y){console.error(`[useExportRecovery] Failed to get download URL for ${m.id}:`,y)}const p={id:m.id,status:m.status,progress:f,title:aa(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}})()},[i,c,r,n])}function aa(t){return t.title?t.title:l.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function bn({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(l.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(oe.CircleX,{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"})}},i=l.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:l.formatFileSize(t.fileSize)})]})]}),i&&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:Bs.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(l.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),i&&e.jsxs("div",{children:[e.jsx(l.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:Bs.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function yn(){const{authToken:t,tokenProps:s}=l.useSemaphorContext(),n=l.useExportStore(S=>S.activeExports),{clearCompleted:r,removeExport:o,updateExport:i}=l.useExportActions(),[c,u]=h.useState(!1),[d,m]=h.useState(!1),f=Array.from(n.values()).sort((S,N)=>N.startedAt.getTime()-S.startedAt.getTime()),g=f.some(S=>S.status==="completed"||S.status==="failed"),p=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!(!S||!N)){u(!0);try{const b=Array.from(n.values());await Promise.all(b.map(async T=>{try{const j=await l.getExportStatus(S,N,T.id);let C;if(j.status==="completed")try{C=await l.getDownloadUrl(S,N,T.id)}catch(A){console.error(`Failed to get download URL for ${T.id}:`,A)}i(T.id,{status:j.status,progress:j.progress,completedChunks:j.completedChunks,completedAt:j.completedAt?new Date(j.completedAt):void 0,lastUpdatedAt:new Date,fileSize:j.fileSize,error:j.error,downloadUrl:C})}catch(j){console.error(`Failed to refresh export ${T.id}:`,j)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,i]),y=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,N=t==null?void 0:t.accessToken;if(!S||!N){r();return}m(!0);try{const b=f.filter(j=>j.status==="completed"||j.status==="failed"),T=await Promise.allSettled(b.map(async j=>(await l.cancelExport(S,N,j.id),j.id)));for(const j of T)j.status==="fulfilled"?o(j.value):console.error("Failed to delete export:",j.reason)}finally{m(!1)}},[f,s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,r,o]),I=h.useCallback(async S=>{const N=s==null?void 0:s.apiServiceUrl,b=t==null?void 0:t.accessToken;if(N&&b)try{await l.cancelExport(N,b,S),o(S);return}catch(T){console.error(`Failed to cancel export ${S}:`,T)}o(S)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,o]);return f.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Vs,{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(Vs,{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(l.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:y,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:f.map(S=>e.jsx(bn,{export:S,onRemove:I},S.id))})})]})}function oa({variant:t}){const s=l.useExportStore(d=>d.activeExports),n=l.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(l.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(yn,{})})]})}function ia(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 jn({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:o="manage"}){const i=o==="create",{forceClose:c,handleOpenChange:u,isCreateFlowActive:d,preventPassiveDismissDuringCreate:m,resolvedOpen:f,setIsCreateFlowActive:g}=oe.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:o==="create",dismissMode:r?"passive":"explicit-only"}),p=a.useDashboardStore(D=>D.dashboard),{setDashboardControlsModel:y}=a.useDashboardActions(),{participants:I}=l.useDashboardStructuralParticipants(a.getDashboardCards(p)),S=Array.from(new Map(I.flatMap(D=>D.fieldChoices.map(R=>{var _;return[R.value,{option:R,target:(_=D.fieldTargetMap)==null?void 0:_[R.value]}]}))).values()),N=Array.from(new Map(I.flatMap(D=>D.metricChoices.map(R=>{var _;return[R.value,{option:R,target:(_=D.metricTargetMap)==null?void 0:_[R.value]}]}))).values()),b=a.collectDashboardControlIds({...p||{},controls:[]}),T=l.buildDashboardStructuralParticipantIdsByControlId(p),j=(D,R,_)=>{y(D,R,ia(_))},C=h.useCallback(()=>{if(i){c();return}g(!1)},[i,c,g]),A=e.jsx(oe.ControlDefinitionListEditor,{scope:"dashboard",controls:p.controls||[],reservedControlIds:b,defaultValues:p.defaultControlValues||{},usageByControlId:l.buildDashboardControlUsageById(p),availableFieldChoices:S,availableMetricChoices:N,structuralParticipants:I,structuralParticipantIdsByControlId:T,initialCreateFlow:o==="create",onCreateFlowActiveChange:g,onCreateFlowComplete:C,onChange:j,emptyMessage:"No dashboard controls yet."}),V=d?"Add dashboard control":"Dashboard Controls",L=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."})]}),A]});return r?e.jsxs(a.Popover,{open:f,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:L})]}):e.jsx(l.Dialog,{open:f,onOpenChange:u,children:e.jsxs(l.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:m,onPointerDownOutside:m,children:[e.jsxs(l.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(l.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(l.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:A})]})})}const la=["enum","multi_enum","text","number","boolean","date"];function vn({open:t,onOpenChange:s,initialMode:n="manage"}){var L;const r=n==="create",{forceClose:o,handleOpenChange:i,isCreateFlowActive:c,preventPassiveDismissDuringCreate:u,resolvedOpen:d,setIsCreateFlowActive:m}=oe.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),f=a.useDashboardStore(D=>D.dashboard),g=a.useDashboardStore(D=>D.selectedSheetId),{setDashboardInputs:p}=a.useDashboardActions(),y=(L=f.sheets)==null?void 0:L.find(D=>D.id===g),I=(y==null?void 0:y.kind)==="document"&&!!y.document,S=h.useMemo(()=>I&&(y!=null&&y.document)?l.getDocumentSheetDashboardInputs(f,y.id):[],[f,I,y==null?void 0:y.document,y==null?void 0:y.id]),N=h.useMemo(()=>S.filter(D=>D.kind==="control"),[S]),b=h.useMemo(()=>N.map(D=>D.control),[N]),T=h.useMemo(()=>da(b),[b]),j=h.useMemo(()=>ca(f),[f]),C=h.useCallback(()=>{if(r){o();return}m(!1)},[r,o,m]),A=h.useCallback((D,R,_)=>{!I||!(y!=null&&y.document)||p(ma({allInputs:f.inputs||[],documentSheetId:y.id,currentDocumentInputs:S,nextControls:D,nextDefaultValues:R,change:_}))},[f.inputs,S,I,y,p]);if(!I||!(y!=null&&y.document))return null;const V=c?"Add document control":"Document Controls";return e.jsx(l.Dialog,{open:d,onOpenChange:i,children:e.jsxs(l.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs(l.DialogHeader,{className:c?"space-y-0":void 0,children:[e.jsx(l.DialogTitle,{className:"text-[15px]",children:V}),e.jsx(l.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(oe.ControlDefinitionListEditor,{scope:"dashboard",controls:b,reservedControlIds:j,defaultValues:T,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:la,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:C,onChange:A,emptyMessage:"No document controls yet."})})]})})}function ca(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 ua(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 ma({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:o,change:i}){const c=new Map(r.map(p=>[p.id,ua(p,o)])),u=(i==null?void 0:i.type)==="rename"?{oldId:i.oldId,newId:i.newId}:null,d=new Set,m=[];for(const p of n){if(p.kind!=="control"){m.push(p);continue}const y=c.get(p.control.id)||((u==null?void 0:u.oldId)===p.control.id?c.get(u.newId):void 0);if(!y)continue;d.add(y.id);const I=l.createUniqueDashboardInputVariableNameFromName(y.id,[...t,...m].filter(N=>N.id!==p.id)),S=y.id===I?y:{...y,id:I};m.push({...p,label:S.label,variableName:I,requiredAtExecution:S.requiredAtExecution,control:S})}for(const p of c.values())d.has(p.id)||m.push(l.createDashboardControlInputFromControl({control:p,existingInputs:[...t,...m],sheetId:s}));const f=new Set(n.map(p=>p.id));return[...t.filter(p=>!f.has(p.id)),...m]}function Nn({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:o="default",className:i,primaryButtonClassName:c,secondaryButtonClassName:u,pickerContentClassName:d,settingsContentClassName:m}){const f=o==="toolbar",[g,p]=h.useState(!1),y=l.useSurfaceAppearance("interactive");return e.jsxs("div",{className:a.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",f?"h-8":"h-7",i),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(zr,{className:"h-3.5 w-3.5"}):e.jsx(l.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:y.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:y.contentStyle,children:r(()=>p(!1))})]})]})}function ha(){oe.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:i}=a.useEditorActions(),c=a.useEditorStore(d=>d.card.dataSource);return h.useEffect(()=>{var m,f;let d=r();if(!d){const g=(m=n==null?void 0:n.sheets)==null?void 0:m.find(y=>y.id===t),p=(f=g==null?void 0:g.frames)==null?void 0:f[0];p&&(o(p.id),d=p)}if(d){const g=d.cards.find(p=>p.id===d.activeCardId);g&&i(g)}},[r,t,s,n,o,i]),{hasEntities:!!(c!=null&&c.selectedEntities&&c.selectedEntities.length>0)}}function xa(){const t=a.useDashboardStore(u=>u.dashboard),s=a.useDashboardStore(u=>u.semanticExecutionPayload),n=a.useDashboardStore(u=>u.actions.addFilter),{hasEntities:r}=ha(),o=h.useMemo(()=>l.getGlobalDateFilterCoverage(t,s),[t,s]),c=!l.getGlobalDateFilter(t.filters)&&o.hasEligibleCards;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[c&&e.jsxs("div",{className:"border-b border-border/60 p-2",children:[e.jsxs("p",{className:"mb-1 flex items-center gap-1 px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[e.jsx(l.Sparkles,{className:"h-2.5 w-2.5"}),"Suggested"]}),e.jsxs("button",{type:"button",onClick:()=>n(l.createDefaultGlobalDateFilter()),title:`Eligible: ${o.eligibleCardCount} of ${o.totalCardCount} 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(l.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:"Global date filter"}),e.jsx("span",{className:"text-[11px] leading-[1.4] text-muted-foreground",children:"One date range, applied across every date-aware card on the dashboard."})]})]})]}),!r&&e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",children:[e.jsx(l.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(l.FilterableFieldsPanel,{context:"filter"})})]})}const Us=!1;function pa({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const o=a.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:i}=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(Lt,{icon:l.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(Lt,{icon:a.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(Lt,{icon:l.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"}),Us,e.jsx(fa,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:c,onCheckedChange:u=>i({toolbarWrap:u===!0})}),Us]})]})}function Lt({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(l.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 ga({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:i}){var V;const[c,u]=h.useState(null),d=a.useDashboardStore(L=>L.dashboard),m=a.useDashboardStore(L=>L.selectedSheetId),f=a.useDashboardStore(L=>L.showFilters),g=l.useAssistantLayoutStore(L=>L.setPanelOpen),p=a.useDashboardStore(L=>L.actions),{setDocumentInspectorTab:y,setShowFilters:I}=p,S=(V=d.sheets)==null?void 0:V.find(L=>L.id===m),N=a.isDocumentSheet(S),b=h.useCallback(L=>{window.setTimeout(()=>{u(L)},0)},[]),T=h.useCallback(L=>{if(N&&m){L&&y(m,"inputs");return}L&&g("dashboard",!1),I(L)},[N,m,y,g,I]),j=h.useCallback(()=>{T(!0)},[T]),C=h.useCallback(()=>{b("create")},[b]),A=h.useCallback(()=>{b("manage")},[b]);return e.jsxs(e.Fragment,{children:[e.jsx(Nn,{showFilters:N?!1:f,onShowFiltersChange:T,pickerContent:e.jsx(xa,{}),settingsContent:L=>e.jsx(pa,{onAddFilter:j,onAddControl:C,onManageControls:A,onDismiss:L}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:i}),c?N?e.jsx(vn,{open:!0,onOpenChange:L=>{L||u(null)},initialMode:c}):e.jsx(jn,{open:!0,onOpenChange:L=>{L||u(null)},showTrigger:!1,initialMode:c}):null]})}class ut extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function wn(t,s){return`${t.replace(/\/$/,"")}${s}`}function ie(t){return encodeURIComponent(t)}function mt(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 ba(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 Cn(t){if(!t||typeof t!="object")return null;const s=t;return typeof s.error=="string"?s.error:null}async function le(t,s,n,r){const o=await fetch(wn(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)||{}}}),i=await o.json().catch(()=>({}));if(!o.ok)throw new ut(Cn(i)||"Briefings API request failed",o.status,i);return i}async function Sn(t,s,n,r){const o=await fetch(wn(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){const i=await ba(o);throw new ut(Cn(i)||"Briefing artifact request failed",o.status,i)}return{kind:r,content:await o.text(),contentType:o.headers.get("content-type")??"text/plain",filename:ya(o.headers.get("content-disposition"))}}function ya(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function kn(t,s,n){return le(t,s,`/v1/briefings${mt({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 ja(t,s,n){return le(t,s,`/v1/briefings/tenant-summaries${mt({status:n==null?void 0:n.status})}`)}async function Gt(t,s,n){return le(t,s,`/v1/briefings/${ie(n)}`)}async function Dn(t,s,n){return le(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function ht(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Xt(t,s,n){return ht(t,s,n,{status:"PAUSED"})}async function Jt(t,s,n){return ht(t,s,n,{status:"ACTIVE"})}async function Qt(t,s,n){return le(t,s,`/v1/briefings/${ie(n)}`,{method:"DELETE"})}async function Yt(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs`,{method:"POST",body:JSON.stringify(r)})}async function En(t,s,n){return le(t,s,"/v1/briefings/preview-plan",{method:"POST",body:JSON.stringify({draft:n})})}async function In(t,s,n){return le(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function An(t,s,n){return(await le(t,s,`/v1/briefings/preview-runs/${ie(n)}`)).previewRun}async function va(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs${mt({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function Zt(t,s,n,r){return(await le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`)).run}async function Tn(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Ln(t,s,n,r){return le(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}`,{method:"DELETE"})}async function Na(t,s,n,r,o){return Sn(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}/artifact${mt({kind:o})}`,o)}async function wa(t,s,n,r){return Sn(t,s,`/v1/briefings/${ie(n)}/runs/${ie(r)}/evidence`,"evidence")}async function Fn(t,s,n){var o;const r=await le(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 ut(r.error||"Polish returned no result",502,r);return r.result.polished}const Ca={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},Sa={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function Ne(t){return Z(t)}function $s(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 es(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 ka(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 Rn(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 Vn(n)}}}function Da(t,s){return Rn(t).includes(s)?{...Ne(t),format:s,settings:Bn(t.settings,s)}:Ne(t)}function Ea(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...Ne(t),settings:n}}function Pn(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),i=o.find(d=>d.id===t.selectedSheetId)??o[0];i&&r.push({key:`dashboard_sheet:${s}:${i.id}`,kind:"dashboard_sheet",title:`${Rt(i)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:i.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:`${Rt(d)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:d.id,formats:["pdf"],defaultFormat:"pdf"});if(i)for(const d of On(i)){if(d.card.type==="text")continue;const m=Vn(d.card.type);r.push({key:`card:${s}:${d.card.id}`,kind:"card",title:d.card.title||"Untitled card",detail:`${Rt(i)} · ${d.card.type}`,dashboardId:s,sheetId:i.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:l.getDefaultExportFormat(d.card.type)})}return r}function _t(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Ia({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:Ft(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:Ft(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:Ft(s.cardId),format:n,title:s.title,settings:r}}}function _s(t){const s=Pn(t),n=s.find(i=>i.kind==="dashboard_sheet"),o=s.find(i=>i.kind==="dashboard")??n;return o?[_t({option:o,runtime:t.runtime})]:[]}function Ia(t){const s={...Bn(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=Z(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=Z(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=Z(t.option.tablePreferences))),Aa({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Pa(s.filterValues)),s}function Aa(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Ta({settings:s,option:n,runtime:r});return}const o=n.kind==="dashboard"?"all":"current",i=n.kind==="dashboard"?r.selectedSheetId:n.sheetId,c=l.buildDashboardExecutionSnapshot({dashboard:r.dashboard||void 0,filterValues:r.filterValues,selectedSheetId:i,sheetSelection:o,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});s.sheetFilterValues=Z(c.filterValues),s.filterValues=Z(c.filterValues),s.controlValues=Z(c.controlValues),r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions));const u=La({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&o==="all"?void 0:i,sheetSelection:o});u&&(s.dashboardInputExecutionSnapshot=Z(u))}function Ta(t){var m,f,g;const{settings:s,option:n,runtime:r}=t,o=n.cardId,i=l.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=Z(i),!o){s.filterValues=Z(i),s.controlValues=Z(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions));return}const c=((m=r.inlineFilterValuesMap)==null?void 0:m[o])||[];c.length>0&&(s.inlineFilterValues=Z(c));const u=l.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:o,interactionStates:r.interactionStates||{},currentDashboardId:(f=r.dashboard)==null?void 0:f.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=Z(u.queryContext.cardFilterValues),s.controlValues=Z(u.queryContext.controlValues),s.controlDefinitions=Z(u.queryContext.controlDefinitions),s.cardControlDefinitions=Z(u.queryContext.cardControlDefinitions),s.controlBindings=Z(u.queryContext.controlBindings)):(s.filterValues=Z(i),s.controlValues={...r.controlValues||{},...((g=r.cardControlValuesMap)==null?void 0:g[o])||{}},r.controlDefinitions&&(s.controlDefinitions=Z(r.controlDefinitions)));const d=Fa({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:c,controlValues:s.controlValues});d&&(s.dashboardInputExecutionSnapshot=Z(d))}function La(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(),i=Mn();if(s.kind==="document_sheet"&&s.sheetId)return l.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:i}).snapshot;const c=t.sheetSelection==="all"?a.getDashboardSheets(r.sheets).map(d=>d.id):t.selectedSheetId?[t.selectedSheetId]:[];if(c.length!==0)return l.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:i}).snapshot}function Fa(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=Ra(r,s.sheetId,s.cardId),i=t.inlineFilterValues!==void 0?{...n.inlineFilterValuesMap||{},[s.cardId]:t.inlineFilterValues}:n.inlineFilterValuesMap,c=t.filterValues!==void 0?l.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 l.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:i,cardControlValuesMap:n.cardControlValuesMap},generatedAt:new Date().toISOString(),timezone:Mn()}).snapshot}function Ra(t,s,n){const r=t.sheets||[],o=s?r.filter(i=>i.id===s):r;for(const i of o)for(const c of On(i))if(c.card.id===n)return{sheet:i,card:c.card}}function Mn(){return typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Pa(t){if(!Array.isArray(t))return"";const s=t.filter(n=>!!n&&typeof n=="object"&&typeof n.name=="string");return l.formatFilterLine(s)}function Bn(t,s){return s==="csv"?{...Sa,...t}:{...Ca,...t}}function Vn(t){return t?l.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function On(t){const s=[],n=new Set,r=(o,i)=>{!(o!=null&&o.id)||n.has(o.id)||(n.add(o.id),s.push({card:o,frame:i}))};for(const o of t.cards||[])r(o);for(const o of t.frames||[])for(const i of o.cards||[])r(i,o);return s}function Ft(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function Rt(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function Z(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Un=["markdown"],Ma={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Un],includeEvidence:!0,includeSql:!0},schedule:{enabled:!1,scheduleExpr:"",timezone:"UTC",status:"ACTIVE"},delivery:{enabled:!1,recipients:[],channels:[],subject:"",message:""},limits:{}};function $n(t){const s=t.trim();return s.length>0?s:void 0}function Ba(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ne),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 Va(t){return t.type==="generated_analysis"?t.instruction:t.type==="custom_message"?t.message:""}function _n(t,s){return t.type==="custom_message"?{type:"custom_message",message:s}:t.type==="none"?{type:"none"}:{type:"generated_analysis",instruction:s}}function ts(t){return _n(t.body,t.instruction.trim())}function zn(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 qn(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 Hn(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 Kn(t){return t.recipients.length===0&&t.channels.length===0?null:{recipients:t.recipients.map(s=>({...s})),channels:[...t.channels],channelConfigs:Hn(t.channelConfigs,t.channels)}}function Oa(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Un],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 Ua(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function $a(t){return{enabled:!0,recipients:(t==null?void 0:t.recipients.map(s=>({...s})))??[],channels:t!=null&&t.channels?[...t.channels]:[],subject:"",message:"",channelConfigs:Hn(t==null?void 0:t.channelConfigs,(t==null?void 0:t.channels)??[])}}function _a(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function za(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function Pt(t,s,n,r,o){_a(n,r,o)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${o}`})}function Wn(t){return at(Ma,t??{})}function at(t,s){var c,u,d,m;const n=s.instruction??(s.body?Va(s.body):t.instruction),r=_n(s.body?{...s.body}:{...t.body},n),o=(c=s.delivery)!=null&&c.channels?[...s.delivery.channels]:[...t.delivery.channels],i=((u=s.delivery)==null?void 0:u.channelConfigs)??t.delivery.channelConfigs;return{...Ba(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(Ne):t.attachments.map(Ne),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(f=>({...f})):t.delivery.recipients.map(f=>({...f})),channels:o,channelConfigs:i},limits:{...t.limits,...s.limits}}}function Ue(t){return{name:t.name,description:t.description??"",instruction:Ua(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(Ne),output:Oa(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:$a(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function zt(t){return{name:t.name.trim(),description:$n(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:ts(t),attachments:t.attachments.map(Ne),presentation:zn(t.output),limits:qn(t.limits),deliveryConfig:Kn(t.delivery)}}function Gn(t){return{name:t.name.trim(),description:$n(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:ts(t),attachments:t.attachments.map(Ne),presentation:zn(t.output),limits:qn(t.limits),deliveryConfig:Kn(t.delivery)}}function qt(t){var r,o,i,c,u;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=ts(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,f)=>{m.type==="email"&&!za(m.address)&&s.push({field:`delivery.recipients.${f}.address`,message:"Email recipient address is invalid"})}),t.delivery.channels.includes("WEBHOOK")){const m=(r=t.delivery.channelConfigs)==null?void 0:r.WEBHOOK;(i=(o=m==null?void 0:m.webhookConfig)==null?void 0:o.url)!=null&&i.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 Pt(s,"maxToolCalls",t.limits.maxToolCalls,1,100),Pt(s,"maxRows",t.limits.maxRows,1,1e5),Pt(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const Qe="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function qa({attachment:t,open:s,onOpenChange:n,onChange:r,children:o}){const i=Rn(t),c=t.settings||{},u=t.format==="csv",d=m=>{r(Ea(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(Qe,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:es(t)})]}),i.length>1?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Qe,"mb-1 block"),children:"Format"}),e.jsxs(a.Select,{value:t.format,onValueChange:m=>r(Da(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:i.map(m=>e.jsx(a.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(Ka,{settings:c,onChange:d}):e.jsx(Ha,{settings:c,onChange:d})]})]})}function Ha({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(Qe,"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(Qe,"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(ot,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(ot,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function Ka({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Qe,"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(ot,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(ot,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function ot({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-foreground/80",children:[e.jsx(l.Checkbox,{checked:s,onCheckedChange:r=>n(r===!0)}),e.jsx("span",{children:t})]})}function Wa({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(l.Paperclip,{className:"h-3 w-3"}),o?"Attach":null]}),t.map((i,c)=>e.jsx(Ga,{attachment:i,disabled:r,onUpdate:u=>{const d=[...t];d[c]=u,s(d)},onRemove:()=>s(t.filter((u,d)=>d!==c))},`${i.type}:${c}:${es(i)}`)),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(l.Plus,{className:"h-3 w-3"}),"Add"]})]})}function Ga({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[o,i]=h.useState(!1),c=es(t),u=ka(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(qa,{attachment:t,open:o,onOpenChange:i,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(Xa,{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 Xa({format:t,className:s}){const n=t==="csv"?l.FileSpreadsheet:l.FileText;return e.jsx(n,{className:a.cn(s)})}const Ja="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Qa({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:o,runtime:i,selectedAttachments:c,onSubmit:u}){const d=h.useMemo(()=>Pn({source:n,dashboard:r,selectedSheetId:o}),[n,r,o]),[m,f]=h.useState([]);h.useEffect(()=>{if(!t)return;const A=[];for(const V of c){const L=$s(V),D=d.find(R=>R.formats.some(_=>{const M=_t({option:R,format:_,runtime:i});return $s(M)===L}));D&&A.push({optionKey:D.key,format:V.format??D.defaultFormat})}f(A)},[t,d,c,i]);const g=h.useMemo(()=>new Set(m.map(A=>A.optionKey)),[m]),p=h.useMemo(()=>{const A={};for(const V of m)A[V.optionKey]=V.format;return A},[m]),y=(A,V)=>{f(L=>L.some(R=>R.optionKey===A)?L.filter(R=>R.optionKey!==A):[...L,{optionKey:A,format:V}])},I=(A,V)=>{f(L=>L.map(D=>D.optionKey===A?{...D,format:V}:D))},S=()=>{const A=[];for(const V of m){const L=d.find(D=>D.key===V.optionKey);L&&A.push(_t({option:L,format:V.format,runtime:i}))}u(A),s(!1)},N=()=>s(!1),b=h.useMemo(()=>d.filter(A=>A.kind==="dashboard"||A.kind==="dashboard_sheet"),[d]),T=h.useMemo(()=>d.filter(A=>A.kind==="document_sheet"),[d]),j=h.useMemo(()=>d.filter(A=>A.kind==="card"),[d]),C=m.length;return e.jsx(l.Dialog,{open:t,onOpenChange:s,children:e.jsxs(l.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(l.DialogHeader,{className:"border-b border-border px-4 py-3 text-left",children:[e.jsx(l.DialogTitle,{className:"text-[14px] font-semibold leading-5",children:"Add attachments"}),e.jsx(l.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(Mt,{label:"Dashboard",options:b,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I}),e.jsx(Mt,{label:"Paginated reports",options:T,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I,emptyText:"No paginated report sheets are available."}),e.jsx(Mt,{label:"Current sheet cards",options:j,selectedOptionKeys:g,formatByOptionKey:p,onToggle:y,onFormatChange:I,emptyText:"No exportable cards are available on the current dashboard sheet."})]})}),e.jsxs(l.DialogFooter,{className:"flex flex-row items-center justify-between gap-2 border-t border-border px-4 py-3 sm:justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:C===0?"Nothing selected":`${C} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Button,{type:"button",variant:"outline",size:"xs",onClick:N,children:"Cancel"}),e.jsx(a.Button,{type:"button",size:"xs",onClick:S,disabled:n.type!=="dashboard",children:C>0?`Add ${C} ${C===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function Mt({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:o,onFormatChange:i,emptyText:c}){return e.jsxs("section",{children:[e.jsx("div",{className:a.cn(Ja,"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(Ya,{selected:d}),e.jsx(Za,{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:f=>i(u.key,f),children:[e.jsx(a.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:f=>f.stopPropagation(),children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:u.formats.map(f=>e.jsx(a.SelectItem,{value:f,children:f.toUpperCase()},f))})]}):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 Ya({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 Za({kind:t,format:s,cardType:n,className:r}){const o=s==="csv"?l.FileSpreadsheet:t==="dashboard"?l.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?oe.Rows3:a.ChartColumn:l.FileText;return e.jsx(o,{className:r})}const eo=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,to=250;function Ge(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 so(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function no(t){return t.type==="group"?t.groupId:null}function Xe(t){return(t==null?void 0:t.trim().toLowerCase())||null}function zs(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function qs(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function Hs({value:t,onChange:s,className:n,disabled:r=!1,prefix:o,placeholder:i}){const c=h.useRef(null),[u,d]=h.useState(!1),[m,f]=h.useState(""),[g,p]=h.useState(0),[y,I]=h.useState(()=>new Map),[S,N]=h.useState(()=>new Map),[b,T]=h.useState("people"),j=l.useDebounce(m,to),{currentUser:C}=l.useCurrentUserInfo(),A=(C==null?void 0:C.type)==="tenant",{users:V,isLoading:L}=l.useUnifiedUsers({search:j,active:!0,type:A?"tenant":"all",tenantId:A?C.tenantId:void 0,limit:25}),{groups:D,isLoading:R}=l.useGroups({search:j,type:A?"TENANT_GROUP":"all",tenantId:A?C.tenantId:void 0,limit:25}),_=h.useMemo(()=>new Set(t.map(Ge)),[t]),M=h.useMemo(()=>new Set(t.map(so).filter(k=>!!k)),[t]),z=h.useMemo(()=>new Set(t.map(no).filter(k=>!!k)),[t]),U=h.useMemo(()=>{const k=new Map(y);return V.forEach(P=>{k.set(P.id,zs(P))}),C!=null&&C.id&&k.set(C.id,{kind:"user",id:C.id,name:C.name||C.email||"User",email:C.email||"",type:C.type}),k},[y,V,C]),B=h.useMemo(()=>{const k=new Set;return t.forEach(P=>{var xe;if(P.type==="email"){const Oe=Xe(P.address);Oe&&k.add(Oe);return}if(P.type==="group")return;const se=P.type==="tenant_user"?P.tenantUserId:P.userId,ce=Xe((xe=U.get(se))==null?void 0:xe.email);ce&&k.add(ce)}),k},[U,t]),W=h.useMemo(()=>{const k=new Map(S);return D.forEach(P=>{k.set(P.id,qs(P))}),k},[S,D]),E=h.useMemo(()=>V.filter(k=>{if(M.has(k.id))return!1;const P=Xe(k.email);return P&&B.has(P)?!1:A?k.type==="tenant"&&k.tenantId===(C==null?void 0:C.tenantId):!0}).map(zs),[V,M,B,A,C==null?void 0:C.tenantId]),me=h.useMemo(()=>E.filter(k=>k.type==="organization"),[E]),w=h.useMemo(()=>E.filter(k=>k.type==="tenant"),[E]),q=h.useMemo(()=>D.filter(k=>z.has(k.id)?!1:(C==null?void 0:C.type)==="tenant"?k.type==="TENANT_GROUP"&&k.tenantId===C.tenantId:!0).map(qs),[D,z,C==null?void 0:C.type,C==null?void 0:C.tenantId]),te=h.useMemo(()=>A?[{key:"people",label:"People",count:w.length},{key:"groups",label:"Groups",count:q.length}]:[{key:"people",label:"People",count:me.length},{key:"tenant_users",label:"Tenant users",count:w.length},{key:"groups",label:"Groups",count:q.length}],[q.length,A,me.length,w.length]),Q=h.useMemo(()=>b==="groups"?[]:b==="tenant_users"||A?w:me,[b,A,me,w]),be=h.useMemo(()=>b==="groups"?q:[],[b,q]),pe=h.useMemo(()=>[...Q,...be],[Q,be]),ye=pe.length===0?0:Math.min(g,pe.length-1),O=m.trim(),Le=eo.test(O),we=Xe(O),je=we?B.has(we):!1,Fe=L||R,H=k=>{_.has(Ge(k))||(s([...t,k]),f(""),p(0))},fe=k=>{s(t.filter(P=>Ge(P)!==k))},Ae=()=>{!Le||je||H({type:"email",address:O})},$=k=>{const P=Xe(k.email);P&&B.has(P)||(I(se=>{const ce=new Map(se);return ce.set(k.id,k),ce}),H(k.type==="tenant"?{type:"tenant_user",tenantUserId:k.id}:{type:"user",userId:k.id}))},Y=k=>{N(P=>{const se=new Map(P);return se.set(k.id,k),se}),H({type:"group",groupId:k.id})},_e=k=>{if(k.key==="Enter"){if(k.preventDefault(),Le&&!je){Ae();return}const P=pe[ye];if((P==null?void 0:P.kind)==="user"){$(P);return}if((P==null?void 0:P.kind)==="group"){Y(P);return}}else if(k.key==="ArrowDown")k.preventDefault(),p(P=>Math.min(P+1,Math.max(pe.length-1,0)));else if(k.key==="ArrowUp")k.preventDefault(),p(P=>Math.max(P-1,0));else if(k.key==="Escape")d(!1);else if(k.key==="Backspace"&&m.length===0){const P=t[t.length-1];P&&fe(Ge(P))}},as=t.map(k=>{const P=Ge(k);if(k.type==="email")return{key:P,label:k.name||k.address,icon:e.jsx(l.AtSign,{className:"h-3 w-3"}),onRemove:()=>fe(P)};if(k.type==="group"){const xe=W.get(k.groupId);return{key:P,label:(xe==null?void 0:xe.name)||"Group",icon:e.jsx(Wt,{className:"h-3 w-3"}),onRemove:()=>fe(P)}}const se=k.type==="tenant_user"?k.tenantUserId:k.userId,ce=U.get(se);return{key:P,label:(ce==null?void 0:ce.name)||(ce==null?void 0:ce.email)||"User",icon:e.jsx(l.User,{className:"h-3 w-3"}),onRemove:()=>fe(P)}});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 k;r||((k=c.current)==null||k.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,as.map(k=>e.jsx(ro,{icon:k.icon,label:k.label,onRemove:k.onRemove},k.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:i??(t.length>0?"Add more...":"Add people, emails, or groups"),onChange:k=>{f(k.target.value),p(0),d(!0)},onFocus:()=>d(!0),onKeyDown:_e})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:k=>k.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(ao,{activeIndex:ye,activeFilter:b,emailAlreadyAdded:je,filters:te,groupSuggestions:be,loading:Fe,onAddEmail:Ae,onFilterChange:k=>{T(k),p(0)},onGroupClick:Y,onUserClick:$,orderedSuggestions:pe,query:O,queryIsEmail:Le,userSuggestions:Q,viewerType:C==null?void 0:C.type})})]})})}function ro({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 ao({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:o,loading:i,onAddEmail:c,onFilterChange:u,onGroupClick:d,onUserClick:m,orderedSuggestions:f,query:g,queryIsEmail:p,userSuggestions:y,viewerType:I}){const S=!i&&f.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(N=>e.jsxs("button",{type:"button",onClick:()=>u(N.key),className:a.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===N.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:N.label}),e.jsx("span",{className:a.cn("tabular-nums",s===N.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:N.count})]},N.key))}),i?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,y.length>0?e.jsx(Ks,{heading:"People",children:y.map(N=>{var T;const b=f.indexOf(N);return e.jsx(Ws,{active:b===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:(T=(N.name||N.email||"?")[0])==null?void 0:T.toUpperCase()}),detail:N.name?N.email:void 0,tag:N.type==="organization"?"Org user":"Tenant user",viewerType:I,title:N.name||N.email,onClick:()=>m(N)},N.id)})}):null,o.length>0?e.jsx(Ks,{heading:"Groups",children:o.map(N=>{const b=f.indexOf(N);return e.jsx(Ws,{active:b===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(Wt,{className:"h-3 w-3"})}),detail:N.memberCount!==void 0?`${N.memberCount} member${N.memberCount===1?"":"s"}`:N.description??void 0,tag:N.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:I,title:N.name,onClick:()=>d(N)},N.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(pn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13px] text-foreground",children:["Send to ",e.jsx("span",{className:"font-medium",children:g})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:"Add as external email"})]}),e.jsx("span",{className:"ml-auto shrink-0 rounded-control border border-border bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"Enter"})]})}):null,S?e.jsx("div",{className:"px-2.5 py-6 text-center text-[12px] text-muted-foreground",children:g?"No people or groups match. Enter a valid email to add an external recipient.":"Pick a category above or type to search people, groups, or external emails."}):null]})}function Ks({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 Ws({active:t,avatar:s,detail:n,onClick:r,tag:o,title:i,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:i}),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 it(t){return t==="SUCCESS"||t==="FAILED"}function lt(t){return t==="QUEUED"||t==="RUNNING"}function Ht({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d}){const[m,f]=h.useState(null),[g,p]=h.useState("idle"),y=h.useRef(null),I=h.useRef({fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d});h.useEffect(()=>{I.current={fetchRun:o,onRun:i,onTerminalRun:c,onError:u,onTimeout:d}},[o,u,i,c,d]);const S=h.useCallback(()=>{f(null),p("idle")},[]),N=h.useCallback(()=>{y.current=null},[]),b=h.useCallback(j=>{var C,A;if(I.current.onRun(j),it(j.status)){y.current=j.id,f(null),p("terminal"),(A=(C=I.current).onTerminalRun)==null||A.call(C,j);return}if(lt(j.status)){y.current=null,f(j.id),p("polling");return}f(null),p("idle")},[]),T=h.useCallback(j=>{y.current!==j&&(f(j),p("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(y.current===m){f(null),p("terminal");return}let j=!1,C=!1,A=null;const V=Date.now(),L=async()=>{var D,R,_,M,z,U;if(!(j||C)){if(Date.now()-V>r){f(B=>B===m?null:B),p("timed_out"),(R=(D=I.current).onTimeout)==null||R.call(D,m);return}C=!0;try{const B=await I.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(j)return;if(I.current.onRun(B),it(B.status)){y.current=B.id,f(W=>W===B.id?null:W),p("terminal"),(M=(_=I.current).onTerminalRun)==null||M.call(_,B);return}if(!lt(B.status)){f(W=>W===B.id?null:W),p("idle");return}A=window.setTimeout(L,n)}catch(B){j||(p("error"),(U=(z=I.current).onError)==null||U.call(z,B))}finally{C=!1}}};return p("polling"),L(),()=>{j=!0,A&&window.clearTimeout(A)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&g==="polling",resetTerminalRun:N,startRun:b,startRunId:T,status:g,stop:S}}function Gs({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 oo({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(l.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(Bt,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:i=>r("evidence",i)}),e.jsx(Bt,{label:"Include SQL in evidence",description:"Show the SQL the briefing ran. Useful for debugging or for a technical audience.",checked:s,onChange:i=>r("sql",i)}),e.jsx(Bt,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:i=>r("html",i)})]})]})]})}function Bt({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 Kt=`Tell me what changed in the business and what is driving it.
57
57
 
58
58
  Watch:
59
59
  - Top-line movement versus the previous period
@@ -69,7 +69,7 @@ Include in the briefing:
69
69
  - KPI comparison with current, previous, delta, and percent change
70
70
  - Driver table or chart when useful
71
71
  - 2-3 recommended next actions
72
- - Evidence link rather than raw SQL in the main body`,Gs=`Watch this dashboard for unusual movement.
72
+ - Evidence link rather than raw SQL in the main body`,Xs=`Watch this dashboard for unusual movement.
73
73
 
74
74
  Focus on:
75
75
  - Spikes or drops versus recent history
@@ -80,11 +80,11 @@ Include in the briefing:
80
80
  - What changed
81
81
  - Why it looks unusual
82
82
  - The most likely drivers
83
- - What the team should check next`,Xs=`Hi team,
83
+ - What the team should check next`,Js=`Hi team,
84
84
 
85
85
  Sharing this dashboard. The PDF below has the selected dashboard view and current filters applied.
86
86
 
87
- Reply if you have questions.`,Js=`Track customer health across the top accounts. Surface accounts that crossed a risk threshold, with the leading signal that flagged them.
87
+ Reply if you have questions.`,Qs=`Track customer health across the top accounts. Surface accounts that crossed a risk threshold, with the leading signal that flagged them.
88
88
 
89
89
  Watch:
90
90
  - Health score drops > 10 points in the last 14 days
@@ -92,7 +92,7 @@ Watch:
92
92
  - Resolution-time regressions on enterprise tickets
93
93
 
94
94
  Audience:
95
- Customer Success leads. Action-oriented — every at-risk row needs an owner.`,Qs=`Short Slack-friendly digest. One headline, three bullets, no PDFs. Use emoji sparingly. Skip the analysis appendix — link to the dashboard.
95
+ Customer Success leads. Action-oriented — every at-risk row needs an owner.`,Ys=`Short Slack-friendly digest. One headline, three bullets, no PDFs. Use emoji sparingly. Skip the analysis appendix — link to the dashboard.
96
96
 
97
97
  Watch:
98
98
  - Top-line movement WoW
@@ -102,5 +102,5 @@ Watch:
102
102
  Format:
103
103
  - Headline (≤ 12 words)
104
104
  - Three bullets max
105
- - Link to the full dashboard`;function io(t,s,n){const r=t.includes("markdown")?t.filter(o=>o!==s):["markdown"];return n?Array.from(new Set([...r,s])):r}const nt=[{label:"Email report",description:"Email body with dashboard attachments",seedsDashboardAttachment:!0,available:t=>t.type==="dashboard",draft:(t,s)=>({name:"Dashboard Email Report",instruction:Xs,body:{type:"custom_message",message:Xs},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:Kt,body:{type:"generated_analysis",instruction:Kt},output:{includeEvidence:!0,includeSql:!1}})},{label:"Anomaly watch",description:"Only surface unusual movement",draft:()=>({name:"Anomaly Watch Briefing",instruction:Gs,body:{type:"generated_analysis",instruction:Gs},output:{includeEvidence:!0,includeSql:!1}})},{label:"Customer health",description:"Daily watch on at-risk accounts",draft:()=>({name:"Customer Health Watch",instruction:Js,body:{type:"generated_analysis",instruction:Js},output:{includeEvidence:!0,includeSql:!1}})},{label:"Slack digest",description:"Short Slack-friendly digest, no PDFs",draft:()=>({name:"Slack Digest",instruction:Qs,body:{type:"generated_analysis",instruction:Qs},output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["SLACK"]}})}],J="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Je="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",Ie="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",Ys="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 lo({scheduleExpr:t,timezone:s,onScheduleChange:n}){const r=h.useMemo(()=>l.parseScheduleExpr(t),[t]),[o,i]=h.useState(()=>ct()),[c,u]=h.useState(null),d=l.buildSchedulePreview(r,s,Zs(o),c?en(c):null),[m,f]=h.useState(!1),g=b=>{n({scheduleExpr:l.buildScheduleExpr(b),timezone:s})},p=b=>{const T=b==="weekly"&&r.weekdays.length===0?[1,2,3,4,5]:r.weekdays;g({...r,repeats:b,weekdays:T})},y=(b,T)=>{g({...r,hour:b,minute:T})},I=b=>{g({...r,weekdays:b})},S=`${String(r.hour).padStart(2,"0")}:${String(r.minute).padStart(2,"0")}`,N=h.useMemo(()=>co(),[]);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:J,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(J,"mb-1 block"),children:"Repeats"}),e.jsxs(a.Select,{value:r.repeats,onValueChange:b=>p(b),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:"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(J,"mb-1 block"),children:"Time"}),e.jsxs(a.Select,{value:S,onValueChange:b=>{const[T,j]=b.split(":").map(C=>parseInt(C,10));y(T,j)},children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{className:"max-h-[280px]",children:N.map(({value:b,label:T})=>e.jsx(a.SelectItem,{value:b,children:T},b))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(a.Popover,{open:m,onOpenChange:f,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-expanded":m,className:a.cn(Je,"h-6 px-1.5 text-[11px]"),children:[e.jsx(l.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:b=>b.preventDefault(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:J,children:"More options"}),e.jsx("button",{onClick:()=>f(!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(J,"mb-1 block"),children:"First occurrence"}),e.jsx(tn,{icon:e.jsx(l.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:o,placeholder:"Pick a start date",disabledBefore:ct(),onChange:b=>{b&&i(b)},renderLabel:b=>b?Zs(b):"Today"})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"Timezone"}),e.jsxs(a.Select,{value:s,onValueChange:b=>n({scheduleExpr:l.buildScheduleExpr(r),timezone:b}),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(l.Globe,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx(a.SelectValue,{})]})}),e.jsx(a.SelectContent,{className:"max-h-[280px]",children:l.COMMON_TIMEZONES.map(b=>e.jsx(a.SelectItem,{value:b,children:uo(b)},b))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"Ends"}),e.jsx(tn,{icon:e.jsx(l.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:b=>b?en(b):"No end date"})]}),r.repeats==="weekly"?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"On these days"}),e.jsx("div",{className:"flex gap-1",children:["S","M","T","W","T","F","S"].map((b,T)=>{const j=r.weekdays.includes(T);return e.jsx("button",{type:"button",onClick:()=>{I(j?r.weekdays.filter(C=>C!==T):[...r.weekdays,T].sort())},className:a.cn("inline-flex h-7 w-7 items-center justify-center rounded-control border text-[11px] font-medium",j?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:border-border"),children:b},T)})})]}):null]})]})})]})}function co(){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:l.formatTimeLabel(s,n)})}return t}function uo(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 ct(){const t=new Date;return t.setHours(0,0,0,0),t}function mo(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function Zs(t){return mo(t,ct())?"Today":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function en(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function tn({value:t,icon:s,placeholder:n,clearable:r,clearLabel:o,disabledBefore:i,onChange:c,renderLabel:u}){const[d,m]=h.useState(!1),f=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??f:f})]}),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(l.Calendar$1,{mode:"single",selected:t??void 0,defaultMonth:t??i??ct(),onSelect:p=>{c(p??null),m(!1)},disabled:i?{before:i}: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 ho({source:t,resolvedSourceContext:s,sourceDetail:n,onChange:r}){const[o,i]=h.useState(!1),c=h.useRef(null),u=s.source.type==="dashboard"?s.source:null,d=u!==null;h.useEffect(()=>{if(!o)return;const N=b=>{const T=b.target;c.current&&!c.current.contains(T)&&!(T instanceof Element&&T.closest("[data-scope-popover]"))&&i(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[o]);const m=t.type==="project",f=s.source.type==="dashboard"?s.label??"This dashboard":"This dashboard",g=s.source.type==="dashboard"?s.detail??n??null:n,p="This project",y="Use any data in this project.",I=m?p:f,S=m?y:g;return d?e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:c,type:"button",onClick:()=>i(N=>!N),"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(l.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:I}),S?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground/70","aria-hidden":!0,children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground/70",children:S})]}):null]}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground group-hover:text-foreground",children:["Change",e.jsx(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(sn,{active:!m,label:f,detail:g??null,description:"Use only the datasets this dashboard already reads.",onSelect:()=>{u&&r(u),i(!1)},isLast:!1}),e.jsx(sn,{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"}),i(!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(l.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:I})]}),S?e.jsx("div",{className:"mt-0.5 pl-5 text-[11px] text-muted-foreground",children:S}):null]})}function sn({active:t,label:s,detail:n,description:r,onSelect:o,isLast:i}){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 ",!i&&"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(l.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 xo({channels:t,selectedChannelId:s,onChange:n,destinationKind:r,onDestinationKindChange:o,loading:i,disabled:c,className:u}){const d=h.useRef(null),[m,f]=h.useState(!1),[g,p]=h.useState(""),y=h.useMemo(()=>t.find(b=>b.id===s)??null,[t,s]),I=h.useMemo(()=>{const b=g.trim().toLowerCase();return b?t.filter(T=>T.name.toLowerCase().includes(b)):t},[t,g]),S=r==="dm",N=c||S;return e.jsx("div",{className:a.cn("relative",u),children:e.jsxs(a.Popover,{open:m&&!N,onOpenChange:f,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",N&&"cursor-not-allowed opacity-60"),onClick:()=>{var b;N||((b=d.current)==null||b.focus(),f(!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:b=>b.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"})]})]}),y?e.jsx(po,{channel:y,onRemove:()=>{var b;n(""),(b=d.current)==null||b.focus(),f(!0)}}):null,e.jsx("input",{ref:d,className:"h-6 min-w-[140px] flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground/70 disabled:cursor-not-allowed",value:g,disabled:N,placeholder:S?"DM delivery coming in V2":y?"Change channel…":i?"Loading channels…":"Search channels…",onChange:b=>{p(b.target.value),f(!0)},onFocus:()=>f(!0)})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:b=>b.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:I.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:I.map(b=>{const T=b.id===s;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{n(b.id),p(""),f(!1)},className:a.cn("flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left",T?"bg-muted text-foreground":"text-foreground/85 hover:bg-muted/60"),children:[b.isPrivate?e.jsx(l.Lock,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(l.Hash,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.name}),typeof b.memberCount=="number"?e.jsxs("span",{className:"ml-auto text-[11px] text-muted-foreground",children:[b.memberCount," members"]}):null]})},b.id)})})})]})})}function po({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(l.Lock,{className:"h-3 w-3"}):e.jsx(l.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 Xn=it,Ve=lt;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 Jn(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 ts(t){const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`}function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function go(t){if(!ne(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=>!ne(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=>!ne(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,i=Array.isArray(t.attachments)?t.attachments.filter(c=>typeof c=="string"):null;return!s||!n||!r||!o||!i?null:{subject:s,body:n,...typeof t.bodyHtml=="string"&&t.bodyHtml.trim()?{bodyHtml:t.bodyHtml}:{},recipients:r,channels:o,attachments:i,...typeof t.attachmentNotice=="string"?{attachmentNotice:t.attachmentNotice}:{}}}function bo(t){if(!ne(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(ne):null;if(!s||!n||!r)return null;const o=ne(t.thread)?{text:typeof t.thread.text=="string"?t.thread.text:"",blocks:Array.isArray(t.thread.blocks)?t.thread.blocks.filter(ne):[],reply_broadcast:!1}:void 0;return{channel:s,text:n,blocks:r,unfurl_links:!1,unfurl_media:!1,...o?{thread:o}:{}}}function yo(t){if(!ne(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 Qn(t){if(!ne(t.result))return null;const s=ne(t.result.deliveryReadiness)?t.result.deliveryReadiness:null,n=s&&ne(s.intent)?s.intent:null,r=ne(t.result.deliveryPackage)?t.result.deliveryPackage:null,o=ne(t.result.deliveryResult)?t.result.deliveryResult:null,i=ne(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 y=yo(p);return y?[y]:[]}):[],f=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(i==null?void 0:i.attachments)?i.attachments.flatMap(p=>ne(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:f,attachments:g}}function Yn({html:t,title:s="Briefing HTML artifact",className:n}){const r=h.useMemo(()=>l.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 X={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 nn(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 jo(t){return t.status==="SUCCESS"?"Complete":t.status==="FAILED"?"Failed":t.status==="RUNNING"?"Running":"Queued"}function ss(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=nn(r.email,"EMAIL"),i=nn(r.slack,"SLACK"),c=[o,i].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",f=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:f,channels:{email:o??void 0,slack:i??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 i=(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(i==="SENT"&&c==="SENT")return"Email and Slack sent";if(i==="SENT"&&c==="FAILED")return"Email sent, Slack failed";if(i==="FAILED"&&c==="SENT")return"Slack sent, email failed";if(i==="SENT")return"Email sent";if(c==="SENT")return"Slack sent";if(i==="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 No(t){return t.status==="SENT"?X.success.surface:t.status==="FAILED"||t.status==="PARTIAL"?X.danger.surface:X.warning.surface}function Zn(t){return t.status==="SUCCESS"?e.jsx(a.Check,{className:a.cn("h-3 w-3",X.success.icon)}):t.status==="FAILED"?e.jsx(a.X,{className:a.cn("h-3 w-3",X.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 wo=[{pattern:/^plan preview/i,label:"Plan preview"},{pattern:/^analysis preview/i,label:"Analysis preview"}];function Co(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:i}of wo){const c=rn(s.find(d=>o.test(d))),u=rn(n.find(d=>o.test(d)));(c||u)&&r.push({label:i,duration:c,toolCalls:u})}return r}function rn(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 an=3;function So({previewPlan:t,previewRun:s,scopeLabel:n}){return e.jsxs("div",{className:"space-y-5","aria-label":"Preview plan",children:[e.jsxs("div",{children:[e.jsx("div",{className:J,children:"What I understood from your brief"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ve,{field:"Datasets",value:e.jsx(zo,{plan:t})}),e.jsx(ve,{field:"Investigate",value:t.understood.investigation}),e.jsx(ve,{field:"Threshold",value:t.understood.threshold}),e.jsx(ve,{field:"Audience",value:t.understood.audience}),e.jsx(ve,{field:"Format",value:t.understood.format,isLast:!0})]})]}),t.scope.grounding?e.jsx(ko,{plan:t}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"What I'll do"}),e.jsx("ol",{className:"space-y-3",children:t.steps.map(r=>e.jsx(qo,{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:J,children:"Scope"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 text-[12px] text-foreground/80",children:[e.jsx(l.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:J,children:"Estimate"}),(()=>{var c;const o=Co(t.estimate).find(u=>u.label.toLowerCase().includes("analysis")),i=(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:i??"—"})})()]})]}),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&&!Ve(s.status)?e.jsx(er,{run:s,labelPrefix:"Preview"}):null]})}function ko({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:J,children:"What I'll analyze"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ve,{field:"Metric",value:s.metric??"Not selected yet"}),e.jsx(ve,{field:"Dataset",value:n}),e.jsx(ve,{field:"Time field",value:s.dateField??"Not selected yet"}),e.jsx(ve,{field:"Breakdown",value:r}),e.jsx(ve,{field:"Confidence",value:`${s.confidence} · ${s.reason}`,isLast:!0})]})]})}function er({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=Ve(t.status),i=n?dt(n.label):`${s?`${s} `:""}${jo(t)}`,c=rr(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"}):Zn(t),e.jsx("span",{className:"font-medium",children:i})]}),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:nr(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 tr({run:t,onRetryRun:s,retryDisabled:n,retryDisabledReason:r,onDeleteRun:o,deletePending:i}){const[c,u]=h.useState(!1),[d,m]=h.useState(!1),f=sr(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",X.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",X.danger.iconBg),children:e.jsx(a.X,{className:a.cn("h-3 w-3",X.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",X.danger.icon),children:p}),f?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:f}):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(l.RefreshCw,{className:"h-3 w-3"}),"Retry"]}):null,o?e.jsxs(l.DropdownMenu,{open:d,onOpenChange:m,children:[e.jsx(l.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(l.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsx(l.DropdownMenuContent,{align:"end",className:"z-[60] w-44",children:e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),m(!1),u(!0)},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(l.Trash2,{className:"h-3.5 w-3.5"}),"Delete run"]})})]}):null]})]}),o?e.jsx(l.AlertDialog,{open:c,onOpenChange:y=>{i||u(y)},children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:"Delete this run record?"}),e.jsx(l.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(l.AlertDialogFooter,{children:[e.jsx(l.AlertDialogCancel,{disabled:i,children:"Cancel"}),e.jsxs(l.AlertDialogAction,{disabled:i,onClick:y=>{y.preventDefault(),o()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[i?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.Trash2,{className:"h-3 w-3"}),"Delete run"]})]})]})}):null]})}function Do({run:t}){const s=ss(t);return!Xn(t.status)||!s||s.status==="SKIPPED"?null:e.jsxs("div",{className:a.cn("rounded-card border px-3 py-2 text-[12px]",No(s)),"aria-label":"Email delivery status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(oe.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 sr(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 Eo(t){const s=ss(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 Io({run:t,onViewOutput:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,deletePending:c}){const u=ss(t),d=sr(t.completedAt??t.startedAt??t.scheduledFor);if(t.status==="FAILED"||(u==null?void 0:u.status)==="FAILED")return e.jsx(tr,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,onDeleteRun:n,deletePending:c});const f=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",X.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",X.success.label),children:[Zn(t),e.jsx("span",{children:Eo(t)}),d?e.jsx("span",{className:"font-normal text-muted-foreground",children:d}):null]}),f?e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:f}):null]}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs("button",{type:"button",className:Ie,onClick:s,children:[e.jsx(l.ExternalLink,{className:"h-3 w-3"}),"View output"]})})]})})}function dt(t){return t.replace(/\s+(started|completed)$/i,"")}function nr(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 on=4;function ln({run:t}){const s=t.progress??null,n=s?Ao(s.recentEvents??[],s.label).slice(-on).reverse():[],r=s!=null&&s.detail&&s.detail!==s.label?s.detail:null,o=rr(t),i=[...n];for(;i.length<on;)i.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:i.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:nr(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 Ao(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 i=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 i)c.set(u.label.trim().toLowerCase(),u);return Array.from(c.values())}function To(){return e.jsx("div",{className:a.cn("border-b px-4 py-2 text-[12px] leading-[1.5]",X.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",X.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 Lo({run:t,onExpand:s}){var o;const n=Jn(t.startedAt),r=(o=t.progress)!=null&&o.label?dt(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:ts(n)}):"Starting…"})]}),e.jsx(l.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 Fo({title:t,durationSeconds:s,status:n,onView:r,onDismiss:o}){const i=n==="success";return e.jsx("div",{className:a.cn("border-b px-4 py-2.5",i?X.success.surface:X.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",i?X.success.iconBg:X.danger.iconBg),children:i?e.jsx(a.Check,{className:a.cn("h-3 w-3",X.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&&i?e.jsxs("p",{className:"mt-0.5 text-[11px] text-foreground/70",children:["Generated in ",ts(s)]}):null]}),i?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(l.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 Ro({run:t}){const s=Jn(t==null?void 0:t.startedAt);return s===null?null:e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",ts(s)]})}function Po({pendingAction:t,previewRun:s,savedActiveRun:n,onShowDetails:r,onCancelSavedRun:o,onMinimizeRun:i,detailsVisible:c}){var S,N,b,T;const u=s&&Ve(s.status)?s:null,d=n;let m=null,f=null,g=!1;if(t==="plan"?(m="Reviewing your brief",f="Reading the brief and planning the analysis…"):t==="preview"?(m="Starting preview run",f="Starting the preview…"):t==="run"?(m="Starting briefing run",f="Preparing the run…"):u?(m=(S=u.progress)!=null&&S.label?dt(u.progress.label):"Running preview",f=((N=u.progress)==null?void 0:N.detail)??null,g=!!u.progress):d&&(m=(b=d.progress)!=null&&b.label?dt(d.progress.label):"Running",f=((T=d.progress)==null?void 0:T.detail)??null,g=!!d.progress),!m)return null;const p=!c&&f,y=d??u,I=!!(d&&i)&&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(Ro,{run:y}),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:f})]}):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,I&&i?e.jsxs("button",{type:"button",onClick:i,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(l.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 rr(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 Mo(t){var s,n;return((n=(s=t.result)==null?void 0:s.limits)==null?void 0:n.previewKind)==="email_package"}function ar({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 Bo({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(i=>!i),"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(l.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:J,children:"Members"}),e.jsx("div",{className:"mt-1.5 space-y-1",children:r.map((i,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:i.label}),i.detail?e.jsx("div",{className:"truncate text-muted-foreground",children:i.detail}):null]},`${i.type}-${i.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(ar,{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 or({markdown:t,className:s}){return e.jsx("div",{className:a.cn("text-[13px] leading-[1.6] text-foreground ",s),children:e.jsx(l.Markdown,{remarkPlugins:[l.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 ns({preview:t,onExpand:s}){var i;const[n,r]=h.useState("rendered"),o=!!((i=t.bodyHtml)!=null&&i.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(Bo,{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(l.Maximize2,{className:"h-3.5 w-3.5"})}):null]}):null]}),n==="html"&&o?e.jsx(Yn,{html:t.bodyHtml??"",title:"Briefing email HTML preview",className:"h-[620px] rounded-none border-0"}):e.jsx(or,{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(ar,{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 $e(t){if(!ne(t))return null;const s=t.text;return typeof s=="string"?s:null}function Vo(t){return t.type==="header"||t.type==="section"?$e(t.text):t.type==="context"&&Array.isArray(t.elements)&&t.elements.map(n=>ne(n)?$e(n):null).filter(n=>!!n).join(" · ")||null}function Oo(t){return t.flatMap(s=>s.type!=="actions"||!Array.isArray(s.elements)?[]:s.elements.flatMap(n=>{if(!ne(n))return[];const r=$e(n.text);return r?[r]:[]}))}function Uo(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 Vt({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 $o({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(l.Hash,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:n})]})}function _o({preview:t,onExpand:s,trustLine:n,reactions:r}){const o=Uo(t.blocks),i=o.header?$e(o.header.text):null,c=o.context?Vo(o.context):null,u=o.sections.map(g=>$e(g.text)).filter(g=>!!g),d=o.actions?Oo([o.actions]):[],[m,f]=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(Ut,{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($o,{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(l.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(Vt,{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"})]}),i?e.jsx("div",{className:"mt-2 text-[13.5px] font-semibold leading-[1.35] text-foreground",children:i}):null,c?e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:c}):null,(i||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:()=>f(g=>!g),className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-foreground/80 hover:underline",children:[e.jsx(Vt,{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(Vt,{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(J,"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 ve({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 zo({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(l.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 qo({order:t,title:s,detail:n,optional:r}){const[o,i]=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-${an}`),style:o?void 0:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:an,overflow:"hidden"},children:n}),n.length>220?e.jsx("button",{type:"button",onClick:()=>i(c=>!c),className:"mt-0.5 text-[11px] text-foreground/60 hover:text-foreground",children:o?"Show less":"Show all fields"}):null]}):null]})]})}function cn({previewRun:t,onExpand:s,fullWidth:n}){var m,f,g,p,y;const r=t.result,o=(m=r==null?void 0:r.artifactPreview)==null?void 0:m.markdown,i=(f=r==null?void 0:r.artifactPreview)==null?void 0:f.html,c=Mo(t),u=c?go((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"?bo(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",X.success.label),children:[e.jsx("span",{className:a.cn("h-1.5 w-1.5 rounded-full",X.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(Je,"h-6 px-1.5 text-[11px]"),"aria-label":"Expand preview to a larger view",children:[e.jsx(l.Maximize2,{className:"h-3 w-3"}),"Expand"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:J,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(ns,{preview:u,onExpand:s}):d?e.jsx(_o,{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(or,{markdown:o})}):i?e.jsx(Yn,{html:i,title:"Briefing preview HTML artifact",className:n?"h-[820px]":"h-[680px]"}):e.jsx("div",{className:"rounded-card border border-dashed border-border px-4 py-6 text-center text-[12px] text-muted-foreground",children:"No rendered briefing artifact is available for this preview yet."}),(y=r==null?void 0:r.warnings)!=null&&y.length&&!c?e.jsx("div",{className:"rounded-card border border-border bg-muted px-3 py-2 text-[11px] leading-[1.55] text-muted-foreground",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:r.warnings.join(" ")})]})}):null]})}function dn({run:t,onExpand:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,deletePending:c}){const u=Qn(t),d=t.status==="FAILED";return e.jsxs("div",{className:"space-y-4","aria-label":"Briefing run result",children:[d?e.jsx(tr,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,onDeleteRun:n,deletePending:c}):null,u?e.jsxs("div",{children:[e.jsx("div",{className:J,children:"Email"}),e.jsx("div",{className:"mt-2",children:e.jsx(ns,{preview:u,onExpand:s})})]}):null,!u&&ne(t.result)&&typeof t.result.summary=="string"?e.jsxs("div",{children:[e.jsx("div",{className:J,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(Do,{run:t}),e.jsx(er,{run:t,labelPrefix:"Run"})]})}function Ho({previewRun:t,isStale:s,onViewOutput:n}){var o,i;const r=((o=t.result)==null?void 0:o.title)??((i=t.result)==null?void 0:i.summary)??"Generated briefing preview";return e.jsx("div",{className:a.cn("rounded-card border px-3 py-2",X.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",X.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:Ie,onClick:n,children:[e.jsx(l.ExternalLink,{className:"h-3 w-3"}),"View output"]})]})})}function rt(t,s){return t.includes(s)?t:[...t,s]}function Ko(t,s){const n=t.filter(r=>r!==s);return n.length>0?n:[s]}const Wo={createBriefing:Dn,updateBriefing:ht,pauseBriefing:Gt,resumeBriefing:Xt,deleteBriefing:Jt,getBriefing:Wt,runBriefingNow:Qt,getBriefingRun:Yt,cancelBriefingRun:Tn,deleteBriefingRun:Ln,previewBriefingPlan:En,runBriefingPreview:In,getBriefingPreviewRun:An,polishBriefingText:Fn},un=2e3,Go=10*6e4,Xo=20*6e4;function Jo(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function ge(t){return t instanceof Error&&t.message?t.message:"Something went wrong. Please try again."}function Qo(t,s){return`${t.replace(/\/$/,"")}${s}`}function Yo(t,s){if(!t)return s;try{return new URL(s,new URL(t).origin).toString()}catch{return s}}async function Ot(t,s,n,r){const o=await fetch(Qo(t,n),{cache:"no-store",...r,headers:{...(r==null?void 0:r.headers)??{},Authorization:`Bearer ${s}`}}),i=await o.json().catch(()=>({}));if(!o.ok){const c=i&&typeof i=="object"&&"error"in i?String(i.error):"Request failed";throw new Error(c)}return i}function ir(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 mn(t){if(t.briefing)return Ue(t.briefing);const s=ir(t.briefing,t.sourceContext);return Wn({source:s.source,name:s.source.type==="dashboard"?"Dashboard Briefing":"Project Briefing",instruction:Kt,...t.defaultRecipient?{delivery:{recipients:[t.defaultRecipient],channels:["EMAIL"]}}:{}})}function Zo(t){return t==="PAUSED"||t==="DISABLED"?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"}function lr({apiServiceUrl:t,token:s,briefing:n,sourceContext:r,title:o="Briefing",className:i,client:c,generateRequestId:u=Jo,onSaved:d,onDeleted:m,onRunStarted:f,onCancel:g,onBack:p,onMinimizeRun:y}){var Es,Is,As,Ts,Ls,Fs,Rs;const{authToken:I,tokenProps:S}=l.useSemaphorContext(),{currentUser:N}=l.useCurrentUserInfo(),b=a.useDashboardStore(x=>x.dashboard),T=a.useDashboardStore(x=>x.theme),j=a.useDashboardStore(x=>x.selectedSheetId),C=a.useDashboardStore(x=>x.filterValues),A=a.useDashboardStore(x=>x.controlValues),V=a.useDashboardStore(x=>x.semanticExecutionPayload),L=a.useDashboardStore(x=>x.cardControlValuesMap),D=a.useDashboardStore(x=>x.inlineFilterValuesMap),R=a.useDashboardStore(x=>x.dashboardInputValues),_=a.useInteractionStore(x=>x.interactionStates),M=t??(S==null?void 0:S.apiServiceUrl),z=s??(I==null?void 0:I.accessToken),U=h.useMemo(()=>({...Wo,...c}),[c]),B=h.useMemo(()=>ir(n,r),[n,r]),W=h.useMemo(()=>fo(N),[N]),[E,me]=h.useState(n??null),[w,q]=h.useState(()=>mn({briefing:n,sourceContext:B,defaultRecipient:W})),[te,Q]=h.useState(null),[be,pe]=h.useState([]),[ye,O]=h.useState(null),[Le,we]=h.useState(null),[je,Fe]=h.useState(null),[H,fe]=h.useState(null),[Ae,$]=h.useState(0),[Y,_e]=h.useState(null),[rs,k]=h.useState(!1),[P,se]=h.useState("edit"),[ce,xe]=h.useState(0),[Oe,mr]=h.useState(!1),[hr,xt]=h.useState("EMAIL"),[xr,pt]=h.useState(!1),[as,ft]=h.useState(null),[pr,gt]=h.useState(!1),[re,fr]=h.useState(null),[bt,os]=h.useState([]),[Ye,is]=h.useState(!1),[ls,cs]=h.useState(null),[gr,br]=h.useState(0),[Re,Ze]=h.useState(null),[yr,yt]=h.useState(!1),[jt,ds]=h.useState(!1),[us,ms]=h.useState(null),[ze,vt]=h.useState(null);h.useEffect(()=>{if(!ze)return;const x=window.setTimeout(()=>vt(null),12e3);return()=>window.clearTimeout(x)},[ze]);const hs=h.useRef(void 0),{activeRunId:jr,resetTerminalRun:xs,startRun:Nt,stop:wt}=Ht({apiServiceUrl:M,token:z,intervalMs:un,timeoutMs:Xo,fetchRun:({apiServiceUrl:x,token:v,runId:F})=>{if(!(E!=null&&E.id))throw new Error("Missing saved Briefing id for run polling.");return U.getBriefingRun(x,v,E.id,F)},onRun:x=>{we(x)},onTerminalRun:x=>{se("result"),O(null)},onError:x=>{O(`Unable to refresh briefing run status: ${ge(x)}`)},onTimeout:()=>{O("Briefing run status refresh timed out. Refresh the run to check the latest status.")}}),{activeRunId:vr,startRun:Nr,stop:ps}=Ht({apiServiceUrl:M,token:z,intervalMs:un,timeoutMs:Go,fetchRun:({apiServiceUrl:x,token:v,runId:F})=>U.getBriefingPreviewRun(x,v,F),onRun:x=>{fe(x),x.status==="SUCCESS"&&_e(v=>v??Ae)},onTerminalRun:x=>{x.status==="FAILED"?O(x.error||"Briefing preview failed."):(O(null),se("result"))},onError:x=>{O(`Unable to refresh briefing preview status: ${ge(x)}`)},onTimeout:x=>{fe(v=>(v==null?void 0:v.id)===x?{...v,status:"FAILED",completedAt:v.completedAt??new Date().toISOString(),error:v.error||"Briefing preview status refresh timed out."}:v),O("Briefing preview status refresh timed out.")}}),ae=!!(E!=null&&E.id),Ct=(E==null?void 0:E.status)==="PAUSED"||w.schedule.status==="PAUSED",wr=ae&&!!(E!=null&&E.scheduleExpr||w.schedule.enabled),Pe=Le??(E==null?void 0:E.latestRun)??null,de=Pe&&Ve(Pe.status)&&jr===Pe.id?Pe:null,he=Pe&&Xn(Pe.status)?Pe:null,ue=P==="result"&&((H==null?void 0:H.status)==="SUCCESS"||he)?"result":P==="plan"&&je?"plan":"edit",Cr=B.detail??(w.source.type==="dashboard"?(b==null?void 0:b.title)??null:"All project data available to this token"),fs=(E==null?void 0:E.status)??w.schedule.status,St=H!==null&&Ve(H.status)&&vr===H.id||de!==null,Te=te!==null||St,Sr=ue==="edit"&&he!==null&&!St,kt=(H==null?void 0:H.status)==="SUCCESS"&&H.result?H:null,kr=kt!==null&&Y!==null&&Y!==Ae,qe=as==="preview"?H:null,Ce=as==="saved"?he:null,He=Ce?Qn(Ce):null,Dr=((Es=qe==null?void 0:qe.result)==null?void 0:Es.title)??(He==null?void 0:He.subject)??(ne(Ce==null?void 0:Ce.result)&&typeof Ce.result.title=="string"?Ce.result.title:null)??(E==null?void 0:E.name)??"Briefing preview",et=h.useMemo(()=>({dashboard:b,theme:T||"light",filters:b==null?void 0:b.filters,selectedSheetId:j,filterValues:C,inlineFilterValuesMap:D,controlValues:A,controlDefinitions:(b==null?void 0:b.controls)||[],dashboardControls:(b==null?void 0:b.controls)||[],cardControlValuesMap:L,dashboardInputValues:R,semanticExecutionPayload:V,interactionStates:_}),[L,A,b,R,C,_,D,V,j,T]);h.useEffect(()=>{const x=(n==null?void 0:n.id)??null;if(hs.current===x)return;hs.current=x,xs(),wt(),ps(),me(n??null);let v=mn({briefing:n,sourceContext:B,defaultRecipient:W}),F=null;if(!n){const Ps=nt.findIndex(Ee=>Ee.label==="Business review"&&(!Ee.available||Ee.available(v.source))),$r=nt.findIndex(Ee=>!Ee.available||Ee.available(v.source)),Tt=Ps!==-1?Ps:$r;if(Tt!==-1){const Ee=nt[Tt];v=at(v,Ee.draft(v.source,{attachments:Ee.seedsDashboardAttachment?$s({source:v.source,dashboard:b,selectedSheetId:j,runtime:et}):void 0})),F=Tt}}q(v),xe(F),we(null),Fe(null),fe(null),_e(null);const G=(n==null?void 0:n.latestRun)??null;O(null),se("edit"),G&&Ve(G.status)&&Nt(G)},[et,n,b,W,xs,B,j,Nt,ps,wt]);const Dt=w.delivery.channels.includes("EMAIL"),Se=w.delivery.channels.includes("SLACK"),Ke=Dt&&Se,K=(As=(Is=w.delivery.channelConfigs)==null?void 0:Is.SLACK)==null?void 0:As.slackConfig,gs=((Ts=K==null?void 0:K.destination)==null?void 0:Ts.type)==="channel"?K.destination.channelId??"":"",ke=bt.find(x=>x.id===gs),tt=(K==null?void 0:K.threadMentions)??[],bs=tt.length>0,ys=JSON.stringify({recipients:tt}),st=Se&&!Dt?"SLACK":Dt&&!Se?"EMAIL":hr,Et=st==="EMAIL"?"SLACK":"EMAIL";h.useEffect(()=>{if(!M||!z||!Se)return;let x=!1;return is(!0),cs(null),Promise.all([Ot(M,z,"/v1/integrations/SLACK/status"),Ot(M,z,"/v1/integrations/slack/channels").catch(v=>{if(v instanceof Error&&/not configured/i.test(v.message))return{channels:[]};throw v})]).then(([v,F])=>{x||(fr(v),os(F.channels))}).catch(v=>{x||(cs(ge(v)),os([]))}).finally(()=>{x||is(!1)}),()=>{x=!0}},[Se,M,z,gr]),h.useEffect(()=>{if(!M||!z||!Se){Ze(null);return}if(!bs||!(re!=null&&re.installed)){Ze(null);return}let x=!1;return Ot(M,z,"/v1/integrations/slack/mention-status",{method:"POST",headers:{"Content-Type":"application/json"},body:ys}).then(v=>{x||Ze(v)}).catch(()=>{x||Ze(null)}),()=>{x=!0}},[Se,bs,M,z,re==null?void 0:re.installed,ys]);const ee=x=>{q(v=>at(v,x)),pe([]),O(null),E!=null&&E.id||(Fe(null),$(v=>v+1),se("edit"))},De=()=>!M||!z?(O("Missing Semaphor API credentials."),null):{apiServiceUrl:M,token:z},Er=async x=>{const v=qt(w);if(pe(v.issues),O(null),!v.valid)return null;const F=De();if(!F)return null;x!=null&&x.pendingAction&&Q(x.pendingAction);try{const G=E!=null&&E.id?await U.updateBriefing(F.apiServiceUrl,F.token,E.id,Gn(w)):await U.createBriefing(F.apiServiceUrl,F.token,zt(w));return me(G.briefing),q(Ue(G.briefing)),d==null||d(G.briefing),G.briefing}catch(G){return O(ge(G)),null}finally{x!=null&&x.pendingAction&&Q(null)}},Ir=async()=>Er({pendingAction:"save"}),js=()=>{const x=qt(w);return pe(x.issues),O(null),x.valid?zt(w):null},vs=async x=>{const v=De();if(!v)return null;const F=js();if(!F)return null;Q("plan");try{const G=await U.previewBriefingPlan(v.apiServiceUrl,v.token,F);return Fe(G.plan),x!=null&&x.silent||se("plan"),G.plan}catch(G){return O(ge(G)),null}finally{Q(null)}},Ar=async()=>{const x=De();if(!x)return;const v=js();if(v)try{const F=je??await vs({silent:!0});if(!F)return;Q("preview");const G=await U.runBriefingPreview(x.apiServiceUrl,x.token,{draft:v,planId:F.id,requestId:u()});_e(Ae),Nr(G.previewRun)}catch(F){O(ge(F))}finally{Q(null)}},It=async()=>{const x=De();if(x){if(!(E!=null&&E.id)){await Ar();return}if(Me){O("Save your changes before running this briefing.");return}Q("run"),O(null),fe(null);try{const v=await U.runBriefingNow(x.apiServiceUrl,x.token,E.id,{requestId:u()});Nt(v.run),f==null||f(v)}catch(v){O(ge(v))}finally{Q(null)}}},Ns=async()=>{if(!(E!=null&&E.id))return null;const x=De();if(!x)return null;const v=await U.getBriefing(x.apiServiceUrl,x.token,E.id);return me(v.briefing),q(Ue(v.briefing)),d==null||d(v.briefing),v.briefing},Tr=async()=>{if(!(E!=null&&E.id)||!(de!=null&&de.id))return;const x=De();if(x){Q("cancelRun"),O(null);try{const v=await U.cancelBriefingRun(x.apiServiceUrl,x.token,E.id,de.id);wt(),we(v.run),se("result"),await Ns().catch(()=>null)}catch(v){O(ge(v))}finally{Q(null)}}},Lr=()=>{!E||!de||y==null||y({briefing:{...E,latestRun:de},run:de})},Fr=async()=>{if(!w.instruction.trim())return;const v=De();if(v){ds(!0),ms(null);try{const F=await U.polishBriefingText(v.apiServiceUrl,v.token,w.instruction),G=w.instruction;ee({instruction:F}),vt({previousText:G})}catch(F){ms(ge(F))}finally{ds(!1)}}},Rr=()=>{ze&&(ee({instruction:ze.previousText}),vt(null))},ws=async x=>{if(!(E!=null&&E.id))return;const v=De();if(v){Q("deleteRun"),O(null);try{await U.deleteBriefingRun(v.apiServiceUrl,v.token,E.id,x);const F=await Ns().catch(()=>null),G=(F==null?void 0:F.latestRun)??null;we(G),G||se("edit")}catch(F){O(ge(F))}finally{Q(null)}}},Pr=async x=>{if(!(E!=null&&E.id))return;const v=De();if(v){Q(x==="PAUSED"?"pause":"resume"),O(null);try{const F=x==="PAUSED"?await U.pauseBriefing(v.apiServiceUrl,v.token,E.id):await U.resumeBriefing(v.apiServiceUrl,v.token,E.id);me(F.briefing),q(Ue(F.briefing)),d==null||d(F.briefing)}catch(F){O(ge(F))}finally{Q(null)}}},Mr=w.instruction.split(`
106
- `).map(x=>x.trim()).find(x=>x.length>0),Cs=h.useMemo(()=>E?Ue(E):null,[E]),Me=!!Cs&&JSON.stringify(w)!==JSON.stringify(Cs),Be=w.body.type==="custom_message",At=Be?"Note":"Analysis",We=Be?"Email body":"What should this briefing investigate?",Ss=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.",ks=Be?"Plain note — sent as-is in the email body. No analysis is generated for this preset.":"Write this like instructions to an analyst — what to watch, when to bother the team, and what to include in the briefing.",Ds=x=>{var v,F;if(xt(x),x==="EMAIL"){ee({delivery:{channels:rt(w.delivery.channels,"EMAIL")}});return}ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((v=w.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:((F=K==null?void 0:K.destination)==null?void 0:F.type)==="channel"?K.destination:{type:"channel",channelId:""},postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Br=()=>{if(Ke){ee({delivery:{channels:Ko(w.delivery.channels,Et)}});return}Ds(Et)},Vr=x=>{var F;const v=bt.find(G=>G.id===x);xt("SLACK"),ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((F=w.delivery.channelConfigs)==null?void 0:F.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:{type:"channel",channelId:x,...v?{channelName:v.name}:{},...v?{isPrivate:v.isPrivate}:{}},postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Or=x=>{var v,F;xt("SLACK"),ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((v=w.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:((F=K==null?void 0:K.destination)==null?void 0:F.type)==="channel"?K.destination:{type:"channel",channelId:""},threadMentions:x,postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Ur=h.useMemo(()=>{const x=w.schedule.enabled?w.schedule.scheduleExpr||"Scheduled":"On demand",v=w.delivery.recipients.length,F=v===0?"No email recipients":`${v} email recipient${v===1?"":"s"}`,G=ke?`#${ke.name}`:"Slack channel";return Ke?`${x} · ${F} · ${G}`:Se?`${x} · ${ke?`#${ke.name}`:"Slack channel"}`:`${x} · ${F}`},[w.delivery.recipients.length,w.schedule.enabled,w.schedule.scheduleExpr,Ke,Se,ke]);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",i),"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(l.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:[ae?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]",Zo(fs)),children:fs}):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]})]}),ue!=="edit"?e.jsxs("button",{type:"button",onClick:()=>se("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:Mr||w.name||"Untitled briefing"}),e.jsx("div",{className:"mt-0.5 truncate text-[10px] text-muted-foreground",children:Ur})]}),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,de?e.jsx(To,{}):null,e.jsx(Po,{pendingAction:te,previewRun:H,savedActiveRun:de,detailsVisible:Oe,onShowDetails:()=>mr(x=>!x),onCancelSavedRun:de?Tr:void 0,onMinimizeRun:de&&y?Lr:void 0}),Oe&&H&&Ve(H.status)?e.jsx(ln,{run:H}):Oe&&de?e.jsx(ln,{run:de}):null,e.jsx("div",{className:"flex-1 space-y-5 overflow-y-auto px-4 py-4",children:ue==="edit"?e.jsxs(e.Fragment,{children:[ae?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Start from"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:nt.map((x,v)=>{if(x.available&&!x.available(w.source))return null;const F=ce===v;return e.jsx("button",{type:"button",onClick:()=>{xe(v),ee(x.draft(w.source,{attachments:x.seedsDashboardAttachment?$s({source:w.source,dashboard:b,selectedSheetId:j,runtime:et}):void 0}))},className:a.cn("inline-flex h-6 items-center rounded-control border px-2 text-[11px] transition-colors",F?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"),"aria-label":`${x.label} preset — ${x.description}`,children:x.label},x.label)})})]}),kt?e.jsx(Ho,{previewRun:kt,isStale:kr,onViewOutput:()=>se("result")}):null,Sr&&he?e.jsx(Io,{run:he,onViewOutput:()=>se("result"),onDeleteRun:he.status==="FAILED"?()=>ws(he.id):void 0,onRetryRun:he.status==="FAILED"&&ae?()=>{It()}:void 0,retryDisabled:Te||ae&&Me,retryDisabledReason:ae&&Me?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:te==="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:J,children:At}),e.jsx("button",{type:"button",onClick:()=>yt(!0),"aria-label":`Expand ${At.toLowerCase()}`,title:`Expand ${At.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(l.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:w.name,onChange:x=>{xe(null),ee({name:x.target.value})},placeholder:"Weekly revenue briefing"}),e.jsx("label",{htmlFor:"briefing-instruction",className:"sr-only",children:We}),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:w.instruction,onChange:x=>{xe(null),ee({instruction:x.target.value})},placeholder:Ss,"aria-label":We}),e.jsx("p",{className:"mt-2 text-[11px] leading-[1.5] text-muted-foreground",children:ks})]}),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:[w.source.type==="dashboard"&&w.attachments.length===0?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:Te,onClick:()=>gt(!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(l.Paperclip,{className:"h-3 w-3"}),"Attach"]}),e.jsx("span",{className:"text-border",children:"·"})]}):null,e.jsx(oo,{includeEvidence:w.output.includeEvidence,includeSql:w.output.includeSql,includeHtml:w.output.artifactFormats.includes("html"),onChange:(x,v)=>{ee(x==="evidence"?{output:{includeEvidence:v}}:x==="sql"?{output:{includeSql:v}}:{output:{artifactFormats:io(w.output.artifactFormats,"html",v)}})}})]})]}),e.jsx(l.Dialog,{open:yr,onOpenChange:yt,children:e.jsxs(l.DialogContent,{className:"flex h-[80vh] max-h-[800px] w-[92vw] max-w-[860px] flex-col gap-0 p-0",children:[e.jsxs(l.DialogHeader,{className:"border-b border-border/60 px-5 py-3",children:[e.jsx(l.DialogTitle,{className:"text-[14px] font-semibold",children:We}),e.jsx(l.DialogDescription,{className:"text-[12px] text-muted-foreground",children:ks})]}),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:We}),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:w.instruction,onChange:x=>{xe(null),ee({instruction:x.target.value})},placeholder:Ss,"aria-label":We})]}),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:us?e.jsx("span",{className:"text-destructive",children:us}):ze?e.jsxs("button",{type:"button",onClick:Rr,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(fn,{className:"h-3 w-3"}),"Revert polish"]}):null}),e.jsxs("button",{type:"button",onClick:Fr,disabled:jt||!w.instruction.trim()||!M||!z,title:"Fix typos, grammar, and minor wording without changing your meaning",className:Ie,children:[jt?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.Sparkles,{className:"h-3 w-3"}),jt?"Polishing…":"Polish"]}),e.jsx("button",{type:"button",onClick:()=>yt(!1),className:Ie,children:"Done"})]})]})}),w.source.type==="dashboard"?e.jsxs("div",{children:[w.attachments.length>0?e.jsx(Wa,{attachments:w.attachments,disabled:Te,onAdd:()=>gt(!0),onChange:x=>ee({attachments:x.map(Ne)})}):null,e.jsx(Qa,{open:pr,onOpenChange:gt,source:w.source,dashboard:b,selectedSheetId:j,runtime:et,selectedAttachments:w.attachments,onSubmit:x=>ee({attachments:x})})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"When"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{label:"On demand only",description:"Save the briefing and run it manually when needed.",checked:!w.schedule.enabled,onSelect:()=>ee({schedule:{enabled:!1}}),name:"briefing-schedule-mode"}),e.jsx(Ws,{label:"Scheduled",description:"Store the cadence so the runner picks it up later.",checked:w.schedule.enabled,onSelect:()=>ee({schedule:{enabled:!0}}),name:"briefing-schedule-mode"})]}),w.schedule.enabled?e.jsx("div",{className:"mt-3 pl-6",children:e.jsx(lo,{scheduleExpr:w.schedule.scheduleExpr||l.buildScheduleExpr(l.DEFAULT_SCHEDULE_VM),timezone:w.schedule.timezone||"UTC",onScheduleChange:x=>ee({schedule:{scheduleExpr:x.scheduleExpr,timezone:x.timezone}})})}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"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(x=>{const v=w.delivery.channels.includes(x),F=st===x;return e.jsxs("button",{type:"button",onClick:()=>Ds(x),"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",F&&v&&"ring-1 ring-foreground/20"),children:[x==="EMAIL"?e.jsx(xn,{className:"h-3 w-3"}):e.jsx(Ut,{className:"h-3 w-3"}),x==="EMAIL"?"Email":"Slack"]},x)})}),e.jsxs("button",{type:"button",onClick:Br,className:a.cn(Je,"h-6 px-1.5 text-[11px]"),children:[Ke?"- Remove":"+ Also send"," ",Et==="EMAIL"?"Email":"Slack"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Who hears about it"}),st==="EMAIL"?e.jsx(qs,{value:w.delivery.recipients,onChange:x=>ee({delivery:{recipients:x}})}):re===null&&Ye?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…"]}):re!=null&&re.installed?e.jsxs("div",{className:"space-y-2",children:[e.jsx(xo,{channels:bt,selectedChannelId:gs,onChange:Vr,destinationKind:"channel",onDestinationKindChange:()=>{},loading:Ye}),e.jsx(qs,{value:tt,onChange:Or,prefix:"Thread @",placeholder:tt.length>0?"Add more…":"Mention people in the thread reply"}),Re&&Re.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:[Re.unlinkedCount," of"," ",Re.linkedCount+Re.unlinkedCount," ",Re.linkedCount+Re.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:((Rs=re==null?void 0:re.workspace)==null?void 0:Rs.teamName)??"Slack"}),ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{children:ke.isMember?`Bot in #${ke.name}`:`Can post to #${ke.name}`})]}):null]}),ls?e.jsx("p",{className:"text-[11px] text-destructive",children:ls}):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(Ut,{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:(Ls=re==null?void 0:re.capabilities)!=null&&Ls.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:[(Fs=re==null?void 0:re.capabilities)!=null&&Fs.canConfigure?e.jsx("a",{href:Yo(M,"/admin/integrations/slack"),target:"_blank",rel:"noopener noreferrer",className:Ys,children:"Connect Slack"}):null,e.jsxs("button",{type:"button",onClick:()=>br(x=>x+1),disabled:Ye,className:Ie,children:[Ye?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.RefreshCw,{className:"h-3 w-3"}),"Refresh"]})]})]})]}),Be?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Scope"}),e.jsx(ho,{source:w.source,resolvedSourceContext:B,sourceDetail:Cr,onChange:x=>ee({source:x})})]}),e.jsxs("div",{className:"flex items-start gap-2 border-t border-border/60 pt-3 text-[11px] leading-[1.55] text-muted-foreground",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Runs with"," ",e.jsx("span",{className:"text-foreground/80",children:"your permissions"}),Ke?". Email recipients see only what they’re allowed to see. Slack channel posts are visible to everyone in the channel.":st==="SLACK"?". Channel posts are visible to everyone in the channel.":". Recipients see only what they’re allowed to see."]})]})]}):ue==="plan"&&je?e.jsx(So,{previewPlan:je,previewRun:H&&H.status!=="SUCCESS"?H:null,scopeLabel:B.source.type==="dashboard"?(b==null?void 0:b.title)??B.label:B.label}):ue==="result"&&H?e.jsx(cn,{previewRun:H,onExpand:()=>{ft("preview"),pt(!0)}}):ue==="result"&&he?e.jsx(dn,{run:he,onExpand:()=>{ft("saved"),pt(!0)},onDeleteRun:he.status==="FAILED"?()=>ws(he.id):void 0,onRetryRun:he.status==="FAILED"&&ae?()=>{It()}:void 0,retryDisabled:Te||ae&&Me,retryDisabledReason:ae&&Me?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:te==="deleteRun"}):null}),be.length>0||ye?e.jsxs("div",{className:"shrink-0 space-y-2 border-t border-destructive/30 bg-destructive/10 px-4 py-2.5",children:[be.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:be.map(x=>e.jsx("li",{className:"list-disc marker:text-destructive/60",children:x.message},`${x.field}:${x.message}`))})]}):null,ye?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:ye})]}):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:ae&&wr?e.jsxs("button",{type:"button",className:Ie,disabled:Te,onClick:()=>Pr(Ct?"ACTIVE":"PAUSED"),children:[te==="pause"||te==="resume"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):Ct?e.jsx(l.Play,{className:"h-3 w-3"}):e.jsx(pn,{className:"h-3 w-3"}),Ct?"Resume":"Pause"]}):!ae&&(ue==="plan"||ue==="result")?e.jsxs("button",{type:"button",className:Je,onClick:()=>se("edit"),children:[e.jsx(l.ChevronRight,{className:"h-3 w-3 rotate-180"}),ue==="result"?"Edit brief":"Tweak brief"]}):!ae&&g&&!p?e.jsx("button",{type:"button",className:Je,onClick:g,children:"Discard"}):null}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ae&&ue==="edit"&&!Be?e.jsxs("button",{type:"button",className:Ie,disabled:Te,onClick:()=>{vs()},children:[te==="plan"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(qr,{className:"h-3 w-3"}),"Preview plan"]}):null,e.jsxs("button",{type:"button",className:Ie,disabled:Te||ae&&Me,onClick:It,title:ae&&Me?"Save your changes before running — Run now uses the saved briefing.":void 0,children:[te==="run"||te==="preview"||St?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):ue==="result"?e.jsx(l.RefreshCw,{className:"h-3 w-3"}):ue==="plan"?e.jsx($t,{className:"h-3 w-3"}):ae?e.jsx(l.Send,{className:"h-3 w-3"}):e.jsx($t,{className:"h-3 w-3"}),ae?"Run now":ue==="plan"?"Run plan":ue==="result"?"Run again":"Show preview"]}),e.jsxs("button",{type:"button",className:ae?Ie:Ys,disabled:Te,onClick:Ir,children:[te==="save"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(a.Check,{className:"h-3 w-3"}),ae?"Save changes":"Create briefing"]})]})]})}),e.jsx(l.Dialog,{open:xr,onOpenChange:x=>{pt(x),x||ft(null)},children:e.jsxs(l.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(l.DialogHeader,{className:"border-b border-border px-6 py-3 text-left",children:[e.jsx(l.DialogTitle,{className:"truncate text-[14px] font-semibold leading-5",children:Dr}),e.jsx(l.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:qe?e.jsx(cn,{previewRun:qe,fullWidth:!0}):He?e.jsx(ns,{preview:He}):Ce?e.jsx(dn,{run:Ce}):null})]})})]})}function cr({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(Hr,{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 ei={listBriefings:kn,getBriefing:Wt,pauseBriefing:Gt,resumeBriefing:Xt,deleteBriefing:Jt,runBriefingNow:Qt},ti="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",si="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",dr="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 ni(t){return(t==null?void 0:t.trim())||"This dashboard"}function ri(t){return t==="This dashboard"?"Watch this dashboard":`Watch ${t}`}function ai(t,s){return t.source.type==="dashboard"&&t.source.dashboardId===s}function oi(t){return t==="dashboard"?"This dashboard":"Project"}function ii(t,s,n){return s==="dashboard"?t.filter(r=>ai(r,n)):t}async function li({apiClient:t,apiServiceUrl:s,token:n}){const o=[];let i=1,c=0,u=Number.POSITIVE_INFINITY;for(;c<u;){const d=await t.listBriefings(s,n,{scope:"organization",page:i,pageSize:100}),m=d.briefings;if(o.push(...m),c+=m.length,u=d.total,m.length===0||c>=u)break;i+=1}return o}function ci(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 i=Math.round(o/24);if(i<7)return`${i}d ago`;const c=Math.round(i/7);return c<5?`${c}w ago`:`${Math.round(i/30)}mo ago`}function di(t){return t.scheduleExpr?t.scheduleExpr:"On demand"}function ui(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 ur(t){return t.hasActiveRun?"Running":t.lastRunStatus?`Last run ${t.lastRunStatus.toString().toLowerCase()}`:"Idle"}function mi(t){return t.source.type==="dashboard"?"This dashboard":"Project"}function hi({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:oi(n)},n)})})}function xi({briefings:t,dashboardLabel:s,sourceView:n,error:r,loading:o,onSourceViewChange:i,onClose:c,onEdit:u,onNew:d,onRunNow:m,onTogglePause:f,onDelete:g,selectingId:p,busyId:y,manageBriefingsHref:I}){const S=t.length,N=t.filter(j=>j.status==="ACTIVE").length,b=t.find(j=>j.hasActiveRun)??null,T=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:ti,children:"Briefings"}),e.jsx("h2",{className:"mt-0.5 truncate text-[14px] font-semibold leading-5",children:T})]}),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(hi,{activeView:n,onChange:i}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:o&&S===0?e.jsx("span",{children:"Loading briefings…"}):S===0?e.jsx("span",{children:"No briefings yet"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[S," watching"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[N," active"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[o?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,S>0?e.jsxs("button",{onClick:d,className:dr,children:[e.jsx(l.Plus,{className:"h-3 w-3"}),"New briefing"]}):null]})]}),b?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:b.name}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground",children:ur(b)})]}):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(pi,{onNew:d}):null,t.map(j=>e.jsx(gi,{briefing:j,isOpening:p===j.id,isBusy:y===j.id,onOpen:()=>u(j.id),onRunNow:()=>m(j),onTogglePause:()=>f(j),onDelete:()=>g(j)},j.id))]}),I?e.jsx("div",{className:"border-t border-border px-4 py-2.5",children:e.jsxs("a",{href:I,className:a.cn(si,"h-6 px-1 text-[11px]"),children:["Manage all briefings",e.jsx(_r,{className:"h-3 w-3"})]})}):null]})}function pi({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(dr,"mt-4"),children:[e.jsx(l.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 gi({briefing:t,isOpening:s,isBusy:n,onOpen:r,onRunNow:o,onTogglePause:i,onDelete:c}){const u=t.status==="PAUSED",d=t.hasActiveRun,m=ui(t),f=ci(t.lastRunAt),g=t.lastRunStatus,p=g==="SUCCESS"?X.success.dot:g==="FAILED"?X.danger.dot:g?X.warning.dot:X.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:y=>{(y.key==="Enter"||y.key===" ")&&(y.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:mi(t)}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx(l.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 ",f]})]}):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?ur(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(l.DropdownMenu,{children:[e.jsx(l.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",onClick:y=>y.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(l.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(l.DropdownMenuContent,{align:"end",className:"w-44",children:[e.jsxs(l.DropdownMenuItem,{onClick:r,children:[e.jsx(l.Pencil,{className:"h-3.5 w-3.5"}),"Edit briefing"]}),e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),o()},children:[e.jsx($t,{className:"h-3.5 w-3.5"}),"Run now"]}),t.scheduleExpr?e.jsx(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),i()},children:u?e.jsxs(e.Fragment,{children:[e.jsx(l.Play,{className:"h-3.5 w-3.5"}),"Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Pause"]})}):null,e.jsx(l.DropdownMenuSeparator,{}),e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),c()},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(l.Trash2,{className:"h-3.5 w-3.5"}),"Delete briefing"]})]})]})})]})}const bi=2e3,yi=20*6e4;function ji({briefingId:t,initialRun:s,apiServiceUrl:n,token:r,onTerminal:o,onTimeout:i,onExpand:c}){const[u,d]=h.useState(s),{startRun:m}=Ht({apiServiceUrl:n,token:r,intervalMs:bi,timeoutMs:yi,fetchRun:({apiServiceUrl:g,token:p,runId:y})=>Yt(g,p,t,y),onRun:g=>{d(g)},onTerminalRun:g=>{o(g)},onTimeout:()=>{i()}}),f=h.useRef(!1);return h.useEffect(()=>{f.current||(f.current=!0,lt(s.status)?m(s):it(s.status)&&o(s))},[s,o,m]),e.jsx(Lo,{run:u,onExpand:c})}function vi({dashboardId:t,dashboardTitle:s,apiServiceUrl:n,token:r,disabled:o,className:i,manageBriefingsHref:c,client:u}){const{authToken:d,tokenProps:m}=l.useSemaphorContext(),[f,g]=h.useState(!1),[p,y]=h.useState("list"),[I,S]=h.useState("dashboard"),[N,b]=h.useState([]),[T,j]=h.useState(null),[C,A]=h.useState(!1),[V,L]=h.useState(null),[D,R]=h.useState(null),[_,M]=h.useState(null),[z,U]=h.useState(null),[B,W]=h.useState(null),[E,me]=h.useState(null),w=n??(m==null?void 0:m.apiServiceUrl),q=r??(d==null?void 0:d.accessToken),te=h.useMemo(()=>({...ei,...u}),[u]),Q=ni(s),be=h.useMemo(()=>ii(N,I,t),[t,N,I]),pe=h.useMemo(()=>I==="dashboard"?{source:{type:"dashboard",dashboardId:t},label:Q,detail:ri(Q)}:{source:{type:"project"},label:"This project",detail:"Use any data in this project."},[t,Q,I]),ye=!!(w&&q),O=h.useCallback(async()=>{if(!(!w||!q)){A(!0),U(null);try{b(await li({apiClient:te,apiServiceUrl:w,token:q}))}catch($){U($ instanceof Error?$.message:"Could not load briefings.")}finally{A(!1)}}},[te,w,q]);h.useEffect(()=>{!f||p!=="list"||!ye||O()},[ye,O,f,p]);const Le=()=>{j(null),S("dashboard"),y("list"),g(!0)},we=()=>{j(null),y("author")},je=async $=>{if(!(!w||!q)){L($),U(null);try{const Y=await te.getBriefing(w,q,$);j(Y.briefing),y("author")}catch(Y){U(Y instanceof Error?Y.message:"Could not open briefing.")}finally{L(null)}}},Fe=async $=>{if(!(!w||!q)){R($.id);try{await te.runBriefingNow(w,q,$.id,{requestId:Ni()}),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not start the run.")}finally{R(null)}}},H=async $=>{if(!(!w||!q)){R($.id);try{const Y=$.status==="PAUSED"?await te.resumeBriefing(w,q,$.id):await te.pauseBriefing(w,q,$.id);l.ue.success(Y.briefing.status==="PAUSED"?"Briefing paused":"Briefing resumed"),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not update the briefing status.")}finally{R(null)}}},fe=async()=>{if(!_||!w||!q)return;const $=_;R($.id);try{await te.deleteBriefing(w,q,$.id),l.ue.success("Briefing deleted"),M(null),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not delete the briefing.")}finally{R(null)}},Ae=be.length;return e.jsxs(l.Sheet,{open:f,onOpenChange:g,children:[e.jsx(cr,{disabled:o||!ye,briefingCount:Ae,className:i,onClick:Le}),e.jsxs(l.SheetContent,{side:"right",hideClose:!0,className:"flex h-full w-full flex-col overflow-hidden p-0 sm:max-w-[560px]",children:[e.jsxs(l.SheetHeader,{className:"sr-only",children:[e.jsx(l.SheetTitle,{children:"Briefings"}),e.jsx(l.SheetDescription,{children:"Manage briefings for this dashboard."})]}),p==="list"?e.jsx(xi,{briefings:be,dashboardLabel:Q,sourceView:I,error:z,loading:C,onSourceViewChange:S,onClose:()=>g(!1),onEdit:$=>{je($)},onNew:we,onRunNow:$=>{Fe($)},onTogglePause:$=>{H($)},onDelete:$=>M($),selectingId:V,busyId:D,manageBriefingsHref:c}):e.jsx(lr,{apiServiceUrl:w,token:q,briefing:T,sourceContext:T?void 0:pe,title:T?"Edit briefing":"Create briefing",className:"h-full min-h-0 max-w-none border-0 shadow-none",onBack:()=>y("list"),onCancel:()=>g(!1),onDeleted:()=>{l.ue.success("Briefing deleted"),j(null),y("list"),O()},onRunStarted:()=>{},onSaved:$=>{j($),O()},onMinimizeRun:({briefing:$,run:Y})=>{W({briefing:$,run:Y}),g(!1)}})]}),B&&w&&q?e.jsx(ji,{briefingId:B.briefing.id,initialRun:B.run,apiServiceUrl:w,token:q,onTerminal:$=>{me({briefing:B.briefing,run:$}),W(null),O()},onTimeout:()=>{W(null),O()},onExpand:()=>{j(B.briefing),y("author"),W(null),g(!0)}}):null,E?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(Fo,{title:E.run.status==="SUCCESS"?`${E.briefing.name} is ready`:`${E.briefing.name} run failed`,durationSeconds:E.run.startedAt&&E.run.completedAt?Math.max(0,Math.floor((new Date(E.run.completedAt).getTime()-new Date(E.run.startedAt).getTime())/1e3)):null,status:E.run.status==="SUCCESS"?"success":"failed",onView:()=>{j(E.briefing),y("author"),me(null),g(!0)},onDismiss:()=>me(null)})}):null,e.jsx(l.AlertDialog,{open:!!_,onOpenChange:$=>{$||M(null)},children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:"Delete briefing?"}),e.jsxs(l.AlertDialogDescription,{children:["This permanently deletes ",e.jsx("strong",{children:_==null?void 0:_.name}),". Recipients will stop receiving it."]})]}),e.jsxs(l.AlertDialogFooter,{children:[e.jsx(l.AlertDialogCancel,{children:"Cancel"}),e.jsx(l.AlertDialogAction,{className:"bg-destructive/90 hover:bg-destructive",onClick:fe,children:"Delete briefing"})]})]})})]})}function Ni(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-now-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}exports.AdvancedModeToggle=Xr;exports.BriefingAuthor=lr;exports.BriefingsApiError=ut;exports.DashboardBriefingLauncher=vi;exports.DashboardControlsSettings=jn;exports.DashboardFilterControlsButton=Nn;exports.DashboardFilterControlsLauncher=ga;exports.DocumentControlsSettings=vn;exports.ExportNotificationItem=bn;exports.ExportNotificationList=yn;exports.NotificationBell=oa;exports.Undo2=fn;exports.UnsavedChangesAlert=Jr;exports.VisualEditingControls=Gr;exports.WatchDashboardButton=cr;exports.applyBriefingFormPatch=at;exports.briefingFormDraftToCreateRequest=zt;exports.briefingFormDraftToUpdateRequest=Gn;exports.briefingToFormDraft=Ue;exports.cancelBriefingRun=Tn;exports.createBriefing=Dn;exports.createBriefingFormDraft=Wn;exports.deleteBriefing=Jt;exports.deleteBriefingRun=Ln;exports.getBriefing=Wt;exports.getBriefingArtifact=Na;exports.getBriefingEvidence=wa;exports.getBriefingPreviewRun=An;exports.getBriefingRun=Yt;exports.listBriefingRuns=va;exports.listBriefingTenantSummaries=ja;exports.listBriefings=kn;exports.pauseBriefing=Gt;exports.polishBriefingText=Fn;exports.previewBriefingPlan=En;exports.resumeBriefing=Xt;exports.runBriefingNow=Qt;exports.runBriefingPreview=In;exports.updateBriefing=ht;exports.useExportPolling=na;exports.useExportRecovery=ra;exports.validateBriefingFormDraft=qt;
105
+ - Link to the full dashboard`;function io(t,s,n){const r=t.includes("markdown")?t.filter(o=>o!==s):["markdown"];return n?Array.from(new Set([...r,s])):r}const nt=[{label:"Email report",description:"Email body with dashboard attachments",seedsDashboardAttachment:!0,available:t=>t.type==="dashboard",draft:(t,s)=>({name:"Dashboard Email Report",instruction:Js,body:{type:"custom_message",message:Js},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:Kt,body:{type:"generated_analysis",instruction:Kt},output:{includeEvidence:!0,includeSql:!1}})},{label:"Anomaly watch",description:"Only surface unusual movement",draft:()=>({name:"Anomaly Watch Briefing",instruction:Xs,body:{type:"generated_analysis",instruction:Xs},output:{includeEvidence:!0,includeSql:!1}})},{label:"Customer health",description:"Daily watch on at-risk accounts",draft:()=>({name:"Customer Health Watch",instruction:Qs,body:{type:"generated_analysis",instruction:Qs},output:{includeEvidence:!0,includeSql:!1}})},{label:"Slack digest",description:"Short Slack-friendly digest, no PDFs",draft:()=>({name:"Slack Digest",instruction:Ys,body:{type:"generated_analysis",instruction:Ys},output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["SLACK"]}})}],J="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Je="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",Ie="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",Zs="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 lo({scheduleExpr:t,timezone:s,onScheduleChange:n}){const r=h.useMemo(()=>l.parseScheduleExpr(t),[t]),[o,i]=h.useState(()=>ct()),[c,u]=h.useState(null),d=l.buildSchedulePreview(r,s,en(o),c?tn(c):null),[m,f]=h.useState(!1),g=b=>{n({scheduleExpr:l.buildScheduleExpr(b),timezone:s})},p=b=>{const T=b==="weekly"&&r.weekdays.length===0?[1,2,3,4,5]:r.weekdays;g({...r,repeats:b,weekdays:T})},y=(b,T)=>{g({...r,hour:b,minute:T})},I=b=>{g({...r,weekdays:b})},S=`${String(r.hour).padStart(2,"0")}:${String(r.minute).padStart(2,"0")}`,N=h.useMemo(()=>co(),[]);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:J,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(J,"mb-1 block"),children:"Repeats"}),e.jsxs(a.Select,{value:r.repeats,onValueChange:b=>p(b),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:"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(J,"mb-1 block"),children:"Time"}),e.jsxs(a.Select,{value:S,onValueChange:b=>{const[T,j]=b.split(":").map(C=>parseInt(C,10));y(T,j)},children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{className:"max-h-[280px]",children:N.map(({value:b,label:T})=>e.jsx(a.SelectItem,{value:b,children:T},b))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(a.Popover,{open:m,onOpenChange:f,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-expanded":m,className:a.cn(Je,"h-6 px-1.5 text-[11px]"),children:[e.jsx(l.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:b=>b.preventDefault(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:J,children:"More options"}),e.jsx("button",{onClick:()=>f(!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(J,"mb-1 block"),children:"First occurrence"}),e.jsx(sn,{icon:e.jsx(l.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:o,placeholder:"Pick a start date",disabledBefore:ct(),onChange:b=>{b&&i(b)},renderLabel:b=>b?en(b):"Today"})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"Timezone"}),e.jsxs(a.Select,{value:s,onValueChange:b=>n({scheduleExpr:l.buildScheduleExpr(r),timezone:b}),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(l.Globe,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx(a.SelectValue,{})]})}),e.jsx(a.SelectContent,{className:"max-h-[280px]",children:l.COMMON_TIMEZONES.map(b=>e.jsx(a.SelectItem,{value:b,children:uo(b)},b))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"Ends"}),e.jsx(sn,{icon:e.jsx(l.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:b=>b?tn(b):"No end date"})]}),r.repeats==="weekly"?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(J,"mb-1 block"),children:"On these days"}),e.jsx("div",{className:"flex gap-1",children:["S","M","T","W","T","F","S"].map((b,T)=>{const j=r.weekdays.includes(T);return e.jsx("button",{type:"button",onClick:()=>{I(j?r.weekdays.filter(C=>C!==T):[...r.weekdays,T].sort())},className:a.cn("inline-flex h-7 w-7 items-center justify-center rounded-control border text-[11px] font-medium",j?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:border-border"),children:b},T)})})]}):null]})]})})]})}function co(){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:l.formatTimeLabel(s,n)})}return t}function uo(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 ct(){const t=new Date;return t.setHours(0,0,0,0),t}function mo(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function en(t){return mo(t,ct())?"Today":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function tn(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function sn({value:t,icon:s,placeholder:n,clearable:r,clearLabel:o,disabledBefore:i,onChange:c,renderLabel:u}){const[d,m]=h.useState(!1),f=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??f:f})]}),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(l.Calendar$1,{mode:"single",selected:t??void 0,defaultMonth:t??i??ct(),onSelect:p=>{c(p??null),m(!1)},disabled:i?{before:i}: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 ho({source:t,resolvedSourceContext:s,sourceDetail:n,onChange:r}){const[o,i]=h.useState(!1),c=h.useRef(null),u=s.source.type==="dashboard"?s.source:null,d=u!==null;h.useEffect(()=>{if(!o)return;const N=b=>{const T=b.target;c.current&&!c.current.contains(T)&&!(T instanceof Element&&T.closest("[data-scope-popover]"))&&i(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[o]);const m=t.type==="project",f=s.source.type==="dashboard"?s.label??"This dashboard":"This dashboard",g=s.source.type==="dashboard"?s.detail??n??null:n,p="This project",y="Use any data in this project.",I=m?p:f,S=m?y:g;return d?e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:c,type:"button",onClick:()=>i(N=>!N),"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(l.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:I}),S?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground/70","aria-hidden":!0,children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground/70",children:S})]}):null]}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground group-hover:text-foreground",children:["Change",e.jsx(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(nn,{active:!m,label:f,detail:g??null,description:"Use only the datasets this dashboard already reads.",onSelect:()=>{u&&r(u),i(!1)},isLast:!1}),e.jsx(nn,{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"}),i(!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(l.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:I})]}),S?e.jsx("div",{className:"mt-0.5 pl-5 text-[11px] text-muted-foreground",children:S}):null]})}function nn({active:t,label:s,detail:n,description:r,onSelect:o,isLast:i}){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 ",!i&&"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(l.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 xo({channels:t,selectedChannelId:s,onChange:n,destinationKind:r,onDestinationKindChange:o,loading:i,disabled:c,className:u}){const d=h.useRef(null),[m,f]=h.useState(!1),[g,p]=h.useState(""),y=h.useMemo(()=>t.find(b=>b.id===s)??null,[t,s]),I=h.useMemo(()=>{const b=g.trim().toLowerCase();return b?t.filter(T=>T.name.toLowerCase().includes(b)):t},[t,g]),S=r==="dm",N=c||S;return e.jsx("div",{className:a.cn("relative",u),children:e.jsxs(a.Popover,{open:m&&!N,onOpenChange:f,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",N&&"cursor-not-allowed opacity-60"),onClick:()=>{var b;N||((b=d.current)==null||b.focus(),f(!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:b=>b.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"})]})]}),y?e.jsx(po,{channel:y,onRemove:()=>{var b;n(""),(b=d.current)==null||b.focus(),f(!0)}}):null,e.jsx("input",{ref:d,className:"h-6 min-w-[140px] flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground/70 disabled:cursor-not-allowed",value:g,disabled:N,placeholder:S?"DM delivery coming in V2":y?"Change channel…":i?"Loading channels…":"Search channels…",onChange:b=>{p(b.target.value),f(!0)},onFocus:()=>f(!0)})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:b=>b.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:I.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:I.map(b=>{const T=b.id===s;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{n(b.id),p(""),f(!1)},className:a.cn("flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left",T?"bg-muted text-foreground":"text-foreground/85 hover:bg-muted/60"),children:[b.isPrivate?e.jsx(l.Lock,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(l.Hash,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:b.name}),typeof b.memberCount=="number"?e.jsxs("span",{className:"ml-auto text-[11px] text-muted-foreground",children:[b.memberCount," members"]}):null]})},b.id)})})})]})})}function po({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(l.Lock,{className:"h-3 w-3"}):e.jsx(l.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 Xn=it,Ve=lt;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 Jn(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 ss(t){const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`}function ne(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function go(t){if(!ne(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=>!ne(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=>!ne(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,i=Array.isArray(t.attachments)?t.attachments.filter(c=>typeof c=="string"):null;return!s||!n||!r||!o||!i?null:{subject:s,body:n,...typeof t.bodyHtml=="string"&&t.bodyHtml.trim()?{bodyHtml:t.bodyHtml}:{},recipients:r,channels:o,attachments:i,...typeof t.attachmentNotice=="string"?{attachmentNotice:t.attachmentNotice}:{}}}function bo(t){if(!ne(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(ne):null;if(!s||!n||!r)return null;const o=ne(t.thread)?{text:typeof t.thread.text=="string"?t.thread.text:"",blocks:Array.isArray(t.thread.blocks)?t.thread.blocks.filter(ne):[],reply_broadcast:!1}:void 0;return{channel:s,text:n,blocks:r,unfurl_links:!1,unfurl_media:!1,...o?{thread:o}:{}}}function yo(t){if(!ne(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 Qn(t){if(!ne(t.result))return null;const s=ne(t.result.deliveryReadiness)?t.result.deliveryReadiness:null,n=s&&ne(s.intent)?s.intent:null,r=ne(t.result.deliveryPackage)?t.result.deliveryPackage:null,o=ne(t.result.deliveryResult)?t.result.deliveryResult:null,i=ne(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 y=yo(p);return y?[y]:[]}):[],f=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(i==null?void 0:i.attachments)?i.attachments.flatMap(p=>ne(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:f,attachments:g}}function Yn({html:t,title:s="Briefing HTML artifact",className:n}){const r=h.useMemo(()=>l.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 X={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 rn(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 jo(t){return t.status==="SUCCESS"?"Complete":t.status==="FAILED"?"Failed":t.status==="RUNNING"?"Running":"Queued"}function ns(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=rn(r.email,"EMAIL"),i=rn(r.slack,"SLACK"),c=[o,i].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",f=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:f,channels:{email:o??void 0,slack:i??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 i=(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(i==="SENT"&&c==="SENT")return"Email and Slack sent";if(i==="SENT"&&c==="FAILED")return"Email sent, Slack failed";if(i==="FAILED"&&c==="SENT")return"Slack sent, email failed";if(i==="SENT")return"Email sent";if(c==="SENT")return"Slack sent";if(i==="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 No(t){return t.status==="SENT"?X.success.surface:t.status==="FAILED"||t.status==="PARTIAL"?X.danger.surface:X.warning.surface}function Zn(t){return t.status==="SUCCESS"?e.jsx(a.Check,{className:a.cn("h-3 w-3",X.success.icon)}):t.status==="FAILED"?e.jsx(a.X,{className:a.cn("h-3 w-3",X.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 wo=[{pattern:/^plan preview/i,label:"Plan preview"},{pattern:/^analysis preview/i,label:"Analysis preview"}];function Co(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:i}of wo){const c=an(s.find(d=>o.test(d))),u=an(n.find(d=>o.test(d)));(c||u)&&r.push({label:i,duration:c,toolCalls:u})}return r}function an(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 on=3;function So({previewPlan:t,previewRun:s,scopeLabel:n}){return e.jsxs("div",{className:"space-y-5","aria-label":"Preview plan",children:[e.jsxs("div",{children:[e.jsx("div",{className:J,children:"What I understood from your brief"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ve,{field:"Datasets",value:e.jsx(zo,{plan:t})}),e.jsx(ve,{field:"Investigate",value:t.understood.investigation}),e.jsx(ve,{field:"Threshold",value:t.understood.threshold}),e.jsx(ve,{field:"Audience",value:t.understood.audience}),e.jsx(ve,{field:"Format",value:t.understood.format,isLast:!0})]})]}),t.scope.grounding?e.jsx(ko,{plan:t}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"What I'll do"}),e.jsx("ol",{className:"space-y-3",children:t.steps.map(r=>e.jsx(qo,{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:J,children:"Scope"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 text-[12px] text-foreground/80",children:[e.jsx(l.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:J,children:"Estimate"}),(()=>{var c;const o=Co(t.estimate).find(u=>u.label.toLowerCase().includes("analysis")),i=(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:i??"—"})})()]})]}),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&&!Ve(s.status)?e.jsx(er,{run:s,labelPrefix:"Preview"}):null]})}function ko({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:J,children:"What I'll analyze"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(ve,{field:"Metric",value:s.metric??"Not selected yet"}),e.jsx(ve,{field:"Dataset",value:n}),e.jsx(ve,{field:"Time field",value:s.dateField??"Not selected yet"}),e.jsx(ve,{field:"Breakdown",value:r}),e.jsx(ve,{field:"Confidence",value:`${s.confidence} · ${s.reason}`,isLast:!0})]})]})}function er({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=Ve(t.status),i=n?dt(n.label):`${s?`${s} `:""}${jo(t)}`,c=rr(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"}):Zn(t),e.jsx("span",{className:"font-medium",children:i})]}),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:nr(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 tr({run:t,onRetryRun:s,retryDisabled:n,retryDisabledReason:r,onDeleteRun:o,deletePending:i}){const[c,u]=h.useState(!1),[d,m]=h.useState(!1),f=sr(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",X.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",X.danger.iconBg),children:e.jsx(a.X,{className:a.cn("h-3 w-3",X.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",X.danger.icon),children:p}),f?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:f}):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(l.RefreshCw,{className:"h-3 w-3"}),"Retry"]}):null,o?e.jsxs(l.DropdownMenu,{open:d,onOpenChange:m,children:[e.jsx(l.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(l.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsx(l.DropdownMenuContent,{align:"end",className:"z-[60] w-44",children:e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),m(!1),u(!0)},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(l.Trash2,{className:"h-3.5 w-3.5"}),"Delete run"]})})]}):null]})]}),o?e.jsx(l.AlertDialog,{open:c,onOpenChange:y=>{i||u(y)},children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:"Delete this run record?"}),e.jsx(l.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(l.AlertDialogFooter,{children:[e.jsx(l.AlertDialogCancel,{disabled:i,children:"Cancel"}),e.jsxs(l.AlertDialogAction,{disabled:i,onClick:y=>{y.preventDefault(),o()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[i?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.Trash2,{className:"h-3 w-3"}),"Delete run"]})]})]})}):null]})}function Do({run:t}){const s=ns(t);return!Xn(t.status)||!s||s.status==="SKIPPED"?null:e.jsxs("div",{className:a.cn("rounded-card border px-3 py-2 text-[12px]",No(s)),"aria-label":"Email delivery status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(oe.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 sr(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 Eo(t){const s=ns(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 Io({run:t,onViewOutput:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,deletePending:c}){const u=ns(t),d=sr(t.completedAt??t.startedAt??t.scheduledFor);if(t.status==="FAILED"||(u==null?void 0:u.status)==="FAILED")return e.jsx(tr,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,onDeleteRun:n,deletePending:c});const f=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",X.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",X.success.label),children:[Zn(t),e.jsx("span",{children:Eo(t)}),d?e.jsx("span",{className:"font-normal text-muted-foreground",children:d}):null]}),f?e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:f}):null]}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs("button",{type:"button",className:Ie,onClick:s,children:[e.jsx(l.ExternalLink,{className:"h-3 w-3"}),"View output"]})})]})})}function dt(t){return t.replace(/\s+(started|completed)$/i,"")}function nr(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 ln=4;function cn({run:t}){const s=t.progress??null,n=s?Ao(s.recentEvents??[],s.label).slice(-ln).reverse():[],r=s!=null&&s.detail&&s.detail!==s.label?s.detail:null,o=rr(t),i=[...n];for(;i.length<ln;)i.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:i.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:nr(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 Ao(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 i=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 i)c.set(u.label.trim().toLowerCase(),u);return Array.from(c.values())}function To(){return e.jsx("div",{className:a.cn("border-b px-4 py-2 text-[12px] leading-[1.5]",X.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",X.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 Lo({run:t,onExpand:s}){var o;const n=Jn(t.startedAt),r=(o=t.progress)!=null&&o.label?dt(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:ss(n)}):"Starting…"})]}),e.jsx(l.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 Fo({title:t,durationSeconds:s,status:n,onView:r,onDismiss:o}){const i=n==="success";return e.jsx("div",{className:a.cn("border-b px-4 py-2.5",i?X.success.surface:X.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",i?X.success.iconBg:X.danger.iconBg),children:i?e.jsx(a.Check,{className:a.cn("h-3 w-3",X.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&&i?e.jsxs("p",{className:"mt-0.5 text-[11px] text-foreground/70",children:["Generated in ",ss(s)]}):null]}),i?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(l.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 Ro({run:t}){const s=Jn(t==null?void 0:t.startedAt);return s===null?null:e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",ss(s)]})}function Po({pendingAction:t,previewRun:s,savedActiveRun:n,onShowDetails:r,onCancelSavedRun:o,onMinimizeRun:i,detailsVisible:c}){var S,N,b,T;const u=s&&Ve(s.status)?s:null,d=n;let m=null,f=null,g=!1;if(t==="plan"?(m="Reviewing your brief",f="Reading the brief and planning the analysis…"):t==="preview"?(m="Starting preview run",f="Starting the preview…"):t==="run"?(m="Starting briefing run",f="Preparing the run…"):u?(m=(S=u.progress)!=null&&S.label?dt(u.progress.label):"Running preview",f=((N=u.progress)==null?void 0:N.detail)??null,g=!!u.progress):d&&(m=(b=d.progress)!=null&&b.label?dt(d.progress.label):"Running",f=((T=d.progress)==null?void 0:T.detail)??null,g=!!d.progress),!m)return null;const p=!c&&f,y=d??u,I=!!(d&&i)&&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(Ro,{run:y}),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:f})]}):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,I&&i?e.jsxs("button",{type:"button",onClick:i,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(l.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 rr(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 Mo(t){var s,n;return((n=(s=t.result)==null?void 0:s.limits)==null?void 0:n.previewKind)==="email_package"}function ar({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 Bo({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(i=>!i),"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(l.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:J,children:"Members"}),e.jsx("div",{className:"mt-1.5 space-y-1",children:r.map((i,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:i.label}),i.detail?e.jsx("div",{className:"truncate text-muted-foreground",children:i.detail}):null]},`${i.type}-${i.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(ar,{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 or({markdown:t,className:s}){return e.jsx("div",{className:a.cn("text-[13px] leading-[1.6] text-foreground ",s),children:e.jsx(l.Markdown,{remarkPlugins:[l.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 rs({preview:t,onExpand:s}){var i;const[n,r]=h.useState("rendered"),o=!!((i=t.bodyHtml)!=null&&i.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(Bo,{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(l.Maximize2,{className:"h-3.5 w-3.5"})}):null]}):null]}),n==="html"&&o?e.jsx(Yn,{html:t.bodyHtml??"",title:"Briefing email HTML preview",className:"h-[620px] rounded-none border-0"}):e.jsx(or,{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(ar,{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 $e(t){if(!ne(t))return null;const s=t.text;return typeof s=="string"?s:null}function Vo(t){return t.type==="header"||t.type==="section"?$e(t.text):t.type==="context"&&Array.isArray(t.elements)&&t.elements.map(n=>ne(n)?$e(n):null).filter(n=>!!n).join(" · ")||null}function Oo(t){return t.flatMap(s=>s.type!=="actions"||!Array.isArray(s.elements)?[]:s.elements.flatMap(n=>{if(!ne(n))return[];const r=$e(n.text);return r?[r]:[]}))}function Uo(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 Vt({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 $o({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(l.Hash,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:n})]})}function _o({preview:t,onExpand:s,trustLine:n,reactions:r}){const o=Uo(t.blocks),i=o.header?$e(o.header.text):null,c=o.context?Vo(o.context):null,u=o.sections.map(g=>$e(g.text)).filter(g=>!!g),d=o.actions?Oo([o.actions]):[],[m,f]=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(Ut,{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($o,{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(l.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(Vt,{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"})]}),i?e.jsx("div",{className:"mt-2 text-[13.5px] font-semibold leading-[1.35] text-foreground",children:i}):null,c?e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:c}):null,(i||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:()=>f(g=>!g),className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-foreground/80 hover:underline",children:[e.jsx(Vt,{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(Vt,{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(J,"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 ve({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 zo({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(l.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 qo({order:t,title:s,detail:n,optional:r}){const[o,i]=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-${on}`),style:o?void 0:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:on,overflow:"hidden"},children:n}),n.length>220?e.jsx("button",{type:"button",onClick:()=>i(c=>!c),className:"mt-0.5 text-[11px] text-foreground/60 hover:text-foreground",children:o?"Show less":"Show all fields"}):null]}):null]})]})}function dn({previewRun:t,onExpand:s,fullWidth:n}){var m,f,g,p,y;const r=t.result,o=(m=r==null?void 0:r.artifactPreview)==null?void 0:m.markdown,i=(f=r==null?void 0:r.artifactPreview)==null?void 0:f.html,c=Mo(t),u=c?go((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"?bo(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",X.success.label),children:[e.jsx("span",{className:a.cn("h-1.5 w-1.5 rounded-full",X.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(Je,"h-6 px-1.5 text-[11px]"),"aria-label":"Expand preview to a larger view",children:[e.jsx(l.Maximize2,{className:"h-3 w-3"}),"Expand"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:J,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(rs,{preview:u,onExpand:s}):d?e.jsx(_o,{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(or,{markdown:o})}):i?e.jsx(Yn,{html:i,title:"Briefing preview HTML artifact",className:n?"h-[820px]":"h-[680px]"}):e.jsx("div",{className:"rounded-card border border-dashed border-border px-4 py-6 text-center text-[12px] text-muted-foreground",children:"No rendered briefing artifact is available for this preview yet."}),(y=r==null?void 0:r.warnings)!=null&&y.length&&!c?e.jsx("div",{className:"rounded-card border border-border bg-muted px-3 py-2 text-[11px] leading-[1.55] text-muted-foreground",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:r.warnings.join(" ")})]})}):null]})}function un({run:t,onExpand:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,deletePending:c}){const u=Qn(t),d=t.status==="FAILED";return e.jsxs("div",{className:"space-y-4","aria-label":"Briefing run result",children:[d?e.jsx(tr,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:i,onDeleteRun:n,deletePending:c}):null,u?e.jsxs("div",{children:[e.jsx("div",{className:J,children:"Email"}),e.jsx("div",{className:"mt-2",children:e.jsx(rs,{preview:u,onExpand:s})})]}):null,!u&&ne(t.result)&&typeof t.result.summary=="string"?e.jsxs("div",{children:[e.jsx("div",{className:J,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(Do,{run:t}),e.jsx(er,{run:t,labelPrefix:"Run"})]})}function Ho({previewRun:t,isStale:s,onViewOutput:n}){var o,i;const r=((o=t.result)==null?void 0:o.title)??((i=t.result)==null?void 0:i.summary)??"Generated briefing preview";return e.jsx("div",{className:a.cn("rounded-card border px-3 py-2",X.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",X.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:Ie,onClick:n,children:[e.jsx(l.ExternalLink,{className:"h-3 w-3"}),"View output"]})]})})}function rt(t,s){return t.includes(s)?t:[...t,s]}function Ko(t,s){const n=t.filter(r=>r!==s);return n.length>0?n:[s]}const Wo={createBriefing:Dn,updateBriefing:ht,pauseBriefing:Xt,resumeBriefing:Jt,deleteBriefing:Qt,getBriefing:Gt,runBriefingNow:Yt,getBriefingRun:Zt,cancelBriefingRun:Tn,deleteBriefingRun:Ln,previewBriefingPlan:En,runBriefingPreview:In,getBriefingPreviewRun:An,polishBriefingText:Fn},mn=2e3,Go=10*6e4,Xo=20*6e4;function Jo(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function ge(t){return t instanceof Error&&t.message?t.message:"Something went wrong. Please try again."}function Qo(t,s){return`${t.replace(/\/$/,"")}${s}`}function Yo(t,s){if(!t)return s;try{return new URL(s,new URL(t).origin).toString()}catch{return s}}async function Ot(t,s,n,r){const o=await fetch(Qo(t,n),{cache:"no-store",...r,headers:{...(r==null?void 0:r.headers)??{},Authorization:`Bearer ${s}`}}),i=await o.json().catch(()=>({}));if(!o.ok){const c=i&&typeof i=="object"&&"error"in i?String(i.error):"Request failed";throw new Error(c)}return i}function ir(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 hn(t){if(t.briefing)return Ue(t.briefing);const s=ir(t.briefing,t.sourceContext);return Wn({source:s.source,name:s.source.type==="dashboard"?"Dashboard Briefing":"Project Briefing",instruction:Kt,...t.defaultRecipient?{delivery:{recipients:[t.defaultRecipient],channels:["EMAIL"]}}:{}})}function Zo(t){return t==="PAUSED"||t==="DISABLED"?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"}function lr({apiServiceUrl:t,token:s,briefing:n,sourceContext:r,title:o="Briefing",className:i,client:c,generateRequestId:u=Jo,onSaved:d,onDeleted:m,onRunStarted:f,onCancel:g,onBack:p,onMinimizeRun:y}){var Is,As,Ts,Ls,Fs,Rs,Ps;const{authToken:I,tokenProps:S}=l.useSemaphorContext(),{currentUser:N}=l.useCurrentUserInfo(),b=a.useDashboardStore(x=>x.dashboard),T=a.useDashboardStore(x=>x.theme),j=a.useDashboardStore(x=>x.selectedSheetId),C=a.useDashboardStore(x=>x.filterValues),A=a.useDashboardStore(x=>x.controlValues),V=a.useDashboardStore(x=>x.semanticExecutionPayload),L=a.useDashboardStore(x=>x.cardControlValuesMap),D=a.useDashboardStore(x=>x.inlineFilterValuesMap),R=a.useDashboardStore(x=>x.dashboardInputValues),_=a.useInteractionStore(x=>x.interactionStates),M=t??(S==null?void 0:S.apiServiceUrl),z=s??(I==null?void 0:I.accessToken),U=h.useMemo(()=>({...Wo,...c}),[c]),B=h.useMemo(()=>ir(n,r),[n,r]),W=h.useMemo(()=>fo(N),[N]),[E,me]=h.useState(n??null),[w,q]=h.useState(()=>hn({briefing:n,sourceContext:B,defaultRecipient:W})),[te,Q]=h.useState(null),[be,pe]=h.useState([]),[ye,O]=h.useState(null),[Le,we]=h.useState(null),[je,Fe]=h.useState(null),[H,fe]=h.useState(null),[Ae,$]=h.useState(0),[Y,_e]=h.useState(null),[as,k]=h.useState(!1),[P,se]=h.useState("edit"),[ce,xe]=h.useState(0),[Oe,mr]=h.useState(!1),[hr,xt]=h.useState("EMAIL"),[xr,pt]=h.useState(!1),[os,ft]=h.useState(null),[pr,gt]=h.useState(!1),[re,fr]=h.useState(null),[bt,is]=h.useState([]),[Ye,ls]=h.useState(!1),[cs,ds]=h.useState(null),[gr,br]=h.useState(0),[Re,Ze]=h.useState(null),[yr,yt]=h.useState(!1),[jt,us]=h.useState(!1),[ms,hs]=h.useState(null),[ze,vt]=h.useState(null);h.useEffect(()=>{if(!ze)return;const x=window.setTimeout(()=>vt(null),12e3);return()=>window.clearTimeout(x)},[ze]);const xs=h.useRef(void 0),{activeRunId:jr,resetTerminalRun:ps,startRun:Nt,stop:wt}=Ht({apiServiceUrl:M,token:z,intervalMs:mn,timeoutMs:Xo,fetchRun:({apiServiceUrl:x,token:v,runId:F})=>{if(!(E!=null&&E.id))throw new Error("Missing saved Briefing id for run polling.");return U.getBriefingRun(x,v,E.id,F)},onRun:x=>{we(x)},onTerminalRun:x=>{se("result"),O(null)},onError:x=>{O(`Unable to refresh briefing run status: ${ge(x)}`)},onTimeout:()=>{O("Briefing run status refresh timed out. Refresh the run to check the latest status.")}}),{activeRunId:vr,startRun:Nr,stop:fs}=Ht({apiServiceUrl:M,token:z,intervalMs:mn,timeoutMs:Go,fetchRun:({apiServiceUrl:x,token:v,runId:F})=>U.getBriefingPreviewRun(x,v,F),onRun:x=>{fe(x),x.status==="SUCCESS"&&_e(v=>v??Ae)},onTerminalRun:x=>{x.status==="FAILED"?O(x.error||"Briefing preview failed."):(O(null),se("result"))},onError:x=>{O(`Unable to refresh briefing preview status: ${ge(x)}`)},onTimeout:x=>{fe(v=>(v==null?void 0:v.id)===x?{...v,status:"FAILED",completedAt:v.completedAt??new Date().toISOString(),error:v.error||"Briefing preview status refresh timed out."}:v),O("Briefing preview status refresh timed out.")}}),ae=!!(E!=null&&E.id),Ct=(E==null?void 0:E.status)==="PAUSED"||w.schedule.status==="PAUSED",wr=ae&&!!(E!=null&&E.scheduleExpr||w.schedule.enabled),Pe=Le??(E==null?void 0:E.latestRun)??null,de=Pe&&Ve(Pe.status)&&jr===Pe.id?Pe:null,he=Pe&&Xn(Pe.status)?Pe:null,ue=P==="result"&&((H==null?void 0:H.status)==="SUCCESS"||he)?"result":P==="plan"&&je?"plan":"edit",Cr=B.detail??(w.source.type==="dashboard"?(b==null?void 0:b.title)??null:"All project data available to this token"),gs=(E==null?void 0:E.status)??w.schedule.status,St=H!==null&&Ve(H.status)&&vr===H.id||de!==null,Te=te!==null||St,Sr=ue==="edit"&&he!==null&&!St,kt=(H==null?void 0:H.status)==="SUCCESS"&&H.result?H:null,kr=kt!==null&&Y!==null&&Y!==Ae,qe=os==="preview"?H:null,Ce=os==="saved"?he:null,He=Ce?Qn(Ce):null,Dr=((Is=qe==null?void 0:qe.result)==null?void 0:Is.title)??(He==null?void 0:He.subject)??(ne(Ce==null?void 0:Ce.result)&&typeof Ce.result.title=="string"?Ce.result.title:null)??(E==null?void 0:E.name)??"Briefing preview",et=h.useMemo(()=>({dashboard:b,theme:T||"light",filters:b==null?void 0:b.filters,selectedSheetId:j,filterValues:C,inlineFilterValuesMap:D,controlValues:A,controlDefinitions:(b==null?void 0:b.controls)||[],dashboardControls:(b==null?void 0:b.controls)||[],cardControlValuesMap:L,dashboardInputValues:R,semanticExecutionPayload:V,interactionStates:_}),[L,A,b,R,C,_,D,V,j,T]);h.useEffect(()=>{const x=(n==null?void 0:n.id)??null;if(xs.current===x)return;xs.current=x,ps(),wt(),fs(),me(n??null);let v=hn({briefing:n,sourceContext:B,defaultRecipient:W}),F=null;if(!n){const Ms=nt.findIndex(Ee=>Ee.label==="Business review"&&(!Ee.available||Ee.available(v.source))),$r=nt.findIndex(Ee=>!Ee.available||Ee.available(v.source)),Tt=Ms!==-1?Ms:$r;if(Tt!==-1){const Ee=nt[Tt];v=at(v,Ee.draft(v.source,{attachments:Ee.seedsDashboardAttachment?_s({source:v.source,dashboard:b,selectedSheetId:j,runtime:et}):void 0})),F=Tt}}q(v),xe(F),we(null),Fe(null),fe(null),_e(null);const G=(n==null?void 0:n.latestRun)??null;O(null),se("edit"),G&&Ve(G.status)&&Nt(G)},[et,n,b,W,ps,B,j,Nt,fs,wt]);const Dt=w.delivery.channels.includes("EMAIL"),Se=w.delivery.channels.includes("SLACK"),Ke=Dt&&Se,K=(Ts=(As=w.delivery.channelConfigs)==null?void 0:As.SLACK)==null?void 0:Ts.slackConfig,bs=((Ls=K==null?void 0:K.destination)==null?void 0:Ls.type)==="channel"?K.destination.channelId??"":"",ke=bt.find(x=>x.id===bs),tt=(K==null?void 0:K.threadMentions)??[],ys=tt.length>0,js=JSON.stringify({recipients:tt}),st=Se&&!Dt?"SLACK":Dt&&!Se?"EMAIL":hr,Et=st==="EMAIL"?"SLACK":"EMAIL";h.useEffect(()=>{if(!M||!z||!Se)return;let x=!1;return ls(!0),ds(null),Promise.all([Ot(M,z,"/v1/integrations/SLACK/status"),Ot(M,z,"/v1/integrations/slack/channels").catch(v=>{if(v instanceof Error&&/not configured/i.test(v.message))return{channels:[]};throw v})]).then(([v,F])=>{x||(fr(v),is(F.channels))}).catch(v=>{x||(ds(ge(v)),is([]))}).finally(()=>{x||ls(!1)}),()=>{x=!0}},[Se,M,z,gr]),h.useEffect(()=>{if(!M||!z||!Se){Ze(null);return}if(!ys||!(re!=null&&re.installed)){Ze(null);return}let x=!1;return Ot(M,z,"/v1/integrations/slack/mention-status",{method:"POST",headers:{"Content-Type":"application/json"},body:js}).then(v=>{x||Ze(v)}).catch(()=>{x||Ze(null)}),()=>{x=!0}},[Se,ys,M,z,re==null?void 0:re.installed,js]);const ee=x=>{q(v=>at(v,x)),pe([]),O(null),E!=null&&E.id||(Fe(null),$(v=>v+1),se("edit"))},De=()=>!M||!z?(O("Missing Semaphor API credentials."),null):{apiServiceUrl:M,token:z},Er=async x=>{const v=qt(w);if(pe(v.issues),O(null),!v.valid)return null;const F=De();if(!F)return null;x!=null&&x.pendingAction&&Q(x.pendingAction);try{const G=E!=null&&E.id?await U.updateBriefing(F.apiServiceUrl,F.token,E.id,Gn(w)):await U.createBriefing(F.apiServiceUrl,F.token,zt(w));return me(G.briefing),q(Ue(G.briefing)),d==null||d(G.briefing),G.briefing}catch(G){return O(ge(G)),null}finally{x!=null&&x.pendingAction&&Q(null)}},Ir=async()=>Er({pendingAction:"save"}),vs=()=>{const x=qt(w);return pe(x.issues),O(null),x.valid?zt(w):null},Ns=async x=>{const v=De();if(!v)return null;const F=vs();if(!F)return null;Q("plan");try{const G=await U.previewBriefingPlan(v.apiServiceUrl,v.token,F);return Fe(G.plan),x!=null&&x.silent||se("plan"),G.plan}catch(G){return O(ge(G)),null}finally{Q(null)}},Ar=async()=>{const x=De();if(!x)return;const v=vs();if(v)try{const F=je??await Ns({silent:!0});if(!F)return;Q("preview");const G=await U.runBriefingPreview(x.apiServiceUrl,x.token,{draft:v,planId:F.id,requestId:u()});_e(Ae),Nr(G.previewRun)}catch(F){O(ge(F))}finally{Q(null)}},It=async()=>{const x=De();if(x){if(!(E!=null&&E.id)){await Ar();return}if(Me){O("Save your changes before running this briefing.");return}Q("run"),O(null),fe(null);try{const v=await U.runBriefingNow(x.apiServiceUrl,x.token,E.id,{requestId:u()});Nt(v.run),f==null||f(v)}catch(v){O(ge(v))}finally{Q(null)}}},ws=async()=>{if(!(E!=null&&E.id))return null;const x=De();if(!x)return null;const v=await U.getBriefing(x.apiServiceUrl,x.token,E.id);return me(v.briefing),q(Ue(v.briefing)),d==null||d(v.briefing),v.briefing},Tr=async()=>{if(!(E!=null&&E.id)||!(de!=null&&de.id))return;const x=De();if(x){Q("cancelRun"),O(null);try{const v=await U.cancelBriefingRun(x.apiServiceUrl,x.token,E.id,de.id);wt(),we(v.run),se("result"),await ws().catch(()=>null)}catch(v){O(ge(v))}finally{Q(null)}}},Lr=()=>{!E||!de||y==null||y({briefing:{...E,latestRun:de},run:de})},Fr=async()=>{if(!w.instruction.trim())return;const v=De();if(v){us(!0),hs(null);try{const F=await U.polishBriefingText(v.apiServiceUrl,v.token,w.instruction),G=w.instruction;ee({instruction:F}),vt({previousText:G})}catch(F){hs(ge(F))}finally{us(!1)}}},Rr=()=>{ze&&(ee({instruction:ze.previousText}),vt(null))},Cs=async x=>{if(!(E!=null&&E.id))return;const v=De();if(v){Q("deleteRun"),O(null);try{await U.deleteBriefingRun(v.apiServiceUrl,v.token,E.id,x);const F=await ws().catch(()=>null),G=(F==null?void 0:F.latestRun)??null;we(G),G||se("edit")}catch(F){O(ge(F))}finally{Q(null)}}},Pr=async x=>{if(!(E!=null&&E.id))return;const v=De();if(v){Q(x==="PAUSED"?"pause":"resume"),O(null);try{const F=x==="PAUSED"?await U.pauseBriefing(v.apiServiceUrl,v.token,E.id):await U.resumeBriefing(v.apiServiceUrl,v.token,E.id);me(F.briefing),q(Ue(F.briefing)),d==null||d(F.briefing)}catch(F){O(ge(F))}finally{Q(null)}}},Mr=w.instruction.split(`
106
+ `).map(x=>x.trim()).find(x=>x.length>0),Ss=h.useMemo(()=>E?Ue(E):null,[E]),Me=!!Ss&&JSON.stringify(w)!==JSON.stringify(Ss),Be=w.body.type==="custom_message",At=Be?"Note":"Analysis",We=Be?"Email body":"What should this briefing investigate?",ks=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.",Ds=Be?"Plain note — sent as-is in the email body. No analysis is generated for this preset.":"Write this like instructions to an analyst — what to watch, when to bother the team, and what to include in the briefing.",Es=x=>{var v,F;if(xt(x),x==="EMAIL"){ee({delivery:{channels:rt(w.delivery.channels,"EMAIL")}});return}ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((v=w.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:((F=K==null?void 0:K.destination)==null?void 0:F.type)==="channel"?K.destination:{type:"channel",channelId:""},postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Br=()=>{if(Ke){ee({delivery:{channels:Ko(w.delivery.channels,Et)}});return}Es(Et)},Vr=x=>{var F;const v=bt.find(G=>G.id===x);xt("SLACK"),ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((F=w.delivery.channelConfigs)==null?void 0:F.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:{type:"channel",channelId:x,...v?{channelName:v.name}:{},...v?{isPrivate:v.isPrivate}:{}},postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Or=x=>{var v,F;xt("SLACK"),ee({delivery:{channels:rt(w.delivery.channels,"SLACK"),channelConfigs:{...w.delivery.channelConfigs??{},SLACK:{...((v=w.delivery.channelConfigs)==null?void 0:v.SLACK)??{},formatProfile:"concise",slackConfig:{...K??{},destination:((F=K==null?void 0:K.destination)==null?void 0:F.type)==="channel"?K.destination:{type:"channel",channelId:""},threadMentions:x,postThreadDetail:(K==null?void 0:K.postThreadDetail)??!0,includeDashboardLink:!0,includeBriefingLink:!0}}}}})},Ur=h.useMemo(()=>{const x=w.schedule.enabled?w.schedule.scheduleExpr||"Scheduled":"On demand",v=w.delivery.recipients.length,F=v===0?"No email recipients":`${v} email recipient${v===1?"":"s"}`,G=ke?`#${ke.name}`:"Slack channel";return Ke?`${x} · ${F} · ${G}`:Se?`${x} · ${ke?`#${ke.name}`:"Slack channel"}`:`${x} · ${F}`},[w.delivery.recipients.length,w.schedule.enabled,w.schedule.scheduleExpr,Ke,Se,ke]);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",i),"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(l.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:[ae?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]",Zo(gs)),children:gs}):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]})]}),ue!=="edit"?e.jsxs("button",{type:"button",onClick:()=>se("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:Mr||w.name||"Untitled briefing"}),e.jsx("div",{className:"mt-0.5 truncate text-[10px] text-muted-foreground",children:Ur})]}),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,de?e.jsx(To,{}):null,e.jsx(Po,{pendingAction:te,previewRun:H,savedActiveRun:de,detailsVisible:Oe,onShowDetails:()=>mr(x=>!x),onCancelSavedRun:de?Tr:void 0,onMinimizeRun:de&&y?Lr:void 0}),Oe&&H&&Ve(H.status)?e.jsx(cn,{run:H}):Oe&&de?e.jsx(cn,{run:de}):null,e.jsx("div",{className:"flex-1 space-y-5 overflow-y-auto px-4 py-4",children:ue==="edit"?e.jsxs(e.Fragment,{children:[ae?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Start from"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:nt.map((x,v)=>{if(x.available&&!x.available(w.source))return null;const F=ce===v;return e.jsx("button",{type:"button",onClick:()=>{xe(v),ee(x.draft(w.source,{attachments:x.seedsDashboardAttachment?_s({source:w.source,dashboard:b,selectedSheetId:j,runtime:et}):void 0}))},className:a.cn("inline-flex h-6 items-center rounded-control border px-2 text-[11px] transition-colors",F?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"),"aria-label":`${x.label} preset — ${x.description}`,children:x.label},x.label)})})]}),kt?e.jsx(Ho,{previewRun:kt,isStale:kr,onViewOutput:()=>se("result")}):null,Sr&&he?e.jsx(Io,{run:he,onViewOutput:()=>se("result"),onDeleteRun:he.status==="FAILED"?()=>Cs(he.id):void 0,onRetryRun:he.status==="FAILED"&&ae?()=>{It()}:void 0,retryDisabled:Te||ae&&Me,retryDisabledReason:ae&&Me?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:te==="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:J,children:At}),e.jsx("button",{type:"button",onClick:()=>yt(!0),"aria-label":`Expand ${At.toLowerCase()}`,title:`Expand ${At.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(l.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:w.name,onChange:x=>{xe(null),ee({name:x.target.value})},placeholder:"Weekly revenue briefing"}),e.jsx("label",{htmlFor:"briefing-instruction",className:"sr-only",children:We}),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:w.instruction,onChange:x=>{xe(null),ee({instruction:x.target.value})},placeholder:ks,"aria-label":We}),e.jsx("p",{className:"mt-2 text-[11px] leading-[1.5] text-muted-foreground",children:Ds})]}),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:[w.source.type==="dashboard"&&w.attachments.length===0?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:Te,onClick:()=>gt(!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(l.Paperclip,{className:"h-3 w-3"}),"Attach"]}),e.jsx("span",{className:"text-border",children:"·"})]}):null,e.jsx(oo,{includeEvidence:w.output.includeEvidence,includeSql:w.output.includeSql,includeHtml:w.output.artifactFormats.includes("html"),onChange:(x,v)=>{ee(x==="evidence"?{output:{includeEvidence:v}}:x==="sql"?{output:{includeSql:v}}:{output:{artifactFormats:io(w.output.artifactFormats,"html",v)}})}})]})]}),e.jsx(l.Dialog,{open:yr,onOpenChange:yt,children:e.jsxs(l.DialogContent,{className:"flex h-[80vh] max-h-[800px] w-[92vw] max-w-[860px] flex-col gap-0 p-0",children:[e.jsxs(l.DialogHeader,{className:"border-b border-border/60 px-5 py-3",children:[e.jsx(l.DialogTitle,{className:"text-[14px] font-semibold",children:We}),e.jsx(l.DialogDescription,{className:"text-[12px] text-muted-foreground",children:Ds})]}),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:We}),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:w.instruction,onChange:x=>{xe(null),ee({instruction:x.target.value})},placeholder:ks,"aria-label":We})]}),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:ms?e.jsx("span",{className:"text-destructive",children:ms}):ze?e.jsxs("button",{type:"button",onClick:Rr,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(gn,{className:"h-3 w-3"}),"Revert polish"]}):null}),e.jsxs("button",{type:"button",onClick:Fr,disabled:jt||!w.instruction.trim()||!M||!z,title:"Fix typos, grammar, and minor wording without changing your meaning",className:Ie,children:[jt?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.Sparkles,{className:"h-3 w-3"}),jt?"Polishing…":"Polish"]}),e.jsx("button",{type:"button",onClick:()=>yt(!1),className:Ie,children:"Done"})]})]})}),w.source.type==="dashboard"?e.jsxs("div",{children:[w.attachments.length>0?e.jsx(Wa,{attachments:w.attachments,disabled:Te,onAdd:()=>gt(!0),onChange:x=>ee({attachments:x.map(Ne)})}):null,e.jsx(Qa,{open:pr,onOpenChange:gt,source:w.source,dashboard:b,selectedSheetId:j,runtime:et,selectedAttachments:w.attachments,onSubmit:x=>ee({attachments:x})})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"When"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Gs,{label:"On demand only",description:"Save the briefing and run it manually when needed.",checked:!w.schedule.enabled,onSelect:()=>ee({schedule:{enabled:!1}}),name:"briefing-schedule-mode"}),e.jsx(Gs,{label:"Scheduled",description:"Store the cadence so the runner picks it up later.",checked:w.schedule.enabled,onSelect:()=>ee({schedule:{enabled:!0}}),name:"briefing-schedule-mode"})]}),w.schedule.enabled?e.jsx("div",{className:"mt-3 pl-6",children:e.jsx(lo,{scheduleExpr:w.schedule.scheduleExpr||l.buildScheduleExpr(l.DEFAULT_SCHEDULE_VM),timezone:w.schedule.timezone||"UTC",onScheduleChange:x=>ee({schedule:{scheduleExpr:x.scheduleExpr,timezone:x.timezone}})})}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"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(x=>{const v=w.delivery.channels.includes(x),F=st===x;return e.jsxs("button",{type:"button",onClick:()=>Es(x),"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",F&&v&&"ring-1 ring-foreground/20"),children:[x==="EMAIL"?e.jsx(pn,{className:"h-3 w-3"}):e.jsx(Ut,{className:"h-3 w-3"}),x==="EMAIL"?"Email":"Slack"]},x)})}),e.jsxs("button",{type:"button",onClick:Br,className:a.cn(Je,"h-6 px-1.5 text-[11px]"),children:[Ke?"- Remove":"+ Also send"," ",Et==="EMAIL"?"Email":"Slack"]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Who hears about it"}),st==="EMAIL"?e.jsx(Hs,{value:w.delivery.recipients,onChange:x=>ee({delivery:{recipients:x}})}):re===null&&Ye?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…"]}):re!=null&&re.installed?e.jsxs("div",{className:"space-y-2",children:[e.jsx(xo,{channels:bt,selectedChannelId:bs,onChange:Vr,destinationKind:"channel",onDestinationKindChange:()=>{},loading:Ye}),e.jsx(Hs,{value:tt,onChange:Or,prefix:"Thread @",placeholder:tt.length>0?"Add more…":"Mention people in the thread reply"}),Re&&Re.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:[Re.unlinkedCount," of"," ",Re.linkedCount+Re.unlinkedCount," ",Re.linkedCount+Re.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:((Ps=re==null?void 0:re.workspace)==null?void 0:Ps.teamName)??"Slack"}),ke?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{children:ke.isMember?`Bot in #${ke.name}`:`Can post to #${ke.name}`})]}):null]}),cs?e.jsx("p",{className:"text-[11px] text-destructive",children:cs}):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(Ut,{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:(Fs=re==null?void 0:re.capabilities)!=null&&Fs.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:[(Rs=re==null?void 0:re.capabilities)!=null&&Rs.canConfigure?e.jsx("a",{href:Yo(M,"/admin/integrations/slack"),target:"_blank",rel:"noopener noreferrer",className:Zs,children:"Connect Slack"}):null,e.jsxs("button",{type:"button",onClick:()=>br(x=>x+1),disabled:Ye,className:Ie,children:[Ye?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(l.RefreshCw,{className:"h-3 w-3"}),"Refresh"]})]})]})]}),Be?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(J,"mb-2"),children:"Scope"}),e.jsx(ho,{source:w.source,resolvedSourceContext:B,sourceDetail:Cr,onChange:x=>ee({source:x})})]}),e.jsxs("div",{className:"flex items-start gap-2 border-t border-border/60 pt-3 text-[11px] leading-[1.55] text-muted-foreground",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsxs("span",{children:["Runs with"," ",e.jsx("span",{className:"text-foreground/80",children:"your permissions"}),Ke?". Email recipients see only what they’re allowed to see. Slack channel posts are visible to everyone in the channel.":st==="SLACK"?". Channel posts are visible to everyone in the channel.":". Recipients see only what they’re allowed to see."]})]})]}):ue==="plan"&&je?e.jsx(So,{previewPlan:je,previewRun:H&&H.status!=="SUCCESS"?H:null,scopeLabel:B.source.type==="dashboard"?(b==null?void 0:b.title)??B.label:B.label}):ue==="result"&&H?e.jsx(dn,{previewRun:H,onExpand:()=>{ft("preview"),pt(!0)}}):ue==="result"&&he?e.jsx(un,{run:he,onExpand:()=>{ft("saved"),pt(!0)},onDeleteRun:he.status==="FAILED"?()=>Cs(he.id):void 0,onRetryRun:he.status==="FAILED"&&ae?()=>{It()}:void 0,retryDisabled:Te||ae&&Me,retryDisabledReason:ae&&Me?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:te==="deleteRun"}):null}),be.length>0||ye?e.jsxs("div",{className:"shrink-0 space-y-2 border-t border-destructive/30 bg-destructive/10 px-4 py-2.5",children:[be.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:be.map(x=>e.jsx("li",{className:"list-disc marker:text-destructive/60",children:x.message},`${x.field}:${x.message}`))})]}):null,ye?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:ye})]}):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:ae&&wr?e.jsxs("button",{type:"button",className:Ie,disabled:Te,onClick:()=>Pr(Ct?"ACTIVE":"PAUSED"),children:[te==="pause"||te==="resume"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):Ct?e.jsx(l.Play,{className:"h-3 w-3"}):e.jsx(fn,{className:"h-3 w-3"}),Ct?"Resume":"Pause"]}):!ae&&(ue==="plan"||ue==="result")?e.jsxs("button",{type:"button",className:Je,onClick:()=>se("edit"),children:[e.jsx(l.ChevronRight,{className:"h-3 w-3 rotate-180"}),ue==="result"?"Edit brief":"Tweak brief"]}):!ae&&g&&!p?e.jsx("button",{type:"button",className:Je,onClick:g,children:"Discard"}):null}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!ae&&ue==="edit"&&!Be?e.jsxs("button",{type:"button",className:Ie,disabled:Te,onClick:()=>{Ns()},children:[te==="plan"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(qr,{className:"h-3 w-3"}),"Preview plan"]}):null,e.jsxs("button",{type:"button",className:Ie,disabled:Te||ae&&Me,onClick:It,title:ae&&Me?"Save your changes before running — Run now uses the saved briefing.":void 0,children:[te==="run"||te==="preview"||St?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):ue==="result"?e.jsx(l.RefreshCw,{className:"h-3 w-3"}):ue==="plan"?e.jsx($t,{className:"h-3 w-3"}):ae?e.jsx(l.Send,{className:"h-3 w-3"}):e.jsx($t,{className:"h-3 w-3"}),ae?"Run now":ue==="plan"?"Run plan":ue==="result"?"Run again":"Show preview"]}),e.jsxs("button",{type:"button",className:ae?Ie:Zs,disabled:Te,onClick:Ir,children:[te==="save"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(a.Check,{className:"h-3 w-3"}),ae?"Save changes":"Create briefing"]})]})]})}),e.jsx(l.Dialog,{open:xr,onOpenChange:x=>{pt(x),x||ft(null)},children:e.jsxs(l.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(l.DialogHeader,{className:"border-b border-border px-6 py-3 text-left",children:[e.jsx(l.DialogTitle,{className:"truncate text-[14px] font-semibold leading-5",children:Dr}),e.jsx(l.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:qe?e.jsx(dn,{previewRun:qe,fullWidth:!0}):He?e.jsx(rs,{preview:He}):Ce?e.jsx(un,{run:Ce}):null})]})})]})}function cr({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(Hr,{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 ei={listBriefings:kn,getBriefing:Gt,pauseBriefing:Xt,resumeBriefing:Jt,deleteBriefing:Qt,runBriefingNow:Yt},ti="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",si="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",dr="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 ni(t){return(t==null?void 0:t.trim())||"This dashboard"}function ri(t){return t==="This dashboard"?"Watch this dashboard":`Watch ${t}`}function ai(t,s){return t.source.type==="dashboard"&&t.source.dashboardId===s}function oi(t){return t==="dashboard"?"This dashboard":"Project"}function ii(t,s,n){return s==="dashboard"?t.filter(r=>ai(r,n)):t}async function li({apiClient:t,apiServiceUrl:s,token:n}){const o=[];let i=1,c=0,u=Number.POSITIVE_INFINITY;for(;c<u;){const d=await t.listBriefings(s,n,{scope:"organization",page:i,pageSize:100}),m=d.briefings;if(o.push(...m),c+=m.length,u=d.total,m.length===0||c>=u)break;i+=1}return o}function ci(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 i=Math.round(o/24);if(i<7)return`${i}d ago`;const c=Math.round(i/7);return c<5?`${c}w ago`:`${Math.round(i/30)}mo ago`}function di(t){return t.scheduleExpr?t.scheduleExpr:"On demand"}function ui(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 ur(t){return t.hasActiveRun?"Running":t.lastRunStatus?`Last run ${t.lastRunStatus.toString().toLowerCase()}`:"Idle"}function mi(t){return t.source.type==="dashboard"?"This dashboard":"Project"}function hi({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:oi(n)},n)})})}function xi({briefings:t,dashboardLabel:s,sourceView:n,error:r,loading:o,onSourceViewChange:i,onClose:c,onEdit:u,onNew:d,onRunNow:m,onTogglePause:f,onDelete:g,selectingId:p,busyId:y,manageBriefingsHref:I}){const S=t.length,N=t.filter(j=>j.status==="ACTIVE").length,b=t.find(j=>j.hasActiveRun)??null,T=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:ti,children:"Briefings"}),e.jsx("h2",{className:"mt-0.5 truncate text-[14px] font-semibold leading-5",children:T})]}),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(hi,{activeView:n,onChange:i}),e.jsx("div",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:o&&S===0?e.jsx("span",{children:"Loading briefings…"}):S===0?e.jsx("span",{children:"No briefings yet"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[S," watching"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[N," active"]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[o?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,S>0?e.jsxs("button",{onClick:d,className:dr,children:[e.jsx(l.Plus,{className:"h-3 w-3"}),"New briefing"]}):null]})]}),b?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:b.name}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground",children:ur(b)})]}):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(pi,{onNew:d}):null,t.map(j=>e.jsx(gi,{briefing:j,isOpening:p===j.id,isBusy:y===j.id,onOpen:()=>u(j.id),onRunNow:()=>m(j),onTogglePause:()=>f(j),onDelete:()=>g(j)},j.id))]}),I?e.jsx("div",{className:"border-t border-border px-4 py-2.5",children:e.jsxs("a",{href:I,className:a.cn(si,"h-6 px-1 text-[11px]"),children:["Manage all briefings",e.jsx(_r,{className:"h-3 w-3"})]})}):null]})}function pi({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(dr,"mt-4"),children:[e.jsx(l.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 gi({briefing:t,isOpening:s,isBusy:n,onOpen:r,onRunNow:o,onTogglePause:i,onDelete:c}){const u=t.status==="PAUSED",d=t.hasActiveRun,m=ui(t),f=ci(t.lastRunAt),g=t.lastRunStatus,p=g==="SUCCESS"?X.success.dot:g==="FAILED"?X.danger.dot:g?X.warning.dot:X.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:y=>{(y.key==="Enter"||y.key===" ")&&(y.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:mi(t)}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx(l.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 ",f]})]}):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?ur(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(l.DropdownMenu,{children:[e.jsx(l.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",onClick:y=>y.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(l.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(l.DropdownMenuContent,{align:"end",className:"w-44",children:[e.jsxs(l.DropdownMenuItem,{onClick:r,children:[e.jsx(l.Pencil,{className:"h-3.5 w-3.5"}),"Edit briefing"]}),e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),o()},children:[e.jsx($t,{className:"h-3.5 w-3.5"}),"Run now"]}),t.scheduleExpr?e.jsx(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),i()},children:u?e.jsxs(e.Fragment,{children:[e.jsx(l.Play,{className:"h-3.5 w-3.5"}),"Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(fn,{className:"h-3.5 w-3.5"}),"Pause"]})}):null,e.jsx(l.DropdownMenuSeparator,{}),e.jsxs(l.DropdownMenuItem,{onClick:y=>{y.preventDefault(),c()},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(l.Trash2,{className:"h-3.5 w-3.5"}),"Delete briefing"]})]})]})})]})}const bi=2e3,yi=20*6e4;function ji({briefingId:t,initialRun:s,apiServiceUrl:n,token:r,onTerminal:o,onTimeout:i,onExpand:c}){const[u,d]=h.useState(s),{startRun:m}=Ht({apiServiceUrl:n,token:r,intervalMs:bi,timeoutMs:yi,fetchRun:({apiServiceUrl:g,token:p,runId:y})=>Zt(g,p,t,y),onRun:g=>{d(g)},onTerminalRun:g=>{o(g)},onTimeout:()=>{i()}}),f=h.useRef(!1);return h.useEffect(()=>{f.current||(f.current=!0,lt(s.status)?m(s):it(s.status)&&o(s))},[s,o,m]),e.jsx(Lo,{run:u,onExpand:c})}function vi({dashboardId:t,dashboardTitle:s,apiServiceUrl:n,token:r,disabled:o,className:i,manageBriefingsHref:c,client:u}){const{authToken:d,tokenProps:m}=l.useSemaphorContext(),[f,g]=h.useState(!1),[p,y]=h.useState("list"),[I,S]=h.useState("dashboard"),[N,b]=h.useState([]),[T,j]=h.useState(null),[C,A]=h.useState(!1),[V,L]=h.useState(null),[D,R]=h.useState(null),[_,M]=h.useState(null),[z,U]=h.useState(null),[B,W]=h.useState(null),[E,me]=h.useState(null),w=n??(m==null?void 0:m.apiServiceUrl),q=r??(d==null?void 0:d.accessToken),te=h.useMemo(()=>({...ei,...u}),[u]),Q=ni(s),be=h.useMemo(()=>ii(N,I,t),[t,N,I]),pe=h.useMemo(()=>I==="dashboard"?{source:{type:"dashboard",dashboardId:t},label:Q,detail:ri(Q)}:{source:{type:"project"},label:"This project",detail:"Use any data in this project."},[t,Q,I]),ye=!!(w&&q),O=h.useCallback(async()=>{if(!(!w||!q)){A(!0),U(null);try{b(await li({apiClient:te,apiServiceUrl:w,token:q}))}catch($){U($ instanceof Error?$.message:"Could not load briefings.")}finally{A(!1)}}},[te,w,q]);h.useEffect(()=>{!f||p!=="list"||!ye||O()},[ye,O,f,p]);const Le=()=>{j(null),S("dashboard"),y("list"),g(!0)},we=()=>{j(null),y("author")},je=async $=>{if(!(!w||!q)){L($),U(null);try{const Y=await te.getBriefing(w,q,$);j(Y.briefing),y("author")}catch(Y){U(Y instanceof Error?Y.message:"Could not open briefing.")}finally{L(null)}}},Fe=async $=>{if(!(!w||!q)){R($.id);try{await te.runBriefingNow(w,q,$.id,{requestId:Ni()}),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not start the run.")}finally{R(null)}}},H=async $=>{if(!(!w||!q)){R($.id);try{const Y=$.status==="PAUSED"?await te.resumeBriefing(w,q,$.id):await te.pauseBriefing(w,q,$.id);l.ue.success(Y.briefing.status==="PAUSED"?"Briefing paused":"Briefing resumed"),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not update the briefing status.")}finally{R(null)}}},fe=async()=>{if(!_||!w||!q)return;const $=_;R($.id);try{await te.deleteBriefing(w,q,$.id),l.ue.success("Briefing deleted"),M(null),O()}catch(Y){l.ue.error(Y instanceof Error?Y.message:"Could not delete the briefing.")}finally{R(null)}},Ae=be.length;return e.jsxs(l.Sheet,{open:f,onOpenChange:g,children:[e.jsx(cr,{disabled:o||!ye,briefingCount:Ae,className:i,onClick:Le}),e.jsxs(l.SheetContent,{side:"right",hideClose:!0,className:"flex h-full w-full flex-col overflow-hidden p-0 sm:max-w-[560px]",children:[e.jsxs(l.SheetHeader,{className:"sr-only",children:[e.jsx(l.SheetTitle,{children:"Briefings"}),e.jsx(l.SheetDescription,{children:"Manage briefings for this dashboard."})]}),p==="list"?e.jsx(xi,{briefings:be,dashboardLabel:Q,sourceView:I,error:z,loading:C,onSourceViewChange:S,onClose:()=>g(!1),onEdit:$=>{je($)},onNew:we,onRunNow:$=>{Fe($)},onTogglePause:$=>{H($)},onDelete:$=>M($),selectingId:V,busyId:D,manageBriefingsHref:c}):e.jsx(lr,{apiServiceUrl:w,token:q,briefing:T,sourceContext:T?void 0:pe,title:T?"Edit briefing":"Create briefing",className:"h-full min-h-0 max-w-none border-0 shadow-none",onBack:()=>y("list"),onCancel:()=>g(!1),onDeleted:()=>{l.ue.success("Briefing deleted"),j(null),y("list"),O()},onRunStarted:()=>{},onSaved:$=>{j($),O()},onMinimizeRun:({briefing:$,run:Y})=>{W({briefing:$,run:Y}),g(!1)}})]}),B&&w&&q?e.jsx(ji,{briefingId:B.briefing.id,initialRun:B.run,apiServiceUrl:w,token:q,onTerminal:$=>{me({briefing:B.briefing,run:$}),W(null),O()},onTimeout:()=>{W(null),O()},onExpand:()=>{j(B.briefing),y("author"),W(null),g(!0)}}):null,E?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(Fo,{title:E.run.status==="SUCCESS"?`${E.briefing.name} is ready`:`${E.briefing.name} run failed`,durationSeconds:E.run.startedAt&&E.run.completedAt?Math.max(0,Math.floor((new Date(E.run.completedAt).getTime()-new Date(E.run.startedAt).getTime())/1e3)):null,status:E.run.status==="SUCCESS"?"success":"failed",onView:()=>{j(E.briefing),y("author"),me(null),g(!0)},onDismiss:()=>me(null)})}):null,e.jsx(l.AlertDialog,{open:!!_,onOpenChange:$=>{$||M(null)},children:e.jsxs(l.AlertDialogContent,{children:[e.jsxs(l.AlertDialogHeader,{children:[e.jsx(l.AlertDialogTitle,{children:"Delete briefing?"}),e.jsxs(l.AlertDialogDescription,{children:["This permanently deletes ",e.jsx("strong",{children:_==null?void 0:_.name}),". Recipients will stop receiving it."]})]}),e.jsxs(l.AlertDialogFooter,{children:[e.jsx(l.AlertDialogCancel,{children:"Cancel"}),e.jsx(l.AlertDialogAction,{className:"bg-destructive/90 hover:bg-destructive",onClick:fe,children:"Delete briefing"})]})]})})]})}function Ni(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-now-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}exports.AdvancedModeToggle=Xr;exports.BriefingAuthor=lr;exports.BriefingsApiError=ut;exports.DashboardBriefingLauncher=vi;exports.DashboardControlsSettings=jn;exports.DashboardFilterControlsButton=Nn;exports.DashboardFilterControlsLauncher=ga;exports.DocumentControlsSettings=vn;exports.ExportNotificationItem=bn;exports.ExportNotificationList=yn;exports.NotificationBell=oa;exports.Undo2=gn;exports.UnsavedChangesAlert=Jr;exports.UsersRound=Wt;exports.VisualEditingControls=Gr;exports.WatchDashboardButton=cr;exports.applyBriefingFormPatch=at;exports.briefingFormDraftToCreateRequest=zt;exports.briefingFormDraftToUpdateRequest=Gn;exports.briefingToFormDraft=Ue;exports.cancelBriefingRun=Tn;exports.createBriefing=Dn;exports.createBriefingFormDraft=Wn;exports.deleteBriefing=Qt;exports.deleteBriefingRun=Ln;exports.getBriefing=Gt;exports.getBriefingArtifact=Na;exports.getBriefingEvidence=wa;exports.getBriefingPreviewRun=An;exports.getBriefingRun=Zt;exports.listBriefingRuns=va;exports.listBriefingTenantSummaries=ja;exports.listBriefings=kn;exports.pauseBriefing=Xt;exports.polishBriefingText=Fn;exports.previewBriefingPlan=En;exports.resumeBriefing=Jt;exports.runBriefingNow=Yt;exports.runBriefingPreview=In;exports.updateBriefing=ht;exports.useExportPolling=na;exports.useExportRecovery=ra;exports.validateBriefingFormDraft=qt;