react-semaphor 0.1.316 → 0.1.318

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 (28) hide show
  1. package/dist/chunks/{calendar-preferences-dialog-9NlFzHX8.js → calendar-preferences-dialog-DgpoCz1l.js} +1 -1
  2. package/dist/chunks/{calendar-preferences-dialog-BDdxi7Xm.js → calendar-preferences-dialog-DySStYHa.js} +1 -1
  3. package/dist/chunks/{dashboard-briefing-launcher-5fM_KJoT.js → dashboard-briefing-launcher-BrUNYrwk.js} +2565 -2261
  4. package/dist/chunks/dashboard-briefing-launcher-Fh6vC1S2.js +101 -0
  5. package/dist/chunks/{dashboard-controls-9YV-D1tD.js → dashboard-controls-BJb7QHvl.js} +119 -129
  6. package/dist/chunks/{dashboard-controls-UR_m0wD1.js → dashboard-controls-CDCpt8iB.js} +3 -8
  7. package/dist/chunks/{dashboard-json-ws4tortP.js → dashboard-json-BYEqzs6b.js} +1 -1
  8. package/dist/chunks/{dashboard-json-CKPID8Am.js → dashboard-json-BjFw0Ktj.js} +1 -1
  9. package/dist/chunks/{edit-dashboard-visual-CmxnZI8I.js → edit-dashboard-visual-IxtXVkBc.js} +1 -1
  10. package/dist/chunks/{edit-dashboard-visual-ifKJLMTS.js → edit-dashboard-visual-VHlDJd5A.js} +3 -3
  11. package/dist/chunks/{index-Xdag_85e.js → index-BhrZn1Zk.js} +2 -2
  12. package/dist/chunks/{index-gcA9Rs35.js → index-CAWSZGCL.js} +5 -5
  13. package/dist/chunks/{resource-management-panel-paSAzVj2.js → resource-management-panel-0OlH_Gze.js} +2 -2
  14. package/dist/chunks/{resource-management-panel-BduJanWW.js → resource-management-panel-X4zxZ4wq.js} +1 -1
  15. package/dist/chunks/{use-create-flow-overlay-state-DWnzVVlP.js → use-create-flow-overlay-state-DkZTa6eN.js} +1 -1
  16. package/dist/chunks/{use-create-flow-overlay-state-DKV6tIc5.js → use-create-flow-overlay-state-WYyQFfGQ.js} +2 -2
  17. package/dist/chunks/{use-visual-utils-C8PDxg2w.js → use-visual-utils-2l8uDXRH.js} +1 -1
  18. package/dist/chunks/{use-visual-utils-Cs0-baCK.js → use-visual-utils-C8VR6_Cr.js} +1 -1
  19. package/dist/dashboard/index.cjs +1 -1
  20. package/dist/dashboard/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +17 -16
  23. package/dist/style.css +1 -1
  24. package/dist/surfboard/index.cjs +1 -1
  25. package/dist/surfboard/index.js +2 -2
  26. package/dist/types/main.d.ts +3 -0
  27. package/package.json +1 -1
  28. package/dist/chunks/dashboard-briefing-launcher-CVxLt10p.js +0 -96
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../chunks/index-Xdag_85e.js"),e=require("../chunks/common-types-C73-Ud1-.js"),a=require("../chunks/calendar-preferences-dialog-BDdxi7Xm.js");exports.Surfboard=r.DashboardPlus;exports.CONTROL_CARD_DEFAULT_VALUE=e.CONTROL_CARD_DEFAULT_VALUE;exports.EMPTY_SELECTION=e.EMPTY_SELECTION;exports.CalendarPreferencesDialog=a.CalendarPreferencesDialog;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("../chunks/index-BhrZn1Zk.js"),e=require("../chunks/common-types-C73-Ud1-.js"),a=require("../chunks/calendar-preferences-dialog-DySStYHa.js");exports.Surfboard=r.DashboardPlus;exports.CONTROL_CARD_DEFAULT_VALUE=e.CONTROL_CARD_DEFAULT_VALUE;exports.EMPTY_SELECTION=e.EMPTY_SELECTION;exports.CalendarPreferencesDialog=a.CalendarPreferencesDialog;
@@ -1,6 +1,6 @@
1
- import { a as e } from "../chunks/index-gcA9Rs35.js";
1
+ import { a as e } from "../chunks/index-CAWSZGCL.js";
2
2
  import { C, E } from "../chunks/common-types-4bjoIgvm.js";
3
- import { C as s } from "../chunks/calendar-preferences-dialog-9NlFzHX8.js";
3
+ import { C as s } from "../chunks/calendar-preferences-dialog-DgpoCz1l.js";
4
4
  export {
5
5
  C as CONTROL_CARD_DEFAULT_VALUE,
6
6
  s as CalendarPreferencesDialog,
@@ -629,6 +629,7 @@ export declare type BriefingAuthorClient = {
629
629
  previewBriefingPlan: typeof previewBriefingPlan;
630
630
  runBriefingPreview: typeof runBriefingPreview;
631
631
  getBriefingPreviewRun: typeof getBriefingPreviewRun;
632
+ polishBriefingText: typeof polishBriefingText;
632
633
  };
633
634
 
634
635
  export declare type BriefingAuthorProps = {
@@ -3898,6 +3899,8 @@ export declare type Placeholders = {
3898
3899
 
3899
3900
  export declare type PluginType = 'custom' | 'standard';
3900
3901
 
3902
+ export declare function polishBriefingText(apiServiceUrl: string, token: string, text: string): Promise<string>;
3903
+
3901
3904
  export declare function previewBriefingPlan(apiServiceUrl: string, token: string, payload: CreateBriefingRequest): Promise<PreviewBriefingPlanResponse>;
3902
3905
 
3903
3906
  export declare type PreviewBriefingPlanResponse = {
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "email": "support@semaphor.cloud"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "0.1.316",
8
+ "version": "0.1.318",
9
9
  "description": "Fully interactive and customizable dashboards for your apps.",
10
10
  "keywords": [
11
11
  "react",
@@ -1,96 +0,0 @@
1
- "use strict";const e=require("react/jsx-runtime"),a=require("./switch-DPaKnsb8.js"),i=require("./index-Xdag_85e.js"),ee=require("./use-create-flow-overlay-state-DWnzVVlP.js"),h=require("react"),vs=require("./use-visual-utils-C8PDxg2w.js"),Kt=require("./date-formatter-D9Bvw5Qk.js");require("./index-DRlMUglg.js");require("react-dom");/**
2
- * @license lucide-react v0.453.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const Un=a.createLucideIcon("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
7
- * @license lucide-react v0.453.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const Xt=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
- * @license lucide-react v0.453.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const $n=a.createLucideIcon("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/**
17
- * @license lucide-react v0.453.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const _n=a.createLucideIcon("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/**
22
- * @license lucide-react v0.453.0 - ISC
23
- *
24
- * This source code is licensed under the ISC license.
25
- * See the LICENSE file in the root directory of this source tree.
26
- */const zn=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
- * @license lucide-react v0.453.0 - ISC
28
- *
29
- * This source code is licensed under the ISC license.
30
- * See the LICENSE file in the root directory of this source tree.
31
- */const qn=a.createLucideIcon("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/**
32
- * @license lucide-react v0.453.0 - ISC
33
- *
34
- * This source code is licensed under the ISC license.
35
- * See the LICENSE file in the root directory of this source tree.
36
- */const ws=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"}]]);/**
37
- * @license lucide-react v0.453.0 - ISC
38
- *
39
- * This source code is licensed under the ISC license.
40
- * See the LICENSE file in the root directory of this source tree.
41
- */const Ns=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"}]]);/**
42
- * @license lucide-react v0.453.0 - ISC
43
- *
44
- * This source code is licensed under the ISC license.
45
- * See the LICENSE file in the root directory of this source tree.
46
- */const ft=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 Hn({open:t,onOpenChange:s,isLibraryVisual:n,currentVisualName:r,isSaving:o=!1,destinationMode:l="both",onConfirm:d}){const[u,c]=h.useState(n&&r?`Copy of ${r}`:r||""),[m,x]=h.useState("");h.useEffect(()=>{t&&(c(n&&r?`Copy of ${r}`:r||""),x(""))},[t,n,r]);const y=!!u.trim(),p=l==="local"?{saveToLibrary:!1,saveToCurrentDashboard:!0,badgeType:"local",description:"Creates a local copy on the current dashboard.",actionLabel:"Add to Dashboard (Local)"}:l==="library"?{saveToLibrary:!0,saveToCurrentDashboard:!1,badgeType:"library",description:"Creates a reusable visual in Visual Library.",actionLabel:"Save as Library Visual"}:{saveToLibrary:!0,saveToCurrentDashboard:!0,badgeType:"linked",description:"Creates a new library visual and adds a linked copy to this dashboard.",actionLabel:"Save Copy as Linked Visual"},f=()=>{!y||o||d({name:u.trim(),description:m.trim()||void 0,saveToLibrary:p.saveToLibrary,saveToCurrentDashboard:p.saveToCurrentDashboard})};return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"sm:max-w-[500px]",children:[e.jsxs(i.DialogHeader,{children:[e.jsxs(i.DialogTitle,{className:"flex items-center gap-2",children:[e.jsx("span",{children:"Save Visual As"}),p.badgeType!=="local"&&e.jsx(ee.VisualBadge,{type:p.badgeType,showLabel:!0,className:"px-2 py-0.5"})]}),e.jsx(i.DialogDescription,{children:p.description})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(a.Label,{htmlFor:"name",children:"Name"}),e.jsx(a.Input,{id:"name",value:u,onChange:E=>c(E.target.value),placeholder:"Enter visual name",disabled:o})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(a.Label,{htmlFor:"description",children:"Description (optional)"}),e.jsx(i.Textarea,{id:"description",value:m,onChange:E=>x(E.target.value),placeholder:"Enter visual description",rows:3,disabled:o})]})]}),e.jsxs(i.DialogFooter,{children:[e.jsx(a.Button,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancel"}),e.jsxs(a.Button,{onClick:f,disabled:!y||o,children:[o&&e.jsx(a.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),p.actionLabel]})]})]})})}function Wn(){const[t,s]=h.useState(!1),[n,r]=h.useState(!1),[o,l]=h.useState(null),[d,u]=h.useState(null),c=a.useEditorStore(D=>D.frame),m=a.useEditorStore(D=>D.card),x=i.useSelectedVisual(),y=a.useDashboardStore(D=>D.selectedSheetId),p=a.useDashboardStore(D=>D.dashboard),f=a.useDashboardStore(D=>D.actions.setIsDashboardPanelOpen),{getUpdatedFrame:E}=vs.useVisualUtils(),{selectVisual:S}=i.useManagementActions(),{addFrame:j,setSelectedFrameId:b,setIsVisualEditing:w}=a.useDashboardActions(),v=i.useResolveExistingFrameSemanticExecutionPayload(),F=!!(c!=null&&c.visualId),A=(()=>{var D,P;return((D=c==null?void 0:c.cards)==null?void 0:D.length)===1&&((P=c.cards[0])!=null&&P.title)?c.cards[0].title:x!=null&&x.title?x.title:(m==null?void 0:m.title)||"Untitled Visual"})(),B=i.useCreateVisualWithFrame(D=>{D!=null&&D.id&&(S(D),n&&o&&d&&y&&(async()=>{try{const P={...o,id:a.v4(),visualId:D.id};j(y,P,{position:"end",semanticExecutionPayload:d}),b(P.id),r(!1),l(null),u(null),w(!1)}catch(P){console.error("Failed to promote semantic metadata for saved visual:",P),i.ue.error(P instanceof Error?P.message:"Failed to prepare semantic metadata for the saved visual")}})(),f(!0),s(!1))});return{saveAsDialogOpen:t,setSaveAsDialogOpen:s,handleSaveAs:async D=>{if(!y){i.ue.error("No sheet selected");return}const P=E(),$=a.getDynamicFrameSaveIssue(P);if($){i.ue.error($);return}const _=P.cards.length===1?{...P,cards:P.cards.map(U=>({...U,title:D.name}))}:P;if(D.saveToLibrary){let U=null;if(D.saveToCurrentDashboard)try{U=await v(_,{previousFrame:i.findDashboardFrameById(p,_.id)})}catch(q){console.error("Failed to prepare semantic metadata before saving visual:",q),i.ue.error(q instanceof Error?q.message:"Failed to prepare semantic metadata for the saved visual");return}r(D.saveToCurrentDashboard),l(_),u(U);const L={title:D.name,description:D.description,frameObject:_,isPrivate:!1};B.mutate(L)}else if(D.saveToCurrentDashboard){const U={..._,id:a.v4(),visualId:void 0};try{const L=await v(_,{previousFrame:i.findDashboardFrameById(p,_.id)});j(y,U,{position:"end",semanticExecutionPayload:L}),b(U.id),i.ue.success("Visual saved to dashboard"),s(!1),w(!1)}catch(L){console.error("Failed to save visual to dashboard:",L),i.ue.error(L instanceof Error?L.message:"Failed to prepare semantic metadata for the visual")}}},isLibraryVisual:F,currentVisualName:A,isSaving:B.isPending}}function Gn(t={}){const s=a.useEditorStore(V=>V.frame),n=a.useEditorStore(V=>V.editorContext),r=i.useManagementStore(V=>V.selectedVisual),o=a.useDashboardStore(V=>V.selectedFrameId),l=a.useDashboardStore(V=>V.selectedSheetId),d=a.useDashboardStore(V=>V.dashboard),{setIsVisualEditing:u,updateFrame:c}=a.useDashboardActions(),[m,x]=h.useState(!1),[y,p]=h.useState("both"),f=i.useResolveExistingFrameSemanticExecutionPayload(),E=(n==null?void 0:n.type)==="documentSection",S=!!(s!=null&&s.visualId||r!=null&&r.id),j=!!(s!=null&&s.visualId&&o),b=S&&!j,{saveAsDialogOpen:w,setSaveAsDialogOpen:v,handleSaveAs:F,isLibraryVisual:A,currentVisualName:B,isSaving:I}=Wn(),{getUpdatedFrame:D}=vs.useVisualUtils();if(E)return e.jsxs(e.Fragment,{children:[e.jsx(ee.EditorAcceptButton,{className:"rounded-control",variant:"default"}),e.jsx(ee.EditorCancelButton,{})]});const P=async()=>{if(!l){i.ue.error("No sheet selected");return}if(m)return;x(!0);const V=D(),_=a.getDynamicFrameSaveIssue(V);if(_){x(!1),i.ue.error(_);return}const U={...V,visualId:void 0},L=i.findDashboardFrameById(d,U.id);try{const q=await f(U,{previousFrame:L});c(l,U,{semanticExecutionPayload:q})}catch(q){console.error("Failed to apply local semantic metadata:",q),x(!1),i.ue.error(q instanceof Error?q.message:"Failed to prepare semantic metadata for this visual");return}setTimeout(()=>{x(!1),i.ue.success("Changes applied. Visual is now local to this dashboard"),u(!1)},300)},$=V=>{p(V),v(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"inline-flex items-center overflow-hidden rounded-control",children:[!S&&e.jsx(ee.EditorAcceptButton,{className:"!rounded-none",variant:"default"}),S&&b&&e.jsx(ee.VisualSaveButton,{className:"!rounded-none",variant:"default"}),S&&j&&e.jsx(ee.VisualSaveAndApplyButton,{className:"!rounded-none"}),e.jsxs(i.DropdownMenu,{modal:!1,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx(a.Button,{variant:"default",size:"xs",className:"w-7 !rounded-none border-l border-primary-foreground/20 px-0","aria-label":"Open visual save options",disabled:I||m,children:e.jsx(a.ChevronDown,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"min-w-[220px] rounded-control border border-border/60 p-1 shadow-sm",children:[j&&e.jsxs(e.Fragment,{children:[e.jsxs(i.DropdownMenuItem,{onClick:P,disabled:m,children:[e.jsx(a.Check,{className:"h-3.5 w-3.5"}),m?"Applying...":"Apply Locally"]}),e.jsx(i.DropdownMenuSeparator,{})]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>$("local"),disabled:I,children:[e.jsx(i.Plus,{className:"h-3.5 w-3.5"}),"Add to Dashboard (Local)"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>$("library"),disabled:I,children:[e.jsx(ee.Library,{className:"h-3.5 w-3.5"}),"Save as Library Visual"]}),e.jsxs(i.DropdownMenuItem,{onClick:()=>$("both"),disabled:I,children:[e.jsx(ee.Link2,{className:"h-3.5 w-3.5"}),"Save Copy as Linked Visual"]})]})]})]}),e.jsx(ee.EditorCancelButton,{}),e.jsx(Hn,{open:w,onOpenChange:V=>{I||v(V)},isLibraryVisual:A,currentVisualName:B,isSaving:I,destinationMode:y,onConfirm:F})]})}function Kn({className:t}){const s=a.useEditorStore(m=>m.isDevMode),n=a.useDashboardStore(m=>m.isVisualEditing),{setIsDevMode:r}=a.useEditorActions(),{config:o}=h.useContext(i.SemaphorContext).tokenProps,l=(o==null?void 0:o.showAdvancedMode)!==!1;if(!n||!l)return null;const d=s?a.SlidersHorizontal:i.CodeXml,u=s?"Drag & drop":"SQL",c=s?"Switch to drag-and-drop mode":"Switch to SQL mode";return e.jsxs("button",{type:"button","aria-label":c,title:c,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(d,{className:"h-3 w-3 text-muted-foreground"}),u]})}function Xn({open:t,onOpenChange:s,onSave:n,onDiscard:r,isSaving:o,title:l="Unsaved changes",description:d="You have unsaved changes to this dashboard. What would you like to do?",cancelLabel:u="Cancel",discardLabel:c="Discard",saveLabel:m="Save"}){const x=y=>{!y&&o||s(y)};return e.jsx(i.AlertDialog,{open:t,onOpenChange:x,children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:l}),e.jsx(i.AlertDialogDescription,{children:d})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(a.Button,{type:"button",size:"xs",onClick:r,disabled:o,variant:"ghost",className:"mr-auto text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",children:c}),e.jsx(i.AlertDialogCancel,{disabled:o,children:u}),e.jsx(a.Button,{type:"button",size:"xs",onClick:n,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(a.LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}),"Saving..."]}):m})]})]})})}const Qn=1e4,Jn=15e3,Yn=3e4,Zn=3e4,er=12e4,Qt=2*60*60*1e3;function tr(t){const s=Date.now()-t.getTime();return s<Zn?Qn:s<er?Jn:Yn}function sr(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(p=>p.activeExports),[r,o]=h.useState(typeof document<"u"?!document.hidden:!0),l=h.useRef(null),d=h.useRef(!1),u=h.useRef(void 0),c=s==null?void 0:s.apiServiceUrl,m=t==null?void 0:t.accessToken,x=h.useCallback(()=>{const p=i.useExportStore.getState().activeExports;return Array.from(p.values()).filter(f=>i.isExportInProgress(f.status))},[]);h.useEffect(()=>{if(typeof document>"u")return;const p=()=>{o(!document.hidden)};return document.addEventListener("visibilitychange",p),()=>{document.removeEventListener("visibilitychange",p)}},[]);const y=h.useCallback(async()=>{if(!c||!m){d.current=!1;return}const p=x();if(p.length===0){d.current=!1;return}const f=Date.now(),E=p.filter(v=>f-v.startedAt.getTime()>Qt);if(E.length>0){const{updateExport:v}=i.useExportStore.getState().actions;for(const F of E)v(F.id,{status:"failed",error:"Export timed out. Please try again or contact support.",lastUpdatedAt:new Date})}const S=p.filter(v=>f-v.startedAt.getTime()<=Qt);if(S.length===0){d.current=!1;return}const j=await Promise.allSettled(S.map(async v=>{try{const F=await i.getExportStatus(c,m,v.id);let A;if(F.status==="completed")try{A=await i.getDownloadUrl(c,m,v.id)}catch(B){console.error(`[useExportPolling] Failed to get download URL for ${v.id}:`,B)}return{id:v.id,status:F.status,progress:F.progress,completedChunks:F.completedChunks,completedAt:F.completedAt?new Date(F.completedAt):void 0,lastUpdatedAt:new Date,fileSize:F.fileSize,error:F.error,downloadUrl:A}}catch(F){return console.error(`[useExportPolling] Failed to poll export ${v.id}:`,F),null}})),{updateExport:b}=i.useExportStore.getState().actions;for(const v of j)v.status==="fulfilled"&&v.value&&b(v.value.id,v.value);const w=x();if(w.length>0&&!document.hidden){const v=w.reduce((A,B)=>B.startedAt<A?B.startedAt:A,w[0].startedAt),F=tr(v);l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{var A;(A=u.current)==null||A.call(u)},F)}else d.current=!1},[c,m,x]);return h.useEffect(()=>{u.current=y},[y]),h.useEffect(()=>{var f;x().length>0&&r&&!d.current&&(d.current=!0,(f=u.current)==null||f.call(u))},[n,r,x]),h.useEffect(()=>{var f;const p=x();r&&p.length>0&&!d.current&&(d.current=!0,(f=u.current)==null||f.call(u))},[r,x]),h.useEffect(()=>{!r&&l.current&&(clearTimeout(l.current),l.current=null,d.current=!1)},[r]),h.useEffect(()=>()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]),{isPolling:d.current,isTabVisible:r,inProgressCount:x().length}}function nr(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(u=>u.activeExports),{addExport:r}=i.useExportActions(),o=h.useRef(!1),l=s==null?void 0:s.apiServiceUrl,d=t==null?void 0:t.accessToken;h.useEffect(()=>{if(o.current||!l||!d)return;(async()=>{try{const{exports:c}=await i.getExports(l,d,{status:["pending","processing","chunking","compacting","completed","failed"],limit:20});for(const m of c){if(n.has(m.id))continue;const x=m.totalChunks?Math.round(m.completedChunks/m.totalChunks*100):0;let y;if(m.status==="completed")try{y=await i.getDownloadUrl(l,d,m.id)}catch(f){console.error(`[useExportRecovery] Failed to get download URL for ${m.id}:`,f)}const p={id:m.id,status:m.status,progress:x,title:rr(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:y};r(p)}o.current=!0}catch(c){console.error("[useExportRecovery] Failed to recover exports:",c),o.current=!0}})()},[l,d,r,n])}function rr(t){return t.title?t.title:i.isExportInProgress(t.status)?"Export in progress...":t.status==="completed"?"Export completed":t.status==="failed"?"Export failed":"Export"}function Cs({export:t,onRemove:s}){const n=()=>{t.downloadUrl&&window.open(t.downloadUrl,"_blank")},r=u=>{u.stopPropagation(),s==null||s(t.id)},o=()=>{switch(t.status){case"completed":return e.jsx(i.CircleCheck,{className:"mt-0.5 h-5 w-5 shrink-0 text-green-600"});case"failed":return e.jsx(ee.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"})}},l=i.isExportInProgress(t.status),d=(()=>{switch(t.status){case"pending":return"Queued...";case"processing":return"Processing...";case"chunking":return"Processing...";case"compacting":return"Finalizing...";default:return"Processing..."}})();return e.jsxs("div",{className:"group p-4 transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[o(),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h4",{className:"mb-1 truncate text-sm font-medium",children:t.title}),t.status==="completed"&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[t.totalRows.toLocaleString()," rows"]}),t.fileSize&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:i.formatFileSize(t.fileSize)})]})]}),l&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d}),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:Kt.formatDistanceToNow(t.startedAt,{addSuffix:!0})}),t.downloadUrl&&e.jsxs(a.Button,{size:"sm",variant:"outline",className:"h-8 bg-transparent",onClick:n,children:[e.jsx(i.Download,{className:"mr-1.5 h-3.5 w-3.5"}),"Download"]})]}),l&&e.jsxs("div",{children:[e.jsx(i.Progress,{value:t.progress,className:"h-1.5"}),e.jsxs("span",{className:"mt-1 block text-xs text-muted-foreground",children:[t.progress,"% complete"]})]}),t.status==="failed"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Kt.formatDistanceToNow(t.startedAt,{addSuffix:!0})})]})]})}function Ss(){const{authToken:t,tokenProps:s}=i.useSemaphorContext(),n=i.useExportStore(S=>S.activeExports),{clearCompleted:r,removeExport:o,updateExport:l}=i.useExportActions(),[d,u]=h.useState(!1),[c,m]=h.useState(!1),x=Array.from(n.values()).sort((S,j)=>j.startedAt.getTime()-S.startedAt.getTime()),y=x.some(S=>S.status==="completed"||S.status==="failed"),p=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,j=t==null?void 0:t.accessToken;if(!(!S||!j)){u(!0);try{const b=Array.from(n.values());await Promise.all(b.map(async w=>{try{const v=await i.getExportStatus(S,j,w.id);let F;if(v.status==="completed")try{F=await i.getDownloadUrl(S,j,w.id)}catch(A){console.error(`Failed to get download URL for ${w.id}:`,A)}l(w.id,{status:v.status,progress:v.progress,completedChunks:v.completedChunks,completedAt:v.completedAt?new Date(v.completedAt):void 0,lastUpdatedAt:new Date,fileSize:v.fileSize,error:v.error,downloadUrl:F})}catch(v){console.error(`Failed to refresh export ${w.id}:`,v)}}))}finally{u(!1)}}},[n,t==null?void 0:t.accessToken,s==null?void 0:s.apiServiceUrl,l]),f=h.useCallback(async()=>{const S=s==null?void 0:s.apiServiceUrl,j=t==null?void 0:t.accessToken;if(!S||!j){r();return}m(!0);try{const b=x.filter(v=>v.status==="completed"||v.status==="failed"),w=await Promise.allSettled(b.map(async v=>(await i.cancelExport(S,j,v.id),v.id)));for(const v of w)v.status==="fulfilled"?o(v.value):console.error("Failed to delete export:",v.reason)}finally{m(!1)}},[x,s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,r,o]),E=h.useCallback(async S=>{const j=s==null?void 0:s.apiServiceUrl,b=t==null?void 0:t.accessToken;if(j&&b)try{await i.cancelExport(j,b,S),o(S);return}catch(w){console.error(`Failed to cancel export ${S}:`,w)}o(S)},[s==null?void 0:s.apiServiceUrl,t==null?void 0:t.accessToken,o]);return x.length===0?e.jsxs("div",{className:"p-6 text-center",children:[e.jsx(Xt,{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(Xt,{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:d,title:"Refresh status",children:e.jsx(i.RefreshCw,{className:`h-4 w-4 ${d?"animate-spin":""}`})}),y&&e.jsx(a.Button,{variant:"ghost",size:"sm",className:"h-7 px-2 text-sm",onClick:f,disabled:c,children:c?"Clearing...":"Clear all"})]})]}),e.jsx("div",{className:"max-h-[350px] overflow-y-auto",children:e.jsx("div",{className:"divide-y",children:x.map(S=>e.jsx(Cs,{export:S,onRemove:E},S.id))})})]})}function ar({variant:t}){const s=i.useExportStore(c=>c.activeExports),n=i.useInProgressExportsCount(),r=s.size>0,o=Array.from(s.values()).some(c=>c.status==="completed"||c.status==="failed"),d=n>0?n>9?"9+":String(n):null,u=r;return e.jsxs(a.Popover,{children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs(a.Button,{variant:t??"ghost",size:"xs",className:"relative w-7 px-0 text-muted-foreground hover:text-foreground","aria-label":"Export notifications",children:[e.jsx(i.Bell,{className:"h-3.5 w-3.5"}),u&&e.jsx("span",{className:`absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground ${d?"-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:d})]})}),e.jsx(a.PopoverContent,{className:"w-80 p-0",align:"end",sideOffset:8,children:e.jsx(Ss,{})})]})}function or(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 Ds({open:t,onOpenChange:s,trigger:n,showTrigger:r=!0,initialMode:o="manage"}){const l=o==="create",{forceClose:d,handleOpenChange:u,isCreateFlowActive:c,preventPassiveDismissDuringCreate:m,resolvedOpen:x,setIsCreateFlowActive:y}=ee.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:o==="create",dismissMode:r?"passive":"explicit-only"}),p=a.useDashboardStore(D=>D.dashboard),{setDashboardControlsModel:f}=a.useDashboardActions(),{participants:E}=i.useDashboardStructuralParticipants(a.getDashboardCards(p)),S=Array.from(new Map(E.flatMap(D=>D.fieldChoices.map(P=>{var $;return[P.value,{option:P,target:($=D.fieldTargetMap)==null?void 0:$[P.value]}]}))).values()),j=Array.from(new Map(E.flatMap(D=>D.metricChoices.map(P=>{var $;return[P.value,{option:P,target:($=D.metricTargetMap)==null?void 0:$[P.value]}]}))).values()),b=a.collectDashboardControlIds({...p||{},controls:[]}),w=i.buildDashboardStructuralParticipantIdsByControlId(p),v=(D,P,$)=>{f(D,P,or($))},F=h.useCallback(()=>{if(l){d();return}y(!1)},[l,d,y]),A=e.jsx(ee.ControlDefinitionListEditor,{scope:"dashboard",controls:p.controls||[],reservedControlIds:b,defaultValues:p.defaultControlValues||{},usageByControlId:i.buildDashboardControlUsageById(p),availableFieldChoices:S,availableMetricChoices:j,structuralParticipants:E,structuralParticipantIdsByControlId:w,initialCreateFlow:o==="create",onCreateFlowActiveChange:y,onCreateFlowComplete:F,onChange:v,emptyMessage:"No dashboard controls yet."}),B=c?"Add dashboard control":"Dashboard Controls",I=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:x,onOpenChange:u,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:n||e.jsxs(a.Button,{variant:"outline",className:"h-7 px-2",size:"sm",children:[e.jsx(a.SlidersHorizontal,{className:"mr-2 h-4 w-4"}),"Controls"]})}),e.jsx(a.PopoverContent,{className:"w-[620px] max-w-[95vw] space-y-4",align:"end",onEscapeKeyDown:m,onPointerDownOutside:m,children:I})]}):e.jsx(i.Dialog,{open:x,onOpenChange:u,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:m,onPointerDownOutside:m,children:[e.jsxs(i.DialogHeader,{className:c?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:B}),e.jsx(i.DialogDescription,{className:c?"sr-only":"text-[13px]",children:c?"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 ir=["enum","multi_enum","text","number","boolean","date"];function ks({open:t,onOpenChange:s,initialMode:n="manage"}){var I;const r=n==="create",{forceClose:o,handleOpenChange:l,isCreateFlowActive:d,preventPassiveDismissDuringCreate:u,resolvedOpen:c,setIsCreateFlowActive:m}=ee.useCreateFlowOverlayState({open:t,onOpenChange:s,initialCreateFlowActive:n==="create",dismissMode:"explicit-only"}),x=a.useDashboardStore(D=>D.dashboard),y=a.useDashboardStore(D=>D.selectedSheetId),{setDashboardInputs:p}=a.useDashboardActions(),f=(I=x.sheets)==null?void 0:I.find(D=>D.id===y),E=(f==null?void 0:f.kind)==="document"&&!!f.document,S=h.useMemo(()=>E&&(f!=null&&f.document)?i.getDocumentSheetDashboardInputs(x,f.id):[],[x,E,f==null?void 0:f.document,f==null?void 0:f.id]),j=h.useMemo(()=>S.filter(D=>D.kind==="control"),[S]),b=h.useMemo(()=>j.map(D=>D.control),[j]),w=h.useMemo(()=>dr(b),[b]),v=h.useMemo(()=>lr(x),[x]),F=h.useCallback(()=>{if(r){o();return}m(!1)},[r,o,m]),A=h.useCallback((D,P,$)=>{!E||!(f!=null&&f.document)||p(ur({allInputs:x.inputs||[],documentSheetId:f.id,currentDocumentInputs:S,nextControls:D,nextDefaultValues:P,change:$}))},[x.inputs,S,E,f,p]);if(!E||!(f!=null&&f.document))return null;const B=d?"Add document control":"Document Controls";return e.jsx(i.Dialog,{open:c,onOpenChange:l,children:e.jsxs(i.DialogContent,{className:"flex max-h-[88vh] flex-col overflow-hidden sm:max-w-[600px]",onEscapeKeyDown:u,onPointerDownOutside:u,children:[e.jsxs(i.DialogHeader,{className:d?"space-y-0":void 0,children:[e.jsx(i.DialogTitle,{className:"text-[15px]",children:B}),e.jsx(i.DialogDescription,{className:d?"sr-only":"text-[13px]",children:d?"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(ee.ControlDefinitionListEditor,{scope:"dashboard",controls:b,reservedControlIds:v,defaultValues:w,usageByControlId:{},availableFieldChoices:[],availableMetricChoices:[],structuralParticipants:[],structuralParticipantIdsByControlId:{},allowedControlTypes:ir,initialCreateFlow:n==="create",onCreateFlowActiveChange:m,onCreateFlowComplete:F,onChange:A,emptyMessage:"No document controls yet."})})]})})}function lr(t){return(t.controls||[]).map(s=>s.id)}function dr(t){const s={};for(const n of t)n.defaultValue!==void 0&&(s[n.id]=n.defaultValue);return s}function cr(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 ur({allInputs:t,documentSheetId:s,currentDocumentInputs:n,nextControls:r,nextDefaultValues:o,change:l}){const d=new Map(r.map(p=>[p.id,cr(p,o)])),u=(l==null?void 0:l.type)==="rename"?{oldId:l.oldId,newId:l.newId}:null,c=new Set,m=[];for(const p of n){if(p.kind!=="control"){m.push(p);continue}const f=d.get(p.control.id)||((u==null?void 0:u.oldId)===p.control.id?d.get(u.newId):void 0);if(!f)continue;c.add(f.id);const E=i.createUniqueDashboardInputVariableNameFromName(f.id,[...t,...m].filter(j=>j.id!==p.id)),S=f.id===E?f:{...f,id:E};m.push({...p,label:S.label,variableName:E,requiredAtExecution:S.requiredAtExecution,control:S})}for(const p of d.values())c.has(p.id)||m.push(i.createDashboardControlInputFromControl({control:p,existingInputs:[...t,...m],sheetId:s}));const x=new Set(n.map(p=>p.id));return[...t.filter(p=>!x.has(p.id)),...m]}function Es({showFilters:t,onShowFiltersChange:s,pickerContent:n,settingsContent:r,size:o="default",className:l,primaryButtonClassName:d,secondaryButtonClassName:u,pickerContentClassName:c,settingsContentClassName:m}){const x=o==="toolbar",[y,p]=h.useState(!1),f=i.useSurfaceAppearance("interactive");return e.jsxs("div",{className:a.cn("relative inline-flex items-stretch overflow-hidden rounded-control border border-input bg-background",x?"h-8":"h-7",l),children:[e.jsxs(a.Popover,{open:t,onOpenChange:s,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs(a.Button,{variant:"ghost",size:"xs",className:a.cn("h-full rounded-none border-0 bg-transparent pl-2.5 pr-2 shadow-none hover:bg-accent/50 data-[state=open]:bg-accent/60",d),children:[t?e.jsx($n,{className:"h-3.5 w-3.5"}):e.jsx(i.Filter,{className:"h-3.5 w-3.5"}),"Filter"]})}),e.jsx(a.PopoverContent,{align:"end",sideOffset:6,className:a.cn("w-auto rounded-card border border-border/60 p-0 shadow-sm",c),style:f.contentStyle,children:n})]}),e.jsxs(a.Popover,{open:y,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:f.contentStyle,children:r(()=>p(!1))})]})]})}function mr(){ee.useSyncLegacyEditorState();const t=a.useDashboardStore(c=>c.selectedSheetId),s=a.useDashboardStore(c=>c.selectedFrameId),n=a.useDashboardStore(c=>c.dashboard),r=a.useDashboardStore(c=>c.actions.getSelectedFrame),{setSelectedFrameId:o}=a.useDashboardActions(),{setCard:l}=a.useEditorActions(),d=a.useEditorStore(c=>c.card.dataSource);return h.useEffect(()=>{var m,x;let c=r();if(!c){const y=(m=n==null?void 0:n.sheets)==null?void 0:m.find(f=>f.id===t),p=(x=y==null?void 0:y.frames)==null?void 0:x[0];p&&(o(p.id),c=p)}if(c){const y=c.cards.find(p=>p.id===c.activeCardId);y&&l(y)}},[r,t,s,n,o,l]),{hasEntities:!!(d!=null&&d.selectedEntities&&d.selectedEntities.length>0)}}function hr(){const t=a.useDashboardStore(u=>u.dashboard),s=a.useDashboardStore(u=>u.semanticExecutionPayload),n=a.useDashboardStore(u=>u.actions.addFilter),{hasEntities:r}=mr(),o=h.useMemo(()=>i.getGlobalDateFilterCoverage(t,s),[t,s]),d=!i.getGlobalDateFilter(t.filters)&&o.hasEligibleCards;return e.jsxs("div",{className:"flex h-[520px] w-[400px] flex-col",children:[d&&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(i.Sparkles,{className:"h-2.5 w-2.5"}),"Suggested"]}),e.jsxs("button",{type:"button",onClick:()=>n(i.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(i.CalendarRange,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"text-[12px] font-medium text-foreground",children:"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(i.Database,{className:"mb-3 h-10 w-10 text-muted-foreground/50"}),e.jsx("h3",{className:"mb-1 text-[13px] font-medium text-foreground",children:"No fields configured"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Configure a data source for this card to enable filtering."})]}),r&&e.jsx("div",{className:"flex flex-1 overflow-hidden",children:e.jsx(i.FilterableFieldsPanel,{context:"filter"})})]})}const Jt=!1;function xr({onAddFilter:t,onAddControl:s,onManageControls:n,onDismiss:r}){const o=a.useDashboardStore(u=>u.dashboard.filterLayout),{setFilterLayout:l}=a.useDashboardActions();o!=null&&o.displayMode;const d=(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(ct,{icon:i.Filter,label:"Add filter",onClick:()=>{t(),r()}}),e.jsx(ct,{icon:a.SlidersHorizontal,label:"Add control",onClick:()=>{s(),r()}}),e.jsx(ct,{icon:i.Pencil,label:"Manage controls",onClick:()=>{n(),r()}})]}),e.jsx("div",{className:"border-t border-border/60"}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"px-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Display"}),Jt,e.jsx(pr,{id:"filter-display-wrap",label:"Wrap to multiple lines",checked:d,onCheckedChange:u=>l({toolbarWrap:u===!0})}),Jt]})]})}function ct({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 pr({id:t,label:s,checked:n,onCheckedChange:r}){return e.jsxs("div",{className:"flex items-center gap-2 rounded-[4px] px-1 py-1 transition-colors hover:bg-muted/40",children:[e.jsx(i.Checkbox,{id:t,checked:n,onCheckedChange:r}),e.jsx(a.Label,{htmlFor:t,className:"cursor-pointer text-[12px] font-normal leading-[1.3]",children:s})]})}function fr({size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:l}){var B;const[d,u]=h.useState(null),c=a.useDashboardStore(I=>I.dashboard),m=a.useDashboardStore(I=>I.selectedSheetId),x=a.useDashboardStore(I=>I.showFilters),y=i.useAssistantLayoutStore(I=>I.setPanelOpen),p=a.useDashboardStore(I=>I.actions),{setDocumentInspectorTab:f,setShowFilters:E}=p,S=(B=c.sheets)==null?void 0:B.find(I=>I.id===m),j=a.isDocumentSheet(S),b=h.useCallback(I=>{window.setTimeout(()=>{u(I)},0)},[]),w=h.useCallback(I=>{if(j&&m){I&&f(m,"inputs");return}I&&y("dashboard",!1),E(I)},[j,m,f,y,E]),v=h.useCallback(()=>{w(!0)},[w]),F=h.useCallback(()=>{b("create")},[b]),A=h.useCallback(()=>{b("manage")},[b]);return e.jsxs(e.Fragment,{children:[e.jsx(Es,{showFilters:j?!1:x,onShowFiltersChange:w,pickerContent:e.jsx(hr,{}),settingsContent:I=>e.jsx(xr,{onAddFilter:v,onAddControl:F,onManageControls:A,onDismiss:I}),size:t,className:s,primaryButtonClassName:n,secondaryButtonClassName:r,pickerContentClassName:o,settingsContentClassName:l}),d?j?e.jsx(ks,{open:!0,onOpenChange:I=>{I||u(null)},initialMode:d}):e.jsx(Ds,{open:!0,onOpenChange:I=>{I||u(null)},showTrigger:!1,initialMode:d}):null]})}class wt extends Error{constructor(s,n,r){super(s),this.status=n,this.details=r,this.name="BriefingsApiError"}}function Is(t,s){return`${t.replace(/\/$/,"")}${s}`}function ne(t){return encodeURIComponent(t)}function Qe(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 gr(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 As(t){if(!t||typeof t!="object")return null;const s=t;return typeof s.error=="string"?s.error:null}async function de(t,s,n,r){const o=await fetch(Is(t,n),{cache:(r==null?void 0:r.cache)??"no-store",...r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,...(r==null?void 0:r.headers)||{}}}),l=await o.json().catch(()=>({}));if(!o.ok)throw new wt(As(l)||"Briefings API request failed",o.status,l);return l}async function Ts(t,s,n,r){const o=await fetch(Is(t,n),{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){const l=await gr(o);throw new wt(As(l)||"Briefing artifact request failed",o.status,l)}return{kind:r,content:await o.text(),contentType:o.headers.get("content-type")??"text/plain",filename:br(o.headers.get("content-disposition"))}}function br(t){if(!t)return;const s=/filename="([^"]+)"/.exec(t);return s==null?void 0:s[1]}async function Fs(t,s,n){return de(t,s,`/v1/briefings${Qe({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 yr(t,s,n){return de(t,s,`/v1/briefings/tenant-summaries${Qe({status:n==null?void 0:n.status})}`)}async function Nt(t,s,n){return de(t,s,`/v1/briefings/${ne(n)}`)}async function Rs(t,s,n){return de(t,s,"/v1/briefings",{method:"POST",body:JSON.stringify(n)})}async function Je(t,s,n,r){return de(t,s,`/v1/briefings/${ne(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Ct(t,s,n){return Je(t,s,n,{status:"PAUSED"})}async function St(t,s,n){return Je(t,s,n,{status:"ACTIVE"})}async function Dt(t,s,n){return de(t,s,`/v1/briefings/${ne(n)}`,{method:"DELETE"})}async function kt(t,s,n,r){return de(t,s,`/v1/briefings/${ne(n)}/runs`,{method:"POST",body:JSON.stringify(r)})}async function Ps(t,s,n){return de(t,s,"/v1/briefings/preview-plan",{method:"POST",body:JSON.stringify({draft:n})})}async function Ls(t,s,n){return de(t,s,"/v1/briefings/preview-runs",{method:"POST",body:JSON.stringify(n)})}async function Ms(t,s,n){return(await de(t,s,`/v1/briefings/preview-runs/${ne(n)}`)).previewRun}async function jr(t,s,n,r){return de(t,s,`/v1/briefings/${ne(n)}/runs${Qe({status:r==null?void 0:r.status,cursor:r==null?void 0:r.cursor,limit:r==null?void 0:r.limit})}`)}async function Et(t,s,n,r){return(await de(t,s,`/v1/briefings/${ne(n)}/runs/${ne(r)}`)).run}async function Bs(t,s,n,r){return de(t,s,`/v1/briefings/${ne(n)}/runs/${ne(r)}`,{method:"PATCH",body:JSON.stringify({action:"cancel"})})}async function Vs(t,s,n,r){return de(t,s,`/v1/briefings/${ne(n)}/runs/${ne(r)}`,{method:"DELETE"})}async function vr(t,s,n,r,o){return Ts(t,s,`/v1/briefings/${ne(n)}/runs/${ne(r)}/artifact${Qe({kind:o})}`,o)}async function wr(t,s,n,r){return Ts(t,s,`/v1/briefings/${ne(n)}/runs/${ne(r)}/evidence`,"evidence")}const Nr={pageSize:"letter",orientation:"portrait",includeFilters:!0,includeTimestamp:!0},Cr={delimiter:",",includeHeaders:!0,useFormattedValues:!0};function fe(t){return X(t)}function Yt(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 It(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 Sr(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 Os(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 zs(n)}}}function Dr(t,s){return Os(t).includes(s)?{...fe(t),format:s,settings:_s(t.settings,s)}:fe(t)}function kr(t,s){const n={...t.settings,...s};return n.includeFilters===!1&&delete n.filterLine,{...fe(t),settings:n}}function Us(t){var d,u;if(t.source.type!=="dashboard")return[];const s=t.source.dashboardId,n=t.dashboard,r=[{key:`dashboard:${s}:all`,kind:"dashboard",title:"Full dashboard PDF",detail:"All dashboard sheets",dashboardId:s,formats:["pdf"],defaultFormat:"pdf"}];if(!n)return r;const o=a.getDashboardSheets(n.sheets),l=o.find(c=>c.id===t.selectedSheetId)??o[0];l&&r.push({key:`dashboard_sheet:${s}:${l.id}`,kind:"dashboard_sheet",title:`${mt(l)} PDF`,detail:"Current dashboard sheet",dashboardId:s,sheetId:l.id,formats:["pdf"],defaultFormat:"pdf"});for(const c of n.sheets||[])a.isDocumentSheet(c)&&r.push({key:`document_sheet:${s}:${c.id}`,kind:"document_sheet",title:`${mt(c)} PDF`,detail:"Paginated report sheet",dashboardId:s,sheetId:c.id,formats:["pdf"],defaultFormat:"pdf"});if(l)for(const c of qs(l)){if(c.card.type==="text")continue;const m=zs(c.card.type);r.push({key:`card:${s}:${c.card.id}`,kind:"card",title:c.card.title||"Untitled card",detail:`${mt(l)} · ${c.card.type}`,dashboardId:s,sheetId:l.id,cardId:c.card.id,cardType:c.card.type,frameId:(d=c.frame)==null?void 0:d.id,cardControlDefinitions:c.card.controls,controlBindings:c.card.controlBindings,tablePreferences:(u=c.card.preferences)==null?void 0:u.tablePrefs,formats:m,defaultFormat:i.getDefaultExportFormat(c.card.type)})}return r}function gt(t){const{option:s}=t,n=t.format??s.defaultFormat,r=Er({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:ut(s.sheetId),format:"pdf",title:s.title,settings:r};case"document_sheet":return{type:"document_sheet",dashboardId:s.dashboardId,sheetId:ut(s.sheetId),format:"pdf",title:s.title,settings:r};case"card":return{type:"card",dashboardId:s.dashboardId,cardId:ut(s.cardId),format:n,title:s.title,settings:r}}}function Zt(t){const s=Us(t),n=s.find(l=>l.kind==="dashboard_sheet"),o=s.find(l=>l.kind==="dashboard")??n;return o?[gt({option:o,runtime:t.runtime})]:[]}function Er(t){const s={..._s(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=X(t.option.cardControlDefinitions)),t.option.controlBindings&&(s.controlBindings=X(t.option.controlBindings)),t.option.tablePreferences&&(s.tablePreferences=X(t.option.tablePreferences))),Ir({settings:s,option:t.option,runtime:n}),s.includeFilters!==!1&&(s.filterLine=Pr(s.filterValues)),s}function Ir(t){const{settings:s,option:n,runtime:r}=t;if(!r)return;if(n.kind==="card"){Ar({settings:s,option:n,runtime:r});return}const o=n.kind==="dashboard"?"all":"current",l=n.kind==="dashboard"?r.selectedSheetId:n.sheetId,d=i.buildDashboardExecutionSnapshot({dashboard:r.dashboard||void 0,filterValues:r.filterValues,selectedSheetId:l,sheetSelection:o,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});s.sheetFilterValues=X(d.filterValues),s.filterValues=X(d.filterValues),s.controlValues=X(d.controlValues),r.controlDefinitions&&(s.controlDefinitions=X(r.controlDefinitions));const u=Tr({option:n,runtime:r,selectedSheetId:n.kind==="dashboard"&&o==="all"?void 0:l,sheetSelection:o});u&&(s.dashboardInputExecutionSnapshot=X(u))}function Ar(t){var m,x,y;const{settings:s,option:n,runtime:r}=t,o=n.cardId,l=i.getSheetScopedFilterValues(r.filters,r.filterValues,n.sheetId);if(s.sheetFilterValues=X(l),!o){s.filterValues=X(l),s.controlValues=X(r.controlValues||{}),r.controlDefinitions&&(s.controlDefinitions=X(r.controlDefinitions));return}const d=((m=r.inlineFilterValuesMap)==null?void 0:m[o])||[];d.length>0&&(s.inlineFilterValues=X(d));const u=i.buildDashboardCardExecutionSnapshot({dashboard:r.dashboard||void 0,cardId:o,interactionStates:r.interactionStates||{},currentDashboardId:(x=r.dashboard)==null?void 0:x.id,semanticExecutionPayload:r.semanticExecutionPayload,filters:r.filters,filterValues:r.filterValues,inlineFilterValuesMap:{...r.inlineFilterValuesMap||{},[o]:d},dashboardControls:r.dashboardControls||r.controlDefinitions,dashboardControlValues:r.controlValues,cardControlValuesMap:r.cardControlValuesMap});u?(s.filterValues=X(u.queryContext.cardFilterValues),s.controlValues=X(u.queryContext.controlValues),s.controlDefinitions=X(u.queryContext.controlDefinitions),s.cardControlDefinitions=X(u.queryContext.cardControlDefinitions),s.controlBindings=X(u.queryContext.controlBindings)):(s.filterValues=X(l),s.controlValues={...r.controlValues||{},...((y=r.cardControlValuesMap)==null?void 0:y[o])||{}},r.controlDefinitions&&(s.controlDefinitions=X(r.controlDefinitions)));const c=Fr({option:n,runtime:r,filterValues:s.filterValues,inlineFilterValues:d,controlValues:s.controlValues});c&&(s.dashboardInputExecutionSnapshot=X(c))}function Tr(t){var u;const{option:s,runtime:n}=t,r=n.dashboard;if(!((u=r==null?void 0:r.inputs)!=null&&u.length))return;const o=new Date().toISOString(),l=$s();if(s.kind==="document_sheet"&&s.sheetId)return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:s.sheetId,sheetKind:"document",mode:"document",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:o,timezone:l}).snapshot;const d=t.sheetSelection==="all"?a.getDashboardSheets(r.sheets).map(c=>c.id):t.selectedSheetId?[t.selectedSheetId]:[];if(d.length!==0)return i.buildDashboardSheetsInputExecutionSnapshot({dashboard:r,sheetIds:d,sheetKind:"dashboard",mode:"dashboard",runtimeValues:{dashboardInputValues:n.dashboardInputValues,filterValues:n.filterValues,controlValues:n.controlValues,inlineFilterValuesMap:n.inlineFilterValuesMap,cardControlValuesMap:n.cardControlValuesMap},generatedAt:o,timezone:l}).snapshot}function Fr(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=Rr(r,s.sheetId,s.cardId),l=t.inlineFilterValues!==void 0?{...n.inlineFilterValuesMap||{},[s.cardId]:t.inlineFilterValues}:n.inlineFilterValuesMap,d=t.filterValues!==void 0?i.applyFilterOverridesToDashboardInputSlots({dashboardInputValues:n.dashboardInputValues,dashboard:r,filterValues:t.filterValues,sheetId:(o==null?void 0:o.sheet.id)||s.sheetId,cardId:s.cardId,sheetKind:"dashboard"}):n.dashboardInputValues;return i.buildDashboardInputExecutionSnapshot({dashboard:r,sheetId:(o==null?void 0:o.sheet.id)||s.sheetId,card:(o==null?void 0:o.card)||null,sheetKind:"dashboard",mode:"visual",runtimeValues:{dashboardInputValues:d,filterValues:t.filterValues??n.filterValues,controlValues:t.controlValues??n.controlValues,inlineFilterValuesMap:l,cardControlValuesMap:n.cardControlValuesMap},generatedAt:new Date().toISOString(),timezone:$s()}).snapshot}function Rr(t,s,n){const r=t.sheets||[],o=s?r.filter(l=>l.id===s):r;for(const l of o)for(const d of qs(l))if(d.card.id===n)return{sheet:l,card:d.card}}function $s(){return typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Pr(t){if(!Array.isArray(t))return"";const s=t.filter(n=>!!n&&typeof n=="object"&&typeof n.name=="string");return i.formatFilterLine(s)}function _s(t,s){return s==="csv"?{...Cr,...t}:{...Nr,...t}}function zs(t){return t?i.getSupportedExportFormats(t).filter(s=>s!=="png"):["pdf"]}function qs(t){const s=[],n=new Set,r=(o,l)=>{!(o!=null&&o.id)||n.has(o.id)||(n.add(o.id),s.push({card:o,frame:l}))};for(const o of t.cards||[])r(o);for(const o of t.frames||[])for(const l of o.cards||[])r(l,o);return s}function ut(t){if(!t)throw new Error("Briefing attachment option is missing a required id.");return t}function mt(t){var s;return((s=t.title)==null?void 0:s.trim())||"Untitled sheet"}function X(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}const Hs=["markdown"],Lr={name:"",description:"",instruction:"",source:{type:"project"},body:{type:"generated_analysis",instruction:""},attachments:[],output:{artifactFormats:[...Hs],includeEvidence:!0,includeSql:!0},schedule:{enabled:!1,scheduleExpr:"",timezone:"UTC",status:"ACTIVE"},delivery:{enabled:!1,recipients:[],channels:[],subject:"",message:""},limits:{}};function Ws(t){const s=t.trim();return s.length>0?s:void 0}function Mr(t){return{...t,source:{...t.source},body:{...t.body},attachments:t.attachments.map(fe),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 Br(t){return t.type==="generated_analysis"?t.instruction:t.type==="custom_message"?t.message:""}function Gs(t,s){return t.type==="custom_message"?{type:"custom_message",message:s}:t.type==="none"?{type:"none"}:{type:"generated_analysis",instruction:s}}function At(t){return Gs(t.body,t.instruction.trim())}function Ks(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 Xs(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 Tt(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 Qs(t){return t.recipients.length===0&&t.channels.length===0?null:{recipients:t.recipients.map(s=>({...s})),channels:[...t.channels],channelConfigs:Tt(t.channelConfigs,t.channels)}}function Vr(t){return{artifactFormats:t!=null&&t.artifactFormats&&t.artifactFormats.length>0?[...t.artifactFormats]:[...Hs],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 Or(t){return t.body.type==="generated_analysis"?t.body.instruction:t.body.type==="custom_message"?t.body.message:""}function Ur(t){return{enabled:!0,recipients:(t==null?void 0:t.recipients.map(s=>({...s})))??[],channels:t!=null&&t.channels?[...t.channels]:[],subject:"",message:"",channelConfigs:Tt(t==null?void 0:t.channelConfigs,(t==null?void 0:t.channels)??[])}}function $r(t,s,n){return t===void 0||Number.isInteger(t)&&t>=s&&t<=n}function _r(t){const s=t.trim();return s.includes("@")&&s.includes(".")&&!s.includes(" ")}function ht(t,s,n,r,o){$r(n,r,o)||t.push({field:`limits.${s}`,message:`${s} must be an integer between ${r} and ${o}`})}function Js(t){return ze(Lr,t??{})}function ze(t,s){var d,u,c,m;const n=s.instruction??(s.body?Br(s.body):t.instruction),r=Gs(s.body?{...s.body}:{...t.body},n),o=(d=s.delivery)!=null&&d.channels?[...s.delivery.channels]:[...t.delivery.channels],l=Tt(((u=s.delivery)==null?void 0:u.channelConfigs)??t.delivery.channelConfigs,o);return{...Mr(t),...s,instruction:n,source:s.source?{...s.source}:{...t.source},body:r,attachments:s.attachments?s.attachments.map(fe):t.attachments.map(fe),output:{...t.output,...s.output,artifactFormats:(c=s.output)!=null&&c.artifactFormats?[...s.output.artifactFormats]:[...t.output.artifactFormats]},schedule:{...t.schedule,...s.schedule},delivery:{...t.delivery,...s.delivery,recipients:(m=s.delivery)!=null&&m.recipients?s.delivery.recipients.map(x=>({...x})):t.delivery.recipients.map(x=>({...x})),channels:o,channelConfigs:l},limits:{...t.limits,...s.limits}}}function Te(t){return{name:t.name,description:t.description??"",instruction:Or(t),source:{...t.source},body:{...t.body},attachments:t.attachments.map(fe),output:Vr(t.presentation),schedule:{enabled:!!t.scheduleExpr,scheduleExpr:t.scheduleExpr??"",timezone:t.timezone||"UTC",status:t.status==="PAUSED"||t.status==="DISABLED"?t.status:"ACTIVE"},delivery:Ur(t.deliveryConfig),limits:t.limits?{...t.limits}:{}}}function bt(t){return{name:t.name.trim(),description:Ws(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:At(t),attachments:t.attachments.map(fe),presentation:Ks(t.output),limits:Xs(t.limits),deliveryConfig:Qs(t.delivery)}}function Ys(t){return{name:t.name.trim(),description:Ws(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:At(t),attachments:t.attachments.map(fe),presentation:Ks(t.output),limits:Xs(t.limits),deliveryConfig:Qs(t.delivery)}}function yt(t){var r,o,l;const s=[];t.name.trim()||s.push({field:"name",message:"Name is required"});const n=At(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)&&(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((d,u)=>{d.type==="email"&&!_r(d.address)&&s.push({field:`delivery.recipients.${u}.address`,message:"Email recipient address is invalid"})}),t.delivery.channels.includes("WEBHOOK"))){const d=(r=t.delivery.channelConfigs)==null?void 0:r.WEBHOOK;(l=(o=d==null?void 0:d.webhookConfig)==null?void 0:o.url)!=null&&l.trim()||s.push({field:"delivery.channelConfigs.WEBHOOK.webhookConfig.url",message:"Webhook URL is required for webhook delivery"})}return ht(s,"maxToolCalls",t.limits.maxToolCalls,1,100),ht(s,"maxRows",t.limits.maxRows,1,1e5),ht(s,"timeoutMs",t.limits.timeoutMs,1e3,30*6e4),{valid:s.length===0,issues:s}}const Be="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function zr({attachment:t,open:s,onOpenChange:n,onChange:r,children:o}){const l=Os(t),d=t.settings||{},u=t.format==="csv",c=m=>{r(kr(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(Be,"mb-1"),children:"Attachment"}),e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:It(t)})]}),l.length>1?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Be,"mb-1 block"),children:"Format"}),e.jsxs(a.Select,{value:t.format,onValueChange:m=>r(Dr(t,m)),children:[e.jsx(a.SelectTrigger,{size:"sm",className:"h-8 text-[12.5px]",children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:l.map(m=>e.jsx(a.SelectItem,{value:m,children:m.toUpperCase()},m))})]})]}):null,u?e.jsx(Hr,{settings:d,onChange:c}):e.jsx(qr,{settings:d,onChange:c})]})]})}function qr({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(Be,"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(Be,"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(qe,{label:"Include filters",checked:t.includeFilters??!0,onChange:n=>s({includeFilters:n})}),e.jsx(qe,{label:"Include timestamp and footer",checked:t.includeTimestamp??!0,onChange:n=>s({includeTimestamp:n})})]})]})}function Hr({settings:t,onChange:s}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Be,"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(qe,{label:"Include headers",checked:t.includeHeaders??!0,onChange:n=>s({includeHeaders:n})}),e.jsx(qe,{label:"Use formatted values",checked:t.useFormattedValues??!0,onChange:n=>s({useFormattedValues:n})})]})]})}function qe({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-foreground/80",children:[e.jsx(i.Checkbox,{checked:s,onCheckedChange:r=>n(r===!0)}),e.jsx("span",{children:t})]})}function Wr({attachments:t,onChange:s,onAdd:n,disabled:r}){const o=t.length===0;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{type:"button",disabled:r,onClick:n,"aria-label":o?"Attach files":"Add another attachment",className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Paperclip,{className:"h-3 w-3"}),o?"Attach":null]}),t.map((l,d)=>e.jsx(Gr,{attachment:l,disabled:r,onUpdate:u=>{const c=[...t];c[d]=u,s(c)},onRemove:()=>s(t.filter((u,c)=>c!==d))},`${l.type}:${d}:${It(l)}`)),o?null:e.jsxs("button",{type:"button",disabled:r,onClick:n,className:"inline-flex h-6 items-center gap-1 rounded-control px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"Add"]})]})}function Gr({attachment:t,disabled:s,onUpdate:n,onRemove:r}){const[o,l]=h.useState(!1),d=It(t),u=Sr(t),c=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?`${d} · ${u}`:d,children:[e.jsx(zr,{attachment:t,open:o,onOpenChange:l,onChange:n,children:e.jsxs("button",{type:"button",disabled:s,className:"inline-flex max-w-[180px] items-center gap-1 disabled:opacity-50",children:[e.jsx(Kr,{format:t.format,className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate font-medium text-foreground",children:d}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground/70",children:c})]})}),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 ${d}`,children:e.jsx(a.X,{className:"h-2.5 w-2.5"})})]})}function Kr({format:t,className:s}){const n=t==="csv"?i.FileSpreadsheet:i.FileText;return e.jsx(n,{className:a.cn(s)})}const Xr="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Qr({open:t,onOpenChange:s,source:n,dashboard:r,selectedSheetId:o,runtime:l,selectedAttachments:d,onSubmit:u}){const c=h.useMemo(()=>Us({source:n,dashboard:r,selectedSheetId:o}),[n,r,o]),[m,x]=h.useState([]);h.useEffect(()=>{if(!t)return;const A=[];for(const B of d){const I=Yt(B),D=c.find(P=>P.formats.some($=>{const V=gt({option:P,format:$,runtime:l});return Yt(V)===I}));D&&A.push({optionKey:D.key,format:B.format??D.defaultFormat})}x(A)},[t,c,d,l]);const y=h.useMemo(()=>new Set(m.map(A=>A.optionKey)),[m]),p=h.useMemo(()=>{const A={};for(const B of m)A[B.optionKey]=B.format;return A},[m]),f=(A,B)=>{x(I=>I.some(P=>P.optionKey===A)?I.filter(P=>P.optionKey!==A):[...I,{optionKey:A,format:B}])},E=(A,B)=>{x(I=>I.map(D=>D.optionKey===A?{...D,format:B}:D))},S=()=>{const A=[];for(const B of m){const I=c.find(D=>D.key===B.optionKey);I&&A.push(gt({option:I,format:B.format,runtime:l}))}u(A),s(!1)},j=()=>s(!1),b=h.useMemo(()=>c.filter(A=>A.kind==="dashboard"||A.kind==="dashboard_sheet"),[c]),w=h.useMemo(()=>c.filter(A=>A.kind==="document_sheet"),[c]),v=h.useMemo(()=>c.filter(A=>A.kind==="card"),[c]),F=m.length;return e.jsx(i.Dialog,{open:t,onOpenChange:s,children:e.jsxs(i.DialogContent,{className:"flex max-h-[80vh] w-[min(560px,calc(100vw-32px))] max-w-none flex-col gap-0 rounded-card p-0",showCloseButton:!0,children:[e.jsxs(i.DialogHeader,{className:"border-b border-border px-4 py-3 text-left",children:[e.jsx(i.DialogTitle,{className:"text-[14px] font-semibold leading-5",children:"Add attachments"}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Choose what gets sent with this briefing."})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:n.type!=="dashboard"?e.jsx("div",{className:"rounded-card border border-dashed border-border px-3 py-3 text-[12px] leading-[1.55] text-muted-foreground",children:"Attachments are available when authoring from a dashboard."}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(xt,{label:"Dashboard",options:b,selectedOptionKeys:y,formatByOptionKey:p,onToggle:f,onFormatChange:E}),e.jsx(xt,{label:"Paginated reports",options:w,selectedOptionKeys:y,formatByOptionKey:p,onToggle:f,onFormatChange:E,emptyText:"No paginated report sheets are available."}),e.jsx(xt,{label:"Current sheet cards",options:v,selectedOptionKeys:y,formatByOptionKey:p,onToggle:f,onFormatChange:E,emptyText:"No exportable cards are available on the current dashboard sheet."})]})}),e.jsxs(i.DialogFooter,{className:"flex flex-row items-center justify-between gap-2 border-t border-border px-4 py-3 sm:justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:F===0?"Nothing selected":`${F} selected`}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a.Button,{type:"button",variant:"outline",size:"xs",onClick:j,children:"Cancel"}),e.jsx(a.Button,{type:"button",size:"xs",onClick:S,disabled:n.type!=="dashboard",children:F>0?`Add ${F} ${F===1?"attachment":"attachments"}`:"Done"})]})]})]})})}function xt({label:t,options:s,selectedOptionKeys:n,formatByOptionKey:r,onToggle:o,onFormatChange:l,emptyText:d}){return e.jsxs("section",{children:[e.jsx("div",{className:a.cn(Xr,"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:d||"Nothing available."}):e.jsx("div",{className:"divide-y divide-border rounded-card border border-border",children:s.map(u=>{const c=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":c,onClick:()=>o(u.key,u.defaultFormat),className:"flex min-w-0 flex-1 items-start gap-2 text-left",children:[e.jsx(Jr,{selected:c}),e.jsx(Yr,{kind:u.kind,format:m,cardType:u.cardType,className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:u.title}),e.jsx("span",{className:"mt-0.5 block truncate text-[11px] text-muted-foreground",children:u.detail})]})]}),e.jsx("div",{className:"shrink-0",children:u.formats.length>1?e.jsxs(a.Select,{value:m,onValueChange:x=>l(u.key,x),children:[e.jsx(a.SelectTrigger,{size:"xs",className:"h-6 w-[72px]","aria-label":`Choose format for ${u.title}`,onClick:x=>x.stopPropagation(),children:e.jsx(a.SelectValue,{})}),e.jsx(a.SelectContent,{children:u.formats.map(x=>e.jsx(a.SelectItem,{value:x,children:x.toUpperCase()},x))})]}):e.jsx("span",{className:"inline-flex h-6 items-center text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:m})})]},u.key)})})]})}function Jr({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 Yr({kind:t,format:s,cardType:n,className:r}){const o=s==="csv"?i.FileSpreadsheet:t==="dashboard"?i.LayoutDashboard:t==="card"?n==="table"||n==="aggregateTable"||n==="pivotTable"||n==="detailTable"?ee.Rows3:a.ChartColumn:i.FileText;return e.jsx(o,{className:r})}const Zr=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ea=250;function Le(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 ta(t){return t.type==="user"?t.userId:t.type==="tenant_user"?t.tenantUserId:null}function sa(t){return t.type==="group"?t.groupId:null}function Me(t){return(t==null?void 0:t.trim().toLowerCase())||null}function es(t){return{kind:"user",id:t.id,name:t.name,email:t.email,type:t.type}}function ts(t){return{kind:"group",id:t.id,name:t.name,type:t.type,memberCount:t.memberCount,description:t.description}}function na({value:t,onChange:s,className:n,disabled:r=!1}){const o=h.useRef(null),[l,d]=h.useState(!1),[u,c]=h.useState(""),[m,x]=h.useState(0),[y,p]=h.useState(()=>new Map),[f,E]=h.useState(()=>new Map),[S,j]=h.useState("people"),b=i.useDebounce(u,ea),{currentUser:w}=i.useCurrentUserInfo(),v=(w==null?void 0:w.type)==="tenant",{users:F,isLoading:A}=i.useUnifiedUsers({search:b,active:!0,type:v?"tenant":"all",tenantId:v?w.tenantId:void 0,limit:25}),{groups:B,isLoading:I}=i.useGroups({search:b,type:v?"TENANT_GROUP":"all",tenantId:v?w.tenantId:void 0,limit:25}),D=h.useMemo(()=>new Set(t.map(Le)),[t]),P=h.useMemo(()=>new Set(t.map(ta).filter(N=>!!N)),[t]),$=h.useMemo(()=>new Set(t.map(sa).filter(N=>!!N)),[t]),V=h.useMemo(()=>{const N=new Map(y);return F.forEach(M=>{N.set(M.id,es(M))}),w!=null&&w.id&&N.set(w.id,{kind:"user",id:w.id,name:w.name||w.email||"User",email:w.email||"",type:w.type}),N},[y,F,w]),_=h.useMemo(()=>{const N=new Set;return t.forEach(M=>{var Z;if(M.type==="email"){const Oe=Me(M.address);Oe&&N.add(Oe);return}if(M.type==="group")return;const be=M.type==="tenant_user"?M.tenantUserId:M.userId,re=Me((Z=V.get(be))==null?void 0:Z.email);re&&N.add(re)}),N},[V,t]),U=h.useMemo(()=>{const N=new Map(f);return B.forEach(M=>{N.set(M.id,ts(M))}),N},[f,B]),L=h.useMemo(()=>F.filter(N=>{if(P.has(N.id))return!1;const M=Me(N.email);return M&&_.has(M)?!1:v?N.type==="tenant"&&N.tenantId===(w==null?void 0:w.tenantId):!0}).map(es),[F,P,_,v,w==null?void 0:w.tenantId]),q=h.useMemo(()=>L.filter(N=>N.type==="organization"),[L]),C=h.useMemo(()=>L.filter(N=>N.type==="tenant"),[L]),H=h.useMemo(()=>B.filter(N=>$.has(N.id)?!1:(w==null?void 0:w.type)==="tenant"?N.type==="TENANT_GROUP"&&N.tenantId===w.tenantId:!0).map(ts),[B,$,w==null?void 0:w.type,w==null?void 0:w.tenantId]),R=h.useMemo(()=>v?[{key:"people",label:"People",count:C.length},{key:"groups",label:"Groups",count:H.length}]:[{key:"people",label:"People",count:q.length},{key:"tenant_users",label:"Tenant users",count:C.length},{key:"groups",label:"Groups",count:H.length}],[H.length,v,q.length,C.length]),ae=h.useMemo(()=>S==="groups"?[]:S==="tenant_users"||v?C:q,[S,v,q,C]),te=h.useMemo(()=>S==="groups"?H:[],[S,H]),K=h.useMemo(()=>[...ae,...te],[ae,te]),se=K.length===0?0:Math.min(m,K.length-1),me=u.trim(),ge=Zr.test(me),z=Me(me),Se=z?_.has(z):!1,we=A||I,he=N=>{D.has(Le(N))||(s([...t,N]),c(""),x(0))},xe=N=>{s(t.filter(M=>Le(M)!==N))},T=()=>{!ge||Se||he({type:"email",address:me})},G=N=>{const M=Me(N.email);M&&_.has(M)||(p(be=>{const re=new Map(be);return re.set(N.id,N),re}),he(N.type==="tenant"?{type:"tenant_user",tenantUserId:N.id}:{type:"user",userId:N.id}))},Ae=N=>{E(M=>{const be=new Map(M);return be.set(N.id,N),be}),he({type:"group",groupId:N.id})},Ye=N=>{if(N.key==="Enter"){if(N.preventDefault(),ge&&!Se){T();return}const M=K[se];if((M==null?void 0:M.kind)==="user"){G(M);return}if((M==null?void 0:M.kind)==="group"){Ae(M);return}}else if(N.key==="ArrowDown")N.preventDefault(),x(M=>Math.min(M+1,Math.max(K.length-1,0)));else if(N.key==="ArrowUp")N.preventDefault(),x(M=>Math.max(M-1,0));else if(N.key==="Escape")d(!1);else if(N.key==="Backspace"&&u.length===0){const M=t[t.length-1];M&&xe(Le(M))}},Ve=t.map(N=>{const M=Le(N);if(N.type==="email")return{key:M,label:N.name||N.address,icon:e.jsx(i.AtSign,{className:"h-3 w-3"}),onRemove:()=>xe(M)};if(N.type==="group"){const Z=U.get(N.groupId);return{key:M,label:(Z==null?void 0:Z.name)||"Group",icon:e.jsx(Ns,{className:"h-3 w-3"}),onRemove:()=>xe(M)}}const be=N.type==="tenant_user"?N.tenantUserId:N.userId,re=V.get(be);return{key:M,label:(re==null?void 0:re.name)||(re==null?void 0:re.email)||"User",icon:e.jsx(i.User,{className:"h-3 w-3"}),onRemove:()=>xe(M)}});return e.jsx("div",{className:a.cn("relative",n),children:e.jsxs(a.Popover,{open:l&&!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",l?"border-ring ring-2 ring-ring/10":"border-border hover:border-border",r&&"cursor-not-allowed opacity-60"),onClick:()=>{var N;r||((N=o.current)==null||N.focus(),d(!0))},children:[Ve.map(N=>e.jsx(ra,{icon:N.icon,label:N.label,onRemove:N.onRemove},N.key)),e.jsx("input",{ref:o,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:u,disabled:r,placeholder:t.length>0?"Add more...":"Add people, emails, or groups",onChange:N=>{c(N.target.value),x(0),d(!0)},onFocus:()=>d(!0),onKeyDown:Ye})]})}),e.jsx(a.Content2,{align:"start",sideOffset:8,onOpenAutoFocus:N=>N.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(aa,{activeIndex:se,activeFilter:S,emailAlreadyAdded:Se,filters:R,groupSuggestions:te,loading:we,onAddEmail:T,onFilterChange:N=>{j(N),x(0)},onGroupClick:Ae,onUserClick:G,orderedSuggestions:K,query:me,queryIsEmail:ge,userSuggestions:ae,viewerType:w==null?void 0:w.type})})]})})}function ra({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 aa({activeIndex:t,activeFilter:s,emailAlreadyAdded:n,filters:r,groupSuggestions:o,loading:l,onAddEmail:d,onFilterChange:u,onGroupClick:c,onUserClick:m,orderedSuggestions:x,query:y,queryIsEmail:p,userSuggestions:f,viewerType:E}){const S=!l&&x.length===0&&!(p&&!n);return e.jsxs("div",{className:"py-1 text-[13px]",children:[e.jsx("div",{className:"flex items-center gap-1 border-b border-border/60 px-2 pb-1",children:r.map(j=>e.jsxs("button",{type:"button",onClick:()=>u(j.key),className:a.cn("inline-flex h-7 items-center gap-1 rounded-control px-2 text-[12px] transition-colors",s===j.key?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e.jsx("span",{children:j.label}),e.jsx("span",{className:a.cn("tabular-nums",s===j.key?"text-primary-foreground/70 ":"text-muted-foreground/70"),children:j.count})]},j.key))}),l?e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-[12px] text-muted-foreground",children:[e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Searching"]}):null,f.length>0?e.jsx(ss,{heading:"People",children:f.map(j=>{var w;const b=x.indexOf(j);return e.jsx(ns,{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:(w=(j.name||j.email||"?")[0])==null?void 0:w.toUpperCase()}),detail:j.name?j.email:void 0,tag:j.type==="organization"?"Org user":"Tenant user",viewerType:E,title:j.name||j.email,onClick:()=>m(j)},j.id)})}):null,o.length>0?e.jsx(ss,{heading:"Groups",children:o.map(j=>{const b=x.indexOf(j);return e.jsx(ns,{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(Ns,{className:"h-3 w-3"})}),detail:j.memberCount!==void 0?`${j.memberCount} member${j.memberCount===1?"":"s"}`:j.description??void 0,tag:j.type==="ORG_GROUP"?"Org group":"Tenant group",viewerType:E,title:j.name,onClick:()=>c(j)},j.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:d,className:"flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left hover:bg-muted",children:[e.jsx(zn,{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:y})]}),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:y?"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 ss({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 ns({active:t,avatar:s,detail:n,onClick:r,tag:o,title:l,viewerType:d}){return e.jsxs("button",{type:"button",onClick:r,className:a.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left",t?"bg-muted ":"hover:bg-muted "),children:[s,e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[13px] text-foreground",children:l}),n?e.jsx("span",{className:"block truncate text-[11px] text-muted-foreground",children:n}):null]}),d==="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 He(t){return t==="SUCCESS"||t==="FAILED"}function We(t){return t==="QUEUED"||t==="RUNNING"}function jt({apiServiceUrl:t,token:s,intervalMs:n,timeoutMs:r,fetchRun:o,onRun:l,onTerminalRun:d,onError:u,onTimeout:c}){const[m,x]=h.useState(null),[y,p]=h.useState("idle"),f=h.useRef(null),E=h.useRef({fetchRun:o,onRun:l,onTerminalRun:d,onError:u,onTimeout:c});h.useEffect(()=>{E.current={fetchRun:o,onRun:l,onTerminalRun:d,onError:u,onTimeout:c}},[o,u,l,d,c]);const S=h.useCallback(()=>{x(null),p("idle")},[]),j=h.useCallback(()=>{f.current=null},[]),b=h.useCallback(v=>{var F,A;if(E.current.onRun(v),He(v.status)){f.current=v.id,x(null),p("terminal"),(A=(F=E.current).onTerminalRun)==null||A.call(F,v);return}if(We(v.status)){f.current=null,x(v.id),p("polling");return}x(null),p("idle")},[]),w=h.useCallback(v=>{f.current!==v&&(x(v),p("polling"))},[]);return h.useEffect(()=>{if(!m||!t||!s)return;if(f.current===m){x(null),p("terminal");return}let v=!1,F=!1,A=null;const B=Date.now(),I=async()=>{var D,P,$,V,_,U;if(!(v||F)){if(Date.now()-B>r){x(L=>L===m?null:L),p("timed_out"),(P=(D=E.current).onTimeout)==null||P.call(D,m);return}F=!0;try{const L=await E.current.fetchRun({apiServiceUrl:t,token:s,runId:m});if(v)return;if(E.current.onRun(L),He(L.status)){f.current=L.id,x(q=>q===L.id?null:q),p("terminal"),(V=($=E.current).onTerminalRun)==null||V.call($,L);return}if(!We(L.status)){x(q=>q===L.id?null:q),p("idle");return}A=window.setTimeout(I,n)}catch(L){v||(p("error"),(U=(_=E.current).onError)==null||U.call(_,L))}finally{F=!1}}};return p("polling"),I(),()=>{v=!0,A&&window.clearTimeout(A)}},[m,t,n,r,s]),{activeRunId:m,isPolling:m!==null&&y==="polling",resetTerminalRun:j,startRun:b,startRunId:w,status:y,stop:S}}function rs({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 oa({includeEvidence:t,includeSql:s,includeHtml:n,onChange:r}){const o=[t,s,n].filter(Boolean).length;return e.jsxs(a.Popover,{children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Output options",children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"Output options",e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",o,"/3"]}),e.jsx(a.ChevronDown,{className:"h-3 w-3"})]})}),e.jsxs(a.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-[320px] rounded-card border-border bg-popover p-0 text-popover-foreground",children:[e.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output options"}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:"Choose what gets included in the rendered briefing."})]}),e.jsxs("div",{className:"space-y-2.5 px-3 py-2.5",children:[e.jsx(pt,{label:"Include evidence links",description:"Cite the queries and data behind each finding.",checked:t,onChange:l=>r("evidence",l)}),e.jsx(pt,{label:"Include SQL in evidence",description:"Show the SQL the briefing ran. Useful for debugging or for a technical audience.",checked:s,onChange:l=>r("sql",l)}),e.jsx(pt,{label:"Generate rich HTML report",description:"Send a styled HTML version alongside the markdown body.",checked:n,onChange:l=>r("html",l)})]})]})]})}function pt({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})]})]})}function ia({label:t,checked:s,onChange:n}){return e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-[12px] text-foreground/80",children:[e.jsx("input",{type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"sr-only"}),e.jsx("span",{"aria-hidden":!0,className:a.cn("flex h-3.5 w-3.5 items-center justify-center rounded-control border",s?"border-primary bg-primary":"border-border"),children:s?e.jsx(a.Check,{className:"h-2 w-2 text-primary-foreground",strokeWidth:3.5}):null}),t]})}const vt=`Tell me what changed in the business and what is driving it.
47
-
48
- Watch:
49
- - Top-line movement versus the previous period
50
- - Largest positive and negative drivers
51
- - Any segment, product, region, or account that explains the change
52
-
53
- Don't bother me unless:
54
- - The movement is meaningful enough for the team to act on
55
- - A single driver explains a large share of the movement
56
-
57
- Include in the briefing:
58
- - Executive summary in plain English
59
- - KPI comparison with current, previous, delta, and percent change
60
- - Driver table or chart when useful
61
- - 2-3 recommended next actions
62
- - Evidence link rather than raw SQL in the main body`,as=`Watch this dashboard for unusual movement.
63
-
64
- Focus on:
65
- - Spikes or drops versus recent history
66
- - Outliers by segment, product, region, or customer
67
- - Changes that are likely to need follow-up
68
-
69
- Include in the briefing:
70
- - What changed
71
- - Why it looks unusual
72
- - The most likely drivers
73
- - What the team should check next`,os=`Hi team,
74
-
75
- Sharing this dashboard. The PDF below has the selected dashboard view and current filters applied.
76
-
77
- Reply if you have questions.`,is=`Track customer health across the top accounts. Surface accounts that crossed a risk threshold, with the leading signal that flagged them.
78
-
79
- Watch:
80
- - Health score drops > 10 points in the last 14 days
81
- - Accounts within 5 points of the at-risk threshold
82
- - Resolution-time regressions on enterprise tickets
83
-
84
- Audience:
85
- Customer Success leads. Action-oriented — every at-risk row needs an owner.`,ls=`Short Slack-friendly digest. One headline, three bullets, no PDFs. Use emoji sparingly. Skip the analysis appendix — link to the dashboard.
86
-
87
- Watch:
88
- - Top-line movement WoW
89
- - The single biggest driver
90
- - Anything urgent the team should act on today
91
-
92
- Format:
93
- - Headline (≤ 12 words)
94
- - Three bullets max
95
- - Link to the full dashboard`;function la(t,s,n){const r=t.includes("markdown")?t.filter(o=>o!==s):["markdown"];return n?Array.from(new Set([...r,s])):r}const _e=[{label:"Email report",description:"Email body with dashboard attachments",seedsDashboardAttachment:!0,available:t=>t.type==="dashboard",draft:(t,s)=>({name:"Dashboard Email Report",instruction:os,body:{type:"custom_message",message:os},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:vt,body:{type:"generated_analysis",instruction:vt},output:{includeEvidence:!0,includeSql:!1}})},{label:"Anomaly watch",description:"Only surface unusual movement",draft:()=>({name:"Anomaly Watch Briefing",instruction:as,body:{type:"generated_analysis",instruction:as},output:{includeEvidence:!0,includeSql:!1}})},{label:"Customer health",description:"Daily watch on at-risk accounts",draft:()=>({name:"Customer Health Watch",instruction:is,body:{type:"generated_analysis",instruction:is},output:{includeEvidence:!0,includeSql:!1}})},{label:"Slack digest",description:"Short Slack-friendly digest, no PDFs",draft:()=>({name:"Slack Digest",instruction:ls,body:{type:"generated_analysis",instruction:ls},output:{includeEvidence:!1,includeSql:!1},delivery:{channels:["SLACK"]}})}],Q="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Ge="inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",Fe="inline-flex h-7 items-center gap-1.5 rounded-control border border-border bg-background px-2.5 text-[12px] text-foreground hover:bg-muted disabled:opacity-50",da="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 ca({scheduleExpr:t,timezone:s,onScheduleChange:n}){const r=h.useMemo(()=>i.parseScheduleExpr(t),[t]),[o,l]=h.useState(()=>Ke()),[d,u]=h.useState(null),c=i.buildSchedulePreview(r,s,ds(o),d?cs(d):null),[m,x]=h.useState(!1),y=b=>{n({scheduleExpr:i.buildScheduleExpr(b),timezone:s})},p=b=>{const w=b==="weekly"&&r.weekdays.length===0?[1,2,3,4,5]:r.weekdays;y({...r,repeats:b,weekdays:w})},f=(b,w)=>{y({...r,hour:b,minute:w})},E=b=>{y({...r,weekdays:b})},S=`${String(r.hour).padStart(2,"0")}:${String(r.minute).padStart(2,"0")}`,j=h.useMemo(()=>ua(),[]);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:Q,children:"When"}),e.jsx("span",{className:"truncate text-[11px] text-muted-foreground",children:c})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Q,"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(Q,"mb-1 block"),children:"Time"}),e.jsxs(a.Select,{value:S,onValueChange:b=>{const[w,v]=b.split(":").map(F=>parseInt(F,10));f(w,v)},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:j.map(({value:b,label:w})=>e.jsx(a.SelectItem,{value:b,children:w},b))})]})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(a.Popover,{open:m,onOpenChange:x,children:[e.jsx(a.PopoverTrigger,{asChild:!0,children:e.jsxs("button",{type:"button","aria-expanded":m,className:a.cn(Ge,"h-6 px-1.5 text-[11px]"),children:[e.jsx(i.Settings2,{className:"h-3 w-3"}),"More options",e.jsx(a.ChevronDown,{className:a.cn("h-3 w-3 text-muted-foreground/70 transition-transform",m&&"rotate-180")})]})}),e.jsxs(a.PopoverContent,{align:"end",className:"z-[60] w-[300px] space-y-2.5 p-3",onOpenAutoFocus:b=>b.preventDefault(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:Q,children:"More options"}),e.jsx("button",{onClick:()=>x(!1),className:"rounded-control p-0.5 text-muted-foreground/70 hover:bg-muted hover:text-foreground/80","aria-label":"Close",children:e.jsx(a.X,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Q,"mb-1 block"),children:"First occurrence"}),e.jsx(us,{icon:e.jsx(i.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:o,placeholder:"Pick a start date",disabledBefore:Ke(),onChange:b=>{b&&l(b)},renderLabel:b=>b?ds(b):"Today"})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Q,"mb-1 block"),children:"Timezone"}),e.jsxs(a.Select,{value:s,onValueChange:b=>n({scheduleExpr:i.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(i.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:i.COMMON_TIMEZONES.map(b=>e.jsx(a.SelectItem,{value:b,children:ma(b)},b))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Q,"mb-1 block"),children:"Ends"}),e.jsx(us,{icon:e.jsx(i.Calendar,{className:"h-3 w-3 text-muted-foreground/70"}),value:d,placeholder:"No end date",clearable:!0,clearLabel:"No end date",disabledBefore:o,onChange:u,renderLabel:b=>b?cs(b):"No end date"})]}),r.repeats==="weekly"?e.jsxs("div",{children:[e.jsx("label",{className:a.cn(Q,"mb-1 block"),children:"On these days"}),e.jsx("div",{className:"flex gap-1",children:["S","M","T","W","T","F","S"].map((b,w)=>{const v=r.weekdays.includes(w);return e.jsx("button",{type:"button",onClick:()=>{E(v?r.weekdays.filter(F=>F!==w):[...r.weekdays,w].sort())},className:a.cn("inline-flex h-7 w-7 items-center justify-center rounded-control border text-[11px] font-medium",v?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:border-border"),children:b},w)})})]}):null]})]})})]})}function ua(){const t=[];for(let s=0;s<24;s+=1)for(const n of[0,30]){const r=`${String(s).padStart(2,"0")}:${String(n).padStart(2,"0")}`;t.push({value:r,label:i.formatTimeLabel(s,n)})}return t}function ma(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 Ke(){const t=new Date;return t.setHours(0,0,0,0),t}function ha(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function ds(t){return ha(t,Ke())?"Today":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function cs(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function us({value:t,icon:s,placeholder:n,clearable:r,clearLabel:o,disabledBefore:l,onChange:d,renderLabel:u}){const[c,m]=h.useState(!1),x=u(t),y=!t;return e.jsxs(a.Popover,{open:c,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",y&&"text-muted-foreground/70"),children:y?n??x:x})]}),e.jsx(a.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"})]})}),e.jsxs(a.PopoverContent,{align:"start",className:"z-[60] w-auto p-0",onOpenAutoFocus:p=>p.preventDefault(),children:[e.jsx(i.Calendar$1,{mode:"single",selected:t??void 0,defaultMonth:t??l??Ke(),onSelect:p=>{d(p??null),m(!1)},disabled:l?{before:l}:void 0}),r?e.jsx("div",{className:"border-t border-border p-2",children:e.jsx("button",{type:"button",onClick:()=>{d(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 xa({source:t,resolvedSourceContext:s,sourceDetail:n,onChange:r}){const[o,l]=h.useState(!1),d=h.useRef(null),u=s.source.type==="dashboard"?s.source:null,c=u!==null;h.useEffect(()=>{if(!o)return;const j=b=>{const w=b.target;d.current&&!d.current.contains(w)&&!(w instanceof Element&&w.closest("[data-scope-popover]"))&&l(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[o]);const m=t.type==="project",x=s.source.type==="dashboard"?s.label??"This dashboard":"This dashboard",y=s.source.type==="dashboard"?s.detail??n??null:n,p="This project",f="Use any data in this project.",E=m?p:x,S=m?f:y;return c?e.jsxs("div",{className:"relative",children:[e.jsxs("button",{ref:d,type:"button",onClick:()=>l(j=>!j),"aria-expanded":o,className:"group flex w-full items-center justify-between rounded-card border border-border bg-muted/40 px-3 py-2 text-left hover:border-border",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[12px]",children:[e.jsx(i.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:E}),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(ms,{active:!m,label:x,detail:y??null,description:"Use only the datasets this dashboard already reads.",onSelect:()=>{u&&r(u),l(!1)},isLast:!1}),e.jsx(ms,{active:m,label:p,detail:"All project data",description:"Broaden scope so the briefing can reach any data in this project.",onSelect:()=>{r({type:"project"}),l(!1)},isLast:!0})]}):null]}):e.jsxs("div",{className:"rounded-card border border-border bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[12px]",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"text-foreground",children:E})]}),S?e.jsx("div",{className:"mt-0.5 pl-5 text-[11px] text-muted-foreground",children:S}):null]})}function ms({active:t,label:s,detail:n,description:r,onSelect:o,isLast:l}){return e.jsxs("button",{type:"button",onClick:o,className:a.cn("flex w-full items-start gap-2.5 px-3 py-2.5 text-left transition-colors hover:bg-muted ",!l&&"border-b border-border/60 "),children:[e.jsx("span",{"aria-hidden":!0,className:a.cn("mt-1 inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border",t?"border-primary":"border-border "),children:t?e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary"}):null}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-[12.5px]",children:[e.jsx(i.Database,{className:"h-3 w-3 shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"font-medium text-foreground",children:s}),n?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[11px] text-muted-foreground/70","aria-hidden":!0,children:"·"}),e.jsx("span",{className:"truncate text-[11px] text-muted-foreground/70",children:n})]}):null]}),e.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.45] text-muted-foreground",children:r})]})]})}const Zs=He,Ie=We;function pa(t,s,n){return n?t.includes(s)?t:[...t,s]:t.filter(r=>r!==s)}function fa(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 en(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 Ft(t){const s=Math.floor(t/60),n=t%60;return`${s}:${n.toString().padStart(2,"0")}`}function ue(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ga(t){if(!ue(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(d=>!ue(d)||typeof d.label!="string"?[]:[{type:d.type==="email"||d.type==="user"||d.type==="tenant_user"||d.type==="group"?d.type:"email",label:d.label,...typeof d.detail=="string"?{detail:d.detail}:{},...typeof d.memberCount=="number"?{memberCount:d.memberCount}:{},...typeof d.hasMoreMembers=="boolean"?{hasMoreMembers:d.hasMoreMembers}:{},...Array.isArray(d.previewMembers)?{previewMembers:d.previewMembers.flatMap(c=>!ue(c)||typeof c.label!="string"?[]:[{type:c.type==="user"||c.type==="tenant_user"||c.type==="email"?c.type:"email",label:c.label,...typeof c.detail=="string"?{detail:c.detail}:{}}])}:{}}]):null,o=Array.isArray(t.channels)?t.channels.filter(d=>typeof d=="string"):null,l=Array.isArray(t.attachments)?t.attachments.filter(d=>typeof d=="string"):null;return!s||!n||!r||!o||!l?null:{subject:s,body:n,...typeof t.bodyHtml=="string"&&t.bodyHtml.trim()?{bodyHtml:t.bodyHtml}:{},recipients:r,channels:o,attachments:l,...typeof t.attachmentNotice=="string"?{attachmentNotice:t.attachmentNotice}:{}}}function ba(t){if(!ue(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 tn(t){if(!ue(t.result))return null;const s=ue(t.result.deliveryReadiness)?t.result.deliveryReadiness:null,n=s&&ue(s.intent)?s.intent:null,r=ue(t.result.deliveryPackage)?t.result.deliveryPackage:null,o=ue(t.result.deliveryResult)?t.result.deliveryResult:null,l=ue(t.result.package)?t.result.package:null,d=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||"",c=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 f=ba(p);return f?[f]:[]}):[],x=Array.isArray(n==null?void 0:n.channels)?n.channels.filter(p=>typeof p=="string"):typeof(o==null?void 0:o.channel)=="string"?[o.channel]:[],y=Array.isArray(l==null?void 0:l.attachments)?l.attachments.flatMap(p=>ue(p)?typeof p.label=="string"?[p.label]:typeof p.title=="string"?[p.title]:typeof p.filename=="string"?[p.filename]:[]:[]):[];return{subject:d,body:u,...c?{bodyHtml:c}:{},recipients:m,channels:x,attachments:y}}function sn({html:t,title:s="Briefing HTML artifact",className:n}){const r=h.useMemo(()=>i.purify.sanitize(t,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style"]}),[t]);return e.jsx("iframe",{title:s,srcDoc:r,sandbox:"",className:a.cn("h-[760px] w-full rounded-card border border-border bg-background ",n)})}const W={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 ya(t){return t.status==="SUCCESS"?"Complete":t.status==="FAILED"?"Failed":t.status==="RUNNING"?"Running":"Queued"}function Rt(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;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 ja(t){return t.status==="SENT"?t.sentCount===1?"Email sent":`${t.sentCount} emails sent`:t.status==="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 va(t){return t.status==="SENT"?W.success.surface:t.status==="FAILED"?W.danger.surface:W.warning.surface}function nn(t){return t.status==="SUCCESS"?e.jsx(a.Check,{className:a.cn("h-3 w-3",W.success.icon)}):t.status==="FAILED"?e.jsx(a.X,{className:a.cn("h-3 w-3",W.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 wa=[{pattern:/^plan preview/i,label:"Plan preview"},{pattern:/^analysis preview/i,label:"Analysis preview"}];function Na(t){const s=t.runtime.split(/;\s*/).map(o=>o.trim()).filter(Boolean),n=t.toolCalls.split(/;\s*/).map(o=>o.trim()).filter(Boolean),r=[];for(const{pattern:o,label:l}of wa){const d=hs(s.find(c=>o.test(c))),u=hs(n.find(c=>o.test(c)));(d||u)&&r.push({label:l,duration:d,toolCalls:u})}return r}function hs(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 xs=3;function Ca({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:Q,children:"What I understood from your brief"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(pe,{field:"Datasets",value:e.jsx(Ma,{plan:t})}),e.jsx(pe,{field:"Investigate",value:t.understood.investigation}),e.jsx(pe,{field:"Threshold",value:t.understood.threshold}),e.jsx(pe,{field:"Audience",value:t.understood.audience}),e.jsx(pe,{field:"Format",value:t.understood.format,isLast:!0})]})]}),t.scope.grounding?e.jsx(Sa,{plan:t}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(Q,"mb-2"),children:"What I'll do"}),e.jsx("ol",{className:"space-y-3",children:t.steps.map(r=>e.jsx(Ba,{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:Q,children:"Scope"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 text-[12px] text-foreground/80",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:(n==null?void 0:n.trim())||t.scope.sourceLabel})]})]}),e.jsxs("div",{className:"rounded-card border border-border px-3 py-2",children:[e.jsx("div",{className:Q,children:"Estimate"}),(()=>{var d;const o=Na(t.estimate).find(u=>u.label.toLowerCase().includes("analysis")),l=(o==null?void 0:o.duration)??((d=t.estimate.runtime)==null?void 0:d.trim())??null;return e.jsx("div",{className:"mt-1 text-[12px] tabular-nums text-foreground/80",children:l??"—"})})()]})]}),t.ambiguities.length>0?e.jsx("div",{className:"rounded-card border border-border bg-muted px-2.5 py-1.5 text-[11px] leading-[1.55] text-muted-foreground",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("ul",{className:"space-y-0.5",children:t.ambiguities.map(r=>e.jsx("li",{children:r},r))})]})}):null,s&&!Ie(s.status)?e.jsx(rn,{run:s,labelPrefix:"Preview"}):null]})}function Sa({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:Q,children:"What I'll analyze"}),e.jsxs("div",{className:"mt-2 overflow-hidden rounded-card border border-border",children:[e.jsx(pe,{field:"Metric",value:s.metric??"Not selected yet"}),e.jsx(pe,{field:"Dataset",value:n}),e.jsx(pe,{field:"Time field",value:s.dateField??"Not selected yet"}),e.jsx(pe,{field:"Breakdown",value:r}),e.jsx(pe,{field:"Confidence",value:`${s.confidence} · ${s.reason}`,isLast:!0})]})]})}function rn({run:t,labelPrefix:s}){const n=t.progress??null,r=n?(n.recentEvents??[]).filter(c=>c.label!==n.label||c.updatedAt!==n.updatedAt).slice(-4).reverse():[],o=Ie(t.status),l=n?Xe(n.label):`${s?`${s} `:""}${ya(t)}`,d=dn(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"}):nn(t),e.jsx("span",{className:"font-medium",children:l})]}),n!=null&&n.detail&&t.status!=="FAILED"?e.jsx("p",{className:"mt-1 text-[11px] leading-[1.5] text-muted-foreground",children:n.detail}):null]}),u?e.jsx("span",{className:"shrink-0 text-[10px] tabular-nums text-muted-foreground/70",children:u}):null]}),r.length>0?e.jsxs("div",{className:"mt-2 border-t border-border/60 pt-2",children:[e.jsx("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70",children:"Recent activity"}),e.jsx("ol",{className:"space-y-1.5",children:r.map((c,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:ln(c.label)})]},`${c.updatedAt}-${c.label}-${m}`))})]}):null,d.length>0?e.jsx("p",{className:"mt-2 text-[11px] leading-[1.55] text-muted-foreground",children:d.join(" ")}):null]})}function an({run:t,onRetryRun:s,retryDisabled:n,retryDisabledReason:r,onDeleteRun:o,deletePending:l}){const[d,u]=h.useState(!1),[c,m]=h.useState(!1),x=on(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",W.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",W.danger.iconBg),children:e.jsx(a.X,{className:a.cn("h-3 w-3",W.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",W.danger.icon),children:p}),x?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:x}):null]}),t.error?e.jsx("p",{className:"mt-1 text-[11px] leading-[1.55] text-foreground/80",children:t.error}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?e.jsxs("button",{type:"button",onClick:s,disabled:n,title:n?r:"Retry run",className:"inline-flex h-7 items-center gap-1.5 rounded-control border border-border bg-background px-2.5 text-[12px] font-medium text-foreground hover:bg-muted disabled:opacity-50",children:[e.jsx(i.RefreshCw,{className:"h-3 w-3"}),"Retry"]}):null,o?e.jsxs(i.DropdownMenu,{open:c,onOpenChange:m,children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"More run actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsx(i.DropdownMenuContent,{align:"end",className:"z-[60] w-44",children:e.jsxs(i.DropdownMenuItem,{onClick:f=>{f.preventDefault(),m(!1),u(!0)},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete run"]})})]}):null]})]}),o?e.jsx(i.AlertDialog,{open:d,onOpenChange:f=>{l||u(f)},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:"Delete this run record?"}),e.jsx(i.AlertDialogDescription,{children:"The briefing itself stays. Only this run's record (status, error message, activity log) is removed and won't appear in history."})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{disabled:l,children:"Cancel"}),e.jsxs(i.AlertDialogAction,{disabled:l,onClick:f=>{f.preventDefault(),o()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:[l?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(i.Trash2,{className:"h-3 w-3"}),"Delete run"]})]})]})}):null]})}function Da({run:t}){const s=Rt(t);return!Zs(t.status)||!s||s.status==="SKIPPED"?null:e.jsxs("div",{className:a.cn("rounded-card border px-3 py-2 text-[12px]",va(s)),"aria-label":"Email delivery status",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(ee.SendHorizontal,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:ja(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 on(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 ka(t){const s=Rt(t);return t.status==="FAILED"?(s==null?void 0:s.status)==="FAILED"?"Last email failed":"Last run failed":(s==null?void 0:s.status)==="SENT"?s.sentCount===1?"Last email sent":"Last emails sent":(s==null?void 0:s.status)==="FAILED"?"Last email failed":"Last run completed"}function Ea({run:t,onViewOutput:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,deletePending:d}){const u=Rt(t),c=on(t.completedAt??t.startedAt??t.scheduledFor);if(t.status==="FAILED"||(u==null?void 0:u.status)==="FAILED")return e.jsx(an,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,onDeleteRun:n,deletePending:d});const x=u&&u.status!=="SKIPPED"?[u.attachmentCount===1?"1 attachment":`${u.attachmentCount} attachments`,u.attemptedCount>0?`${u.attemptedCount} attempted`:null].filter(Boolean).join(" · "):t.error;return e.jsx("div",{className:a.cn("rounded-card border px-3 py-2",W.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",W.success.label),children:[nn(t),e.jsx("span",{children:ka(t)}),c?e.jsx("span",{className:"font-normal text-muted-foreground",children:c}):null]}),x?e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:x}):null]}),e.jsx("div",{className:"flex items-center gap-1",children:e.jsxs("button",{type:"button",className:Fe,onClick:s,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})})]})})}function Xe(t){return t.replace(/\s+(started|completed)$/i,"")}function ln(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 ps=4;function fs({run:t}){const s=t.progress??null,n=s?(s.recentEvents??[]).filter(u=>u.label!==s.label||u.updatedAt!==s.updatedAt).slice(-ps).reverse():[],r=s!=null&&s.updatedAt?new Date(s.updatedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit",second:"2-digit"}):null,o=(s==null?void 0:s.detail)??(s==null?void 0:s.label)??null,l=dn(t),d=[...n];for(;d.length<ps;)d.push(null);return e.jsxs("div",{className:"border-b border-border bg-muted/60 px-4 py-3",children:[e.jsxs("p",{className:"min-h-[18px] text-[12px] leading-[1.5] text-foreground/80",children:[o??e.jsx("span",{className:"text-muted-foreground/70",children:"Waiting for run progress…"}),r?e.jsx("span",{className:"ml-2 text-[10px] tabular-nums text-muted-foreground/70",children:r}):null]}),e.jsxs("div",{className:"mt-3",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:d.map((u,c)=>e.jsx("li",{className:"flex items-start gap-2 text-[11px] leading-[1.45] text-muted-foreground",children:u?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:ln(u.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:"·"})]})},u?`${u.updatedAt}-${u.label}-${c}`:`slot-${c}`))})]}),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,l.length>0?e.jsx("p",{className:"mt-2 text-[11px] leading-[1.55] text-muted-foreground",children:l.join(" ")}):null]})}function Ia(){return e.jsx("div",{className:a.cn("border-b px-4 py-2 text-[12px] leading-[1.5]",W.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",W.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 Aa({run:t,onExpand:s}){var o;const n=en(t.startedAt),r=(o=t.progress)!=null&&o.label?Xe(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:Ft(n)}):"Starting…"})]}),e.jsx(i.Maximize2,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"})]}),e.jsx("div",{className:"border-t border-border/60 bg-muted px-3 py-1.5",children:e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"We'll notify you when it's ready"})})]})}function Ta({title:t,durationSeconds:s,status:n,onView:r,onDismiss:o}){const l=n==="success";return e.jsx("div",{className:a.cn("border-b px-4 py-2.5",l?W.success.surface:W.danger.surface),role:"status",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:a.cn("mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full",l?W.success.iconBg:W.danger.iconBg),children:l?e.jsx(a.Check,{className:a.cn("h-3 w-3",W.success.icon)}):e.jsx(a.X,{className:"h-3 w-3 text-destructive"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:t}),s!==null&&l?e.jsxs("p",{className:"mt-0.5 text-[11px] text-foreground/70",children:["Generated in ",Ft(s)]}):null]}),l?e.jsxs("button",{type:"button",onClick:r,className:"inline-flex h-6 items-center gap-1 rounded-control bg-primary px-2 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:["View briefing",e.jsx(i.ArrowRight,{className:"h-3 w-3"})]}):null,e.jsx("button",{type:"button",onClick:o,className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Dismiss",children:e.jsx(a.X,{className:"h-3 w-3"})})]})})}function Fa({run:t}){const s=en(t==null?void 0:t.startedAt);return s===null?null:e.jsxs("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:["· ",Ft(s)]})}function Ra({pendingAction:t,previewRun:s,savedActiveRun:n,onShowDetails:r,onCancelSavedRun:o,onMinimizeRun:l,detailsVisible:d}){var S,j,b,w;const u=s&&Ie(s.status)?s:null,c=n;let m=null,x=null,y=!1;if(t==="plan"?(m="Reviewing your brief",x="Reading the brief and planning the analysis…"):t==="preview"?(m="Starting preview run",x="Starting the preview…"):t==="run"?(m="Starting briefing run",x="Preparing the run…"):u?(m=(S=u.progress)!=null&&S.label?Xe(u.progress.label):"Running preview",x=((j=u.progress)==null?void 0:j.detail)??null,y=!!u.progress):c&&(m=(b=c.progress)!=null&&b.label?Xe(c.progress.label):"Running",x=((w=c.progress)==null?void 0:w.detail)??null,y=!!c.progress),!m)return null;const p=!d&&x,f=c??u,E=!!(c&&l)&&t!=="cancelRun";return e.jsx("div",{className:"border-b border-border bg-muted/60","aria-live":"polite","aria-label":"Run progress",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 text-[12px]",children:[e.jsx(a.LoaderCircle,{className:"h-3 w-3 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate font-medium text-foreground",children:m}),e.jsx(Fa,{run:f}),p?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"shrink-0 text-border",children:"·"}),e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:x})]}):null,e.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[y?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":d,"aria-label":d?"Hide details":"Show details",title:d?"Hide details":"Show details",children:e.jsx(a.ChevronDown,{className:a.cn("h-3 w-3 transition-transform",d&&"rotate-180")})}):null,E&&l?e.jsxs("button",{type:"button",onClick:l,className:"inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-control border border-border bg-background px-2 text-[11px] font-medium text-foreground hover:bg-muted","aria-label":"Run in background",title:"Run in background — we'll save the result",children:[e.jsx(i.Minimize2,{className:"h-3 w-3"}),"Run in background"]}):null,c&&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 dn(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 Pa(t){var s,n;return((n=(s=t.result)==null?void 0:s.limits)==null?void 0:n.previewKind)==="email_package"}function cn({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 La({recipient:t}){const[s,n]=h.useState(!1),r=t.previewMembers??[];return t.type==="group"&&r.length>0?e.jsxs("div",{className:"relative inline-flex",children:[e.jsxs("button",{type:"button",className:"inline-flex min-h-6 max-w-full items-center rounded-control border border-border bg-muted px-2 py-1 text-left text-[12px] leading-[1.25] text-foreground hover:border-border",onClick:()=>n(l=>!l),"aria-expanded":s,children:[e.jsx("span",{className:"min-w-0 truncate",children:t.label}),t.detail?e.jsx("span",{className:"ml-1.5 min-w-0 truncate text-muted-foreground",children:t.detail}):null,s?e.jsx(a.ChevronDown,{className:"ml-1.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(i.ChevronRight,{className:"ml-1.5 h-3 w-3 shrink-0 text-muted-foreground"})]}),s?e.jsxs("div",{className:"absolute left-0 top-full z-20 mt-1 w-[280px] rounded-card border border-border bg-background p-2 shadow-md",children:[e.jsx("div",{className:Q,children:"Members"}),e.jsx("div",{className:"mt-1.5 space-y-1",children:r.map((l,d)=>e.jsxs("div",{className:"rounded-control bg-muted px-2 py-1.5 text-[12px] leading-4",children:[e.jsx("div",{className:"truncate text-foreground",children:l.label}),l.detail?e.jsx("div",{className:"truncate text-muted-foreground",children:l.detail}):null]},`${l.type}-${l.label}-${d}`))}),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(cn,{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 un({markdown:t,className:s}){return e.jsx("div",{className:a.cn("text-[13px] leading-[1.6] text-foreground ",s),children:e.jsx(i.Markdown,{remarkPlugins:[i.remarkGfm],components:{h1:({children:n})=>e.jsx("h1",{className:"mb-4 text-[18px] font-semibold leading-6 text-foreground",children:n}),h2:({children:n})=>e.jsx("h2",{className:"mb-2 mt-5 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground first:mt-0",children:n}),h3:({children:n})=>e.jsx("h3",{className:"mb-2 mt-4 text-[13px] font-semibold text-foreground",children:n}),p:({children:n})=>e.jsx("p",{className:"mb-3 max-w-[760px] text-[13px] leading-[1.65] text-foreground last:mb-0",children:n}),ul:({children:n})=>e.jsx("ul",{className:"mb-4 max-w-[760px] list-disc space-y-1.5 pl-5 text-[13px] leading-[1.6] marker:text-muted-foreground/70 last:mb-0",children:n}),ol:({children:n})=>e.jsx("ol",{className:"mb-4 max-w-[760px] list-decimal space-y-1.5 pl-5 text-[13px] leading-[1.6] marker:text-muted-foreground/70 last:mb-0",children:n}),li:({children:n})=>e.jsx("li",{className:"pl-0.5",children:n}),table:({children:n})=>e.jsx("div",{className:"my-4 overflow-x-auto rounded-card border border-border",children:e.jsx("table",{className:"w-full min-w-full border-collapse text-[12px]",children:n})}),th:({children:n})=>e.jsx("th",{className:"border-b border-border bg-muted px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:n}),td:({children:n})=>e.jsx("td",{className:"border-b border-border/60 px-3 py-2 align-top text-foreground last:border-b-0",children:n}),a:({children:n,href:r})=>e.jsx("a",{href:r,className:"font-medium text-primary underline decoration-primary/30 underline-offset-2 hover:text-primary",target:r!=null&&r.startsWith("#")?void 0:"_blank",rel:r!=null&&r.startsWith("#")?void 0:"noreferrer",children:n}),img:({alt:n,src:r})=>e.jsx("img",{alt:n??"",src:r??"",className:"my-4 max-h-[280px] w-auto max-w-full rounded-card border border-border object-contain"}),blockquote:({children:n})=>e.jsx("blockquote",{className:"my-4 max-w-[760px] border-l-2 border-border pl-3 text-foreground/70",children:n}),hr:()=>e.jsx("hr",{className:"my-5 border-border"}),code:({children:n})=>e.jsx("code",{className:"rounded-control bg-muted px-1 py-0.5 font-mono text-[11px] text-foreground",children:n}),pre:({children:n})=>e.jsx("pre",{className:"my-4 overflow-x-auto rounded-card border border-border bg-muted p-3 font-mono text-[11px] leading-[1.55] text-foreground/80",children:n})},children:t})})}function Pt({preview:t,onExpand:s}){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((n,r)=>e.jsx(La,{recipient:n},`${n.type}-${n.label}-${r}`)):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]})]}),s?e.jsx("button",{type:"button",onClick:s,"aria-label":"Expand preview to a larger view",className:"-mr-1 -mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground/70 hover:bg-muted hover:text-foreground/80",children:e.jsx(i.Maximize2,{className:"h-3.5 w-3.5"})}):null]}),t.bodyHtml?e.jsx("div",{className:"px-4 py-3.5",children:e.jsx(sn,{html:t.bodyHtml,title:"Briefing email HTML body",className:"h-[720px]"})}):e.jsx(un,{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(n=>e.jsx(cn,{children:n},n))]}):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 pe({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 Ma({plan:t}){const s=t.scope.datasets;return s.length?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-border bg-muted px-1.5 py-0.5 text-[11px] leading-4 text-foreground/80",children:[e.jsx(i.Database,{className:"h-3 w-3 text-muted-foreground/70"}),n]},n))}):e.jsxs("div",{className:"flex items-start gap-1.5 text-muted-foreground",children:[e.jsx(a.Info,{className:"mt-0.5 h-3 w-3 shrink-0"}),e.jsx("span",{children:"No reachable datasets discovered during plan preview. Choose a dashboard, domain, metric, or more specific business question before running."})]})}function Ba({order:t,title:s,detail:n,optional:r}){const[o,l]=h.useState(!1);return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:a.cn("mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",r?"border-border text-muted-foreground/70 0":"border-border/60 text-foreground "),children:t}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:a.cn("text-[12.5px] leading-[1.45]",r?"text-foreground/70 ":"text-foreground "),children:[s,r?e.jsx("span",{className:"ml-1.5 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"if needed"}):null]}),n?e.jsxs("div",{className:"mt-0.5 text-[11px] leading-[1.5] text-muted-foreground",children:[e.jsx("div",{className:a.cn("whitespace-pre-wrap break-words",!o&&`line-clamp-${xs}`),style:o?void 0:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:xs,overflow:"hidden"},children:n}),n.length>220?e.jsx("button",{type:"button",onClick:()=>l(d=>!d),className:"mt-0.5 text-[11px] text-foreground/60 hover:text-foreground",children:o?"Show less":"Show all fields"}):null]}):null]})]})}function gs({previewRun:t,onExpand:s,fullWidth:n}){var c,m,x,y;const r=t.result,o=(c=r==null?void 0:r.artifactPreview)==null?void 0:c.markdown,l=(m=r==null?void 0:r.artifactPreview)==null?void 0:m.html,d=Pa(t),u=d?ga((x=r==null?void 0:r.limits)==null?void 0:x.emailPreview):null;return e.jsxs("div",{className:a.cn("space-y-4",n&&"max-w-none"),"aria-label":"Briefing preview result",children:[d?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",W.success.label),children:[e.jsx("span",{className:a.cn("h-1.5 w-1.5 rounded-full",W.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(Ge,"h-6 px-1.5 text-[11px]"),"aria-label":"Expand preview to a larger view",children:[e.jsx(i.Maximize2,{className:"h-3 w-3"}),"Expand"]}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:Q,children:d?"Email preview":"The story"}),d?null: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]})]}),u?e.jsx(Pt,{preview:u,onExpand:s}):l?e.jsx(sn,{html:l,title:"Briefing preview HTML artifact",className:n?"h-[820px]":"h-[680px]"}):o?e.jsx("article",{className:a.cn("rounded-card border border-border px-4 py-3",d&&"bg-background "),children:e.jsx(un,{markdown:o})}):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&&!d?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 bs({run:t,onExpand:s,onDeleteRun:n,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,deletePending:d}){const u=tn(t),c=t.status==="FAILED";return e.jsxs("div",{className:"space-y-4","aria-label":"Briefing run result",children:[c?e.jsx(an,{run:t,onRetryRun:r,retryDisabled:o,retryDisabledReason:l,onDeleteRun:n,deletePending:d}):null,u?e.jsxs("div",{children:[e.jsx("div",{className:Q,children:"Email"}),e.jsx("div",{className:"mt-2",children:e.jsx(Pt,{preview:u,onExpand:s})})]}):null,!u&&ue(t.result)&&typeof t.result.summary=="string"?e.jsxs("div",{children:[e.jsx("div",{className:Q,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(Da,{run:t}),e.jsx(rn,{run:t,labelPrefix:"Run"})]})}function Va({previewRun:t,isStale:s,onViewOutput:n}){var o,l;const r=((o=t.result)==null?void 0:o.title)??((l=t.result)==null?void 0:l.summary)??"Generated briefing preview";return e.jsx("div",{className:a.cn("rounded-card border px-3 py-2",W.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",W.success.label),children:[e.jsx(a.Check,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:"Preview output available"})]}),e.jsx("div",{className:"mt-1 truncate text-[12px] text-foreground/80",children:r}),s?e.jsx("div",{className:"mt-0.5 text-[10px] leading-[1.45] text-muted-foreground",children:"Generated before your latest edits."}):null]}),e.jsxs("button",{type:"button",className:Fe,onClick:n,children:[e.jsx(i.ExternalLink,{className:"h-3 w-3"}),"View output"]})]})})}const Oa={createBriefing:Rs,updateBriefing:Je,pauseBriefing:Ct,resumeBriefing:St,deleteBriefing:Dt,getBriefing:Nt,runBriefingNow:kt,getBriefingRun:Et,cancelBriefingRun:Bs,deleteBriefingRun:Vs,previewBriefingPlan:Ps,runBriefingPreview:Ls,getBriefingPreviewRun:Ms},ys=2e3,Ua=10*6e4,$a=20*6e4;function _a(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function ve(t){return t instanceof Error&&t.message?t.message:"Something went wrong. Please try again."}function mn(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 js(t){if(t.briefing)return Te(t.briefing);const s=mn(t.briefing,t.sourceContext);return Js({source:s.source,name:s.source.type==="dashboard"?"Dashboard Briefing":"Project Briefing",instruction:vt,...t.defaultRecipient?{delivery:{recipients:[t.defaultRecipient],channels:["EMAIL"]}}:{}})}function za(t){return t==="PAUSED"||t==="DISABLED"?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"}function hn({apiServiceUrl:t,token:s,briefing:n,sourceContext:r,title:o="Briefing",className:l,client:d,generateRequestId:u=_a,onSaved:c,onDeleted:m,onRunStarted:x,onCancel:y,onBack:p,onMinimizeRun:f}){var Wt;const{authToken:E,tokenProps:S}=i.useSemaphorContext(),{currentUser:j}=i.useCurrentUserInfo(),b=a.useDashboardStore(g=>g.dashboard),w=a.useDashboardStore(g=>g.theme),v=a.useDashboardStore(g=>g.selectedSheetId),F=a.useDashboardStore(g=>g.filterValues),A=a.useDashboardStore(g=>g.controlValues),B=a.useDashboardStore(g=>g.semanticExecutionPayload),I=a.useDashboardStore(g=>g.cardControlValuesMap),D=a.useDashboardStore(g=>g.inlineFilterValuesMap),P=a.useDashboardStore(g=>g.dashboardInputValues),$=a.useInteractionStore(g=>g.interactionStates),V=t??(S==null?void 0:S.apiServiceUrl),_=s??(E==null?void 0:E.accessToken),U=h.useMemo(()=>({...Oa,...d}),[d]),L=h.useMemo(()=>mn(n,r),[n,r]),q=h.useMemo(()=>fa(j),[j]),[C,H]=h.useState(n??null),[R,ae]=h.useState(()=>js({briefing:n,sourceContext:L,defaultRecipient:q})),[te,K]=h.useState(null),[se,me]=h.useState([]),[ge,z]=h.useState(null),[Se,we]=h.useState(null),[he,xe]=h.useState(null),[T,G]=h.useState(null),[Ae,Ye]=h.useState(0),[Ve,N]=h.useState(null),[M,be]=h.useState(!1),[re,Z]=h.useState("edit"),[Oe,Ue]=h.useState(0),[Ze,gn]=h.useState(!0),[bn,et]=h.useState(!1),[Lt,tt]=h.useState(null),[yn,st]=h.useState(!1),Mt=h.useRef(void 0),{activeRunId:jn,resetTerminalRun:Bt,startRun:nt,stop:rt}=jt({apiServiceUrl:V,token:_,intervalMs:ys,timeoutMs:$a,fetchRun:({apiServiceUrl:g,token:k,runId:O})=>{if(!(C!=null&&C.id))throw new Error("Missing saved Briefing id for run polling.");return U.getBriefingRun(g,k,C.id,O)},onRun:g=>{we(g)},onTerminalRun:g=>{Z("result"),z(null)},onError:g=>{z(`Unable to refresh briefing run status: ${ve(g)}`)},onTimeout:()=>{z("Briefing run status refresh timed out. Refresh the run to check the latest status.")}}),{activeRunId:vn,startRun:wn,stop:Vt}=jt({apiServiceUrl:V,token:_,intervalMs:ys,timeoutMs:Ua,fetchRun:({apiServiceUrl:g,token:k,runId:O})=>U.getBriefingPreviewRun(g,k,O),onRun:g=>{G(g),g.status==="SUCCESS"&&N(k=>k??Ae)},onTerminalRun:g=>{g.status==="FAILED"?z(g.error||"Briefing preview failed."):(z(null),Z("result"))},onError:g=>{z(`Unable to refresh briefing preview status: ${ve(g)}`)},onTimeout:g=>{G(k=>(k==null?void 0:k.id)===g?{...k,status:"FAILED",completedAt:k.completedAt??new Date().toISOString(),error:k.error||"Briefing preview status refresh timed out."}:k),z("Briefing preview status refresh timed out.")}}),Y=!!(C!=null&&C.id),at=(C==null?void 0:C.status)==="PAUSED"||R.schedule.status==="PAUSED",Nn=Y&&!!(C!=null&&C.scheduleExpr||R.schedule.enabled),De=Se??(C==null?void 0:C.latestRun)??null,oe=De&&Ie(De.status)&&jn===De.id?De:null,ce=De&&Zs(De.status)?De:null,ie=re==="result"&&((T==null?void 0:T.status)==="SUCCESS"||ce)?"result":re==="plan"&&he?"plan":"edit",Cn=L.detail??(R.source.type==="dashboard"?(b==null?void 0:b.title)??null:"All project data available to this token"),Ot=(C==null?void 0:C.status)??R.schedule.status,ot=T!==null&&Ie(T.status)&&vn===T.id||oe!==null,Ne=te!==null||ot,Sn=ie==="edit"&&ce!==null&&!ot,it=(T==null?void 0:T.status)==="SUCCESS"&&T.result?T:null,Dn=it!==null&&Ve!==null&&Ve!==Ae,Re=Lt==="preview"?T:null,ye=Lt==="saved"?ce:null,Pe=ye?tn(ye):null,kn=((Wt=Re==null?void 0:Re.result)==null?void 0:Wt.title)??(Pe==null?void 0:Pe.subject)??(ue(ye==null?void 0:ye.result)&&typeof ye.result.title=="string"?ye.result.title:null)??(C==null?void 0:C.name)??"Briefing preview",$e=h.useMemo(()=>({dashboard:b,theme:w||"light",filters:b==null?void 0:b.filters,selectedSheetId:v,filterValues:F,inlineFilterValuesMap:D,controlValues:A,controlDefinitions:(b==null?void 0:b.controls)||[],dashboardControls:(b==null?void 0:b.controls)||[],cardControlValuesMap:I,dashboardInputValues:P,semanticExecutionPayload:B,interactionStates:$}),[I,A,b,P,F,$,D,B,v,w]);h.useEffect(()=>{const g=(n==null?void 0:n.id)??null;if(Mt.current===g)return;Mt.current=g,Bt(),rt(),Vt(),H(n??null);let k=js({briefing:n,sourceContext:L,defaultRecipient:q}),O=null;if(!n){const Gt=_e.findIndex(je=>je.label==="Business review"&&(!je.available||je.available(k.source))),On=_e.findIndex(je=>!je.available||je.available(k.source)),dt=Gt!==-1?Gt:On;if(dt!==-1){const je=_e[dt];k=ze(k,je.draft(k.source,{attachments:je.seedsDashboardAttachment?Zt({source:k.source,dashboard:b,selectedSheetId:v,runtime:$e}):void 0})),O=dt}}ae(k),Ue(O),we(null),xe(null),G(null),N(null);const J=(n==null?void 0:n.latestRun)??null;z(null),Z("edit"),J&&Ie(J.status)&&nt(J)},[$e,n,b,q,Bt,L,v,nt,Vt,rt]);const le=g=>{ae(k=>ze(k,g)),me([]),z(null),C!=null&&C.id||(xe(null),Ye(k=>k+1),Z("edit"))},Ce=()=>!V||!_?(z("Missing Semaphor API credentials."),null):{apiServiceUrl:V,token:_},En=async g=>{const k=yt(R);if(me(k.issues),z(null),!k.valid)return null;const O=Ce();if(!O)return null;g!=null&&g.pendingAction&&K(g.pendingAction);try{const J=C!=null&&C.id?await U.updateBriefing(O.apiServiceUrl,O.token,C.id,Ys(R)):await U.createBriefing(O.apiServiceUrl,O.token,bt(R));return H(J.briefing),ae(Te(J.briefing)),c==null||c(J.briefing),J.briefing}catch(J){return z(ve(J)),null}finally{g!=null&&g.pendingAction&&K(null)}},In=async()=>En({pendingAction:"save"}),Ut=()=>{const g=yt(R);return me(g.issues),z(null),g.valid?bt(R):null},$t=async g=>{const k=Ce();if(!k)return null;const O=Ut();if(!O)return null;K("plan");try{const J=await U.previewBriefingPlan(k.apiServiceUrl,k.token,O);return xe(J.plan),g!=null&&g.silent||Z("plan"),J.plan}catch(J){return z(ve(J)),null}finally{K(null)}},An=async()=>{const g=Ce();if(!g)return;const k=Ut();if(k)try{const O=he??await $t({silent:!0});if(!O)return;K("preview");const J=await U.runBriefingPreview(g.apiServiceUrl,g.token,{draft:k,planId:O.id,requestId:u()});N(Ae),wn(J.previewRun)}catch(O){z(ve(O))}finally{K(null)}},lt=async()=>{const g=Ce();if(g){if(!(C!=null&&C.id)){await An();return}if(ke){z("Save your changes before running this briefing.");return}K("run"),z(null),G(null);try{const k=await U.runBriefingNow(g.apiServiceUrl,g.token,C.id,{requestId:u()});nt(k.run),x==null||x(k)}catch(k){z(ve(k))}finally{K(null)}}},_t=async()=>{if(!(C!=null&&C.id))return null;const g=Ce();if(!g)return null;const k=await U.getBriefing(g.apiServiceUrl,g.token,C.id);return H(k.briefing),ae(Te(k.briefing)),c==null||c(k.briefing),k.briefing},Tn=async()=>{if(!(C!=null&&C.id)||!(oe!=null&&oe.id))return;const g=Ce();if(g){K("cancelRun"),z(null);try{const k=await U.cancelBriefingRun(g.apiServiceUrl,g.token,C.id,oe.id);rt(),we(k.run),Z("result"),await _t().catch(()=>null)}catch(k){z(ve(k))}finally{K(null)}}},Fn=()=>{!C||!oe||f==null||f({briefing:{...C,latestRun:oe},run:oe})},zt=async g=>{if(!(C!=null&&C.id))return;const k=Ce();if(k){K("deleteRun"),z(null);try{await U.deleteBriefingRun(k.apiServiceUrl,k.token,C.id,g);const O=await _t().catch(()=>null),J=(O==null?void 0:O.latestRun)??null;we(J),J||Z("edit")}catch(O){z(ve(O))}finally{K(null)}}},Rn=async g=>{if(!(C!=null&&C.id))return;const k=Ce();if(k){K(g==="PAUSED"?"pause":"resume"),z(null);try{const O=g==="PAUSED"?await U.pauseBriefing(k.apiServiceUrl,k.token,C.id):await U.resumeBriefing(k.apiServiceUrl,k.token,C.id);H(O.briefing),ae(Te(O.briefing)),c==null||c(O.briefing)}catch(O){z(ve(O))}finally{K(null)}}},Pn=R.instruction.split(`
96
- `).map(g=>g.trim()).find(g=>g.length>0),qt=h.useMemo(()=>C?Te(C):null,[C]),ke=!!qt&&JSON.stringify(R)!==JSON.stringify(qt),Ee=R.body.type==="custom_message",Ln=Ee?"Note":"Analysis",Ht=Ee?"Email body":"What should this briefing investigate?",Mn=Ee?"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.",Bn=Ee?"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.",Vn=h.useMemo(()=>{const g=R.schedule.enabled?R.schedule.scheduleExpr||"Scheduled":"On demand",k=R.delivery.recipients.length,O=k===0?"No recipients":`${k} recipient${k===1?"":"s"}`;return`${g} · ${O}`},[R.delivery.recipients.length,R.schedule.enabled,R.schedule.scheduleExpr]);return e.jsxs("section",{className:a.cn("flex h-full min-h-0 w-full max-w-[480px] flex-col border-l border-border bg-background text-foreground",l),"aria-label":"Briefing author",children:[e.jsxs("header",{className:"flex items-start justify-between gap-3 border-b border-border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[p?e.jsxs("button",{type:"button",onClick:p,className:"-ml-1 mb-1 inline-flex items-center gap-1 rounded-control px-1 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[e.jsx(i.ChevronRight,{className:"h-3 w-3 rotate-180"}),"Back to briefings"]}):null,e.jsx("h2",{className:"truncate text-[14px] font-semibold leading-5 text-foreground",children:o})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[Y?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]",za(Ot)),children:Ot}):null,y?e.jsx("button",{type:"button","aria-label":"Close briefing author",onClick:y,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]})]}),ie!=="edit"?e.jsxs("button",{type:"button",onClick:()=>Z("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:Pn||R.name||"Untitled briefing"}),e.jsx("div",{className:"mt-0.5 truncate text-[10px] text-muted-foreground",children:Vn})]}),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,oe?e.jsx(Ia,{}):null,e.jsx(Ra,{pendingAction:te,previewRun:T,savedActiveRun:oe,detailsVisible:Ze,onShowDetails:()=>gn(g=>!g),onCancelSavedRun:oe?Tn:void 0,onMinimizeRun:oe&&f?Fn:void 0}),Ze&&T&&Ie(T.status)?e.jsx(fs,{run:T}):Ze&&oe?e.jsx(fs,{run:oe}):null,e.jsx("div",{className:"flex-1 space-y-5 overflow-y-auto px-4 py-4",children:ie==="edit"?e.jsxs(e.Fragment,{children:[Y?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(Q,"mb-2"),children:"Start from"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:_e.map((g,k)=>{if(g.available&&!g.available(R.source))return null;const O=Oe===k;return e.jsx("button",{type:"button",onClick:()=>{Ue(k),le(g.draft(R.source,{attachments:g.seedsDashboardAttachment?Zt({source:R.source,dashboard:b,selectedSheetId:v,runtime:$e}):void 0}))},className:a.cn("inline-flex h-6 items-center rounded-control border px-2 text-[11px] transition-colors",O?"border-primary bg-primary text-primary-foreground":"border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"),"aria-label":`${g.label} preset — ${g.description}`,children:g.label},g.label)})})]}),it?e.jsx(Va,{previewRun:it,isStale:Dn,onViewOutput:()=>Z("result")}):null,Sn&&ce?e.jsx(Ea,{run:ce,onViewOutput:()=>Z("result"),onDeleteRun:ce.status==="FAILED"?()=>zt(ce.id):void 0,onRetryRun:ce.status==="FAILED"&&Y?()=>{lt()}:void 0,retryDisabled:Ne||Y&&ke,retryDisabledReason:Y&&ke?"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.jsx("div",{className:"flex items-center justify-between border-b border-border/60 px-3 py-1.5",children:e.jsx("span",{className:Q,children:Ln})}),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:R.name,onChange:g=>{Ue(null),le({name:g.target.value})},placeholder:"Weekly revenue briefing"}),e.jsx("label",{htmlFor:"briefing-instruction",className:"sr-only",children:Ht}),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:R.instruction,onChange:g=>{Ue(null),le({instruction:g.target.value})},placeholder:Mn,"aria-label":Ht}),e.jsx("p",{className:"mt-2 text-[11px] leading-[1.5] text-muted-foreground",children:Bn})]}),Ee?null:e.jsxs("div",{className:"flex items-center justify-end gap-0.5 border-t border-border/60 px-3 py-1.5",children:[R.source.type==="dashboard"&&R.attachments.length===0?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:Ne,onClick:()=>st(!0),className:"inline-flex h-7 items-center gap-1.5 rounded-control px-2 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50","aria-label":"Attach files",children:[e.jsx(i.Paperclip,{className:"h-3 w-3"}),"Attach"]}),e.jsx("span",{className:"text-border",children:"·"})]}):null,e.jsx(oa,{includeEvidence:R.output.includeEvidence,includeSql:R.output.includeSql,includeHtml:R.output.artifactFormats.includes("html"),onChange:(g,k)=>{le(g==="evidence"?{output:{includeEvidence:k}}:g==="sql"?{output:{includeSql:k}}:{output:{artifactFormats:la(R.output.artifactFormats,"html",k)}})}})]})]}),R.source.type==="dashboard"?e.jsxs("div",{children:[R.attachments.length>0?e.jsx(Wr,{attachments:R.attachments,disabled:Ne,onAdd:()=>st(!0),onChange:g=>le({attachments:g.map(fe)})}):null,e.jsx(Qr,{open:yn,onOpenChange:st,source:R.source,dashboard:b,selectedSheetId:v,runtime:$e,selectedAttachments:R.attachments,onSubmit:g=>le({attachments:g})})]}):null,e.jsxs("div",{children:[e.jsx("div",{className:a.cn(Q,"mb-2"),children:"When"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(rs,{label:"On demand only",description:"Save the briefing and run it manually when needed.",checked:!R.schedule.enabled,onSelect:()=>le({schedule:{enabled:!1}}),name:"briefing-schedule-mode"}),e.jsx(rs,{label:"Scheduled",description:"Store the cadence so the runner picks it up later.",checked:R.schedule.enabled,onSelect:()=>le({schedule:{enabled:!0}}),name:"briefing-schedule-mode"})]}),R.schedule.enabled?e.jsx("div",{className:"mt-3 pl-6",children:e.jsx(ca,{scheduleExpr:R.schedule.scheduleExpr||i.buildScheduleExpr(i.DEFAULT_SCHEDULE_VM),timezone:R.schedule.timezone||"UTC",onScheduleChange:g=>le({schedule:{scheduleExpr:g.scheduleExpr,timezone:g.timezone}})})}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:a.cn(Q,"mb-2"),children:"Recipients"}),e.jsxs("div",{className:"space-y-2.5",children:[e.jsx(na,{value:R.delivery.recipients,onChange:g=>le({delivery:{recipients:g}})}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx(ia,{label:"Email",checked:R.delivery.channels.includes("EMAIL"),onChange:g=>le({delivery:{channels:pa(R.delivery.channels,"EMAIL",g)}})})})]})]}),Ee?null:e.jsxs("div",{children:[e.jsx("div",{className:a.cn(Q,"mb-2"),children:"Scope"}),e.jsx(xa,{source:R.source,resolvedSourceContext:L,sourceDetail:Cn,onChange:g=>le({source:g})})]}),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"}),". Recipients see only what they're allowed to see."]})]})]}):ie==="plan"&&he?e.jsx(Ca,{previewPlan:he,previewRun:T&&T.status!=="SUCCESS"?T:null,scopeLabel:L.source.type==="dashboard"?(b==null?void 0:b.title)??L.label:L.label}):ie==="result"&&T?e.jsx(gs,{previewRun:T,onExpand:()=>{tt("preview"),et(!0)}}):ie==="result"&&ce?e.jsx(bs,{run:ce,onExpand:()=>{tt("saved"),et(!0)},onDeleteRun:ce.status==="FAILED"?()=>zt(ce.id):void 0,onRetryRun:ce.status==="FAILED"&&Y?()=>{lt()}:void 0,retryDisabled:Ne||Y&&ke,retryDisabledReason:Y&&ke?"Save your changes before retrying — Retry uses the saved briefing.":void 0,deletePending:te==="deleteRun"}):null}),se.length>0||ge?e.jsxs("div",{className:"shrink-0 space-y-2 border-t border-destructive/30 bg-destructive/10 px-4 py-2.5",children:[se.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:se.map(g=>e.jsx("li",{className:"list-disc marker:text-destructive/60",children:g.message},`${g.field}:${g.message}`))})]}):null,ge?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:ge})]}):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:Y&&Nn?e.jsxs("button",{type:"button",className:Fe,disabled:Ne,onClick:()=>Rn(at?"ACTIVE":"PAUSED"),children:[te==="pause"||te==="resume"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):at?e.jsx(i.Play,{className:"h-3 w-3"}):e.jsx(ws,{className:"h-3 w-3"}),at?"Resume":"Pause"]}):!Y&&(ie==="plan"||ie==="result")?e.jsxs("button",{type:"button",className:Ge,onClick:()=>Z("edit"),children:[e.jsx(i.ChevronRight,{className:"h-3 w-3 rotate-180"}),ie==="result"?"Edit brief":"Tweak brief"]}):!Y&&y&&!p?e.jsx("button",{type:"button",className:Ge,onClick:y,children:"Discard"}):null}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Y&&ie==="edit"&&!Ee?e.jsxs("button",{type:"button",className:Fe,disabled:Ne,onClick:()=>{$t()},children:[te==="plan"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(_n,{className:"h-3 w-3"}),"Preview plan"]}):null,e.jsxs("button",{type:"button",className:Fe,disabled:Ne||Y&&ke,onClick:lt,title:Y&&ke?"Save your changes before running — Run now uses the saved briefing.":void 0,children:[te==="run"||te==="preview"||ot?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):ie==="result"?e.jsx(i.RefreshCw,{className:"h-3 w-3"}):ie==="plan"?e.jsx(ft,{className:"h-3 w-3"}):Y?e.jsx(i.Send,{className:"h-3 w-3"}):e.jsx(ft,{className:"h-3 w-3"}),Y?"Run now":ie==="plan"?"Run plan":ie==="result"?"Run again":"Show preview"]}),e.jsxs("button",{type:"button",className:Y?Fe:da,disabled:Ne,onClick:In,children:[te==="save"?e.jsx(a.LoaderCircle,{className:"h-3 w-3 animate-spin"}):e.jsx(a.Check,{className:"h-3 w-3"}),Y?"Save changes":"Create briefing"]})]})]})}),e.jsx(i.Dialog,{open:bn,onOpenChange:g=>{et(g),g||tt(null)},children:e.jsxs(i.DialogContent,{className:"flex max-h-[90vh] w-[min(960px,calc(100vw-32px))] max-w-none flex-col gap-0 overflow-hidden p-0",children:[e.jsxs(i.DialogHeader,{className:"border-b border-border px-6 py-3 text-left",children:[e.jsx(i.DialogTitle,{className:"truncate text-[14px] font-semibold leading-5",children:kn}),e.jsx(i.DialogDescription,{className:"text-[12px] text-muted-foreground",children:"Full briefing render"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:Re?e.jsx(gs,{previewRun:Re,fullWidth:!0}):Pe?e.jsx(Pt,{preview:Pe}):ye?e.jsx(bs,{run:ye}):null})]})})]})}function xn({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(qn,{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 qa={listBriefings:Fs,getBriefing:Nt,pauseBriefing:Ct,resumeBriefing:St,deleteBriefing:Dt,runBriefingNow:kt},Ha="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Wa="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",pn="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 Ga(t){return(t==null?void 0:t.trim())||"This dashboard"}function Ka(t){return t==="This dashboard"?"Watch this dashboard":`Watch ${t}`}function Xa(t,s){return t.source.type==="dashboard"&&t.source.dashboardId===s}async function Qa({apiClient:t,apiServiceUrl:s,dashboardId:n,token:r}){const l=[];let d=1,u=0,c=Number.POSITIVE_INFINITY;for(;u<c;){const m=await t.listBriefings(s,r,{scope:"organization",page:d,pageSize:100}),x=m.briefings;if(l.push(...x.filter(y=>Xa(y,n))),u+=x.length,c=m.total,x.length===0||u>=c)break;d+=1}return l}function Ja(t){if(!t)return"Never";const s=new Date(t);if(Number.isNaN(s.getTime()))return"Unknown";const n=Date.now()-s.getTime(),r=Math.round(n/6e4);if(r<1)return"now";if(r<60)return`${r}m ago`;const o=Math.round(r/60);if(o<24)return`${o}h ago`;const l=Math.round(o/24);if(l<7)return`${l}d ago`;const d=Math.round(l/7);return d<5?`${d}w ago`:`${Math.round(l/30)}mo ago`}function Ya(t){return t.scheduleExpr?t.scheduleExpr:"On demand"}function Za(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 fn(t){return t.hasActiveRun?"Running":t.lastRunStatus?`Last run ${t.lastRunStatus.toString().toLowerCase()}`:"Idle"}function eo({briefings:t,dashboardLabel:s,error:n,loading:r,onClose:o,onEdit:l,onNew:d,onRunNow:u,onTogglePause:c,onDelete:m,selectingId:x,busyId:y,manageBriefingsHref:p}){const f=t.length,E=t.filter(j=>j.status==="ACTIVE").length,S=t.find(j=>j.hasActiveRun)??null;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:Ha,children:"Briefings"}),e.jsx("h2",{className:"mt-0.5 truncate text-[14px] font-semibold leading-5",children:s})]}),e.jsx("button",{type:"button",onClick:o,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 border-b border-border px-4 py-2",children:[e.jsx("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:r&&f===0?e.jsx("span",{children:"Loading briefings…"}):f===0?e.jsx("span",{children:"No briefings yet"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-medium text-foreground/80",children:[f," watching"]}),e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:[E," active"]})]})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[r?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):null,f>0?e.jsxs("button",{onClick:d,className:pn,children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"New briefing"]}):null]})]}),S?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:S.name}),e.jsx("span",{className:"text-border",children:"·"}),e.jsx("span",{className:"truncate text-muted-foreground",children:fn(S)})]}):null,e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n?e.jsx("div",{className:"m-4 rounded-card border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:n}):null,!r&&t.length===0&&!n?e.jsx(to,{onNew:d}):null,t.map(j=>e.jsx(no,{briefing:j,isOpening:x===j.id,isBusy:y===j.id,onOpen:()=>l(j.id),onRunNow:()=>u(j),onTogglePause:()=>c(j),onDelete:()=>m(j)},j.id))]}),p?e.jsx("div",{className:"border-t border-border px-4 py-2.5",children:e.jsxs("a",{href:p,className:a.cn(Wa,"h-6 px-1 text-[11px]"),children:["Manage all briefings",e.jsx(Un,{className:"h-3 w-3"})]})}):null]})}function to({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(so,{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(pn,"mt-4"),children:[e.jsx(i.Plus,{className:"h-3 w-3"}),"New briefing"]})]})}function so({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 no({briefing:t,isOpening:s,isBusy:n,onOpen:r,onRunNow:o,onTogglePause:l,onDelete:d}){const u=t.status==="PAUSED",c=t.hasActiveRun,m=Za(t),x=Ja(t.lastRunAt),y=t.lastRunStatus,p=y==="SUCCESS"?W.success.dot:y==="FAILED"?W.danger.dot:y?W.warning.dot:W.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:f=>{(f.key==="Enter"||f.key===" ")&&(f.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(i.Clock,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Ya(t)}),t.lastRunAt?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-border",children:"·"}),e.jsxs("span",{children:["Last run ",x]})]}):null]}),m||c?e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5 text-[12px] leading-[1.5] text-foreground/80",children:[c?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:c?fn(t):m})]}):null]}),e.jsx("div",{className:"absolute right-3 top-3",children:n?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):s?e.jsx(a.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground/70"}):e.jsxs(i.DropdownMenu,{children:[e.jsx(i.DropdownMenuTrigger,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f=>f.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 group-hover:opacity-100 focus-visible:opacity-100","aria-label":"Briefing actions",children:e.jsx(i.Ellipsis,{className:"h-3.5 w-3.5"})})}),e.jsxs(i.DropdownMenuContent,{align:"end",className:"w-44",children:[e.jsxs(i.DropdownMenuItem,{onClick:r,children:[e.jsx(i.Pencil,{className:"h-3.5 w-3.5"}),"Edit briefing"]}),e.jsxs(i.DropdownMenuItem,{onClick:f=>{f.preventDefault(),o()},children:[e.jsx(ft,{className:"h-3.5 w-3.5"}),"Run now"]}),t.scheduleExpr?e.jsx(i.DropdownMenuItem,{onClick:f=>{f.preventDefault(),l()},children:u?e.jsxs(e.Fragment,{children:[e.jsx(i.Play,{className:"h-3.5 w-3.5"}),"Resume"]}):e.jsxs(e.Fragment,{children:[e.jsx(ws,{className:"h-3.5 w-3.5"}),"Pause"]})}):null,e.jsx(i.DropdownMenuSeparator,{}),e.jsxs(i.DropdownMenuItem,{onClick:f=>{f.preventDefault(),d()},className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(i.Trash2,{className:"h-3.5 w-3.5"}),"Delete briefing"]})]})]})})]})}const ro=2e3,ao=20*6e4;function oo({briefingId:t,initialRun:s,apiServiceUrl:n,token:r,onTerminal:o,onTimeout:l,onExpand:d}){const[u,c]=h.useState(s),{startRun:m}=jt({apiServiceUrl:n,token:r,intervalMs:ro,timeoutMs:ao,fetchRun:({apiServiceUrl:y,token:p,runId:f})=>Et(y,p,t,f),onRun:y=>{c(y)},onTerminalRun:y=>{o(y)},onTimeout:()=>{l()}}),x=h.useRef(!1);return h.useEffect(()=>{x.current||(x.current=!0,We(s.status)?m(s):He(s.status)&&o(s))},[s,o,m]),e.jsx(Aa,{run:u,onExpand:d})}function io({dashboardId:t,dashboardTitle:s,apiServiceUrl:n,token:r,disabled:o,className:l,manageBriefingsHref:d,client:u}){const{authToken:c,tokenProps:m}=i.useSemaphorContext(),[x,y]=h.useState(!1),[p,f]=h.useState("list"),[E,S]=h.useState([]),[j,b]=h.useState(null),[w,v]=h.useState(!1),[F,A]=h.useState(null),[B,I]=h.useState(null),[D,P]=h.useState(null),[$,V]=h.useState(null),[_,U]=h.useState(null),[L,q]=h.useState(null),C=n??(m==null?void 0:m.apiServiceUrl),H=r??(c==null?void 0:c.accessToken),R=h.useMemo(()=>({...qa,...u}),[u]),ae=Ga(s),te=h.useMemo(()=>({source:{type:"dashboard",dashboardId:t},label:ae,detail:Ka(ae)}),[t,ae]),K=!!(C&&H),se=h.useCallback(async()=>{if(!(!C||!H)){v(!0),V(null);try{S(await Qa({apiClient:R,apiServiceUrl:C,dashboardId:t,token:H}))}catch(T){V(T instanceof Error?T.message:"Could not load briefings.")}finally{v(!1)}}},[R,t,C,H]);h.useEffect(()=>{!x||p!=="list"||!K||se()},[K,se,x,p]);const me=()=>{b(null),f("list"),y(!0)},ge=()=>{b(null),f("author")},z=async T=>{if(!(!C||!H)){A(T),V(null);try{const G=await R.getBriefing(C,H,T);b(G.briefing),f("author")}catch(G){V(G instanceof Error?G.message:"Could not open briefing.")}finally{A(null)}}},Se=async T=>{if(!(!C||!H)){I(T.id);try{await R.runBriefingNow(C,H,T.id,{requestId:lo()}),se()}catch(G){i.ue.error(G instanceof Error?G.message:"Could not start the run.")}finally{I(null)}}},we=async T=>{if(!(!C||!H)){I(T.id);try{const G=T.status==="PAUSED"?await R.resumeBriefing(C,H,T.id):await R.pauseBriefing(C,H,T.id);i.ue.success(G.briefing.status==="PAUSED"?"Briefing paused":"Briefing resumed"),se()}catch(G){i.ue.error(G instanceof Error?G.message:"Could not update the briefing status.")}finally{I(null)}}},he=async()=>{if(!D||!C||!H)return;const T=D;I(T.id);try{await R.deleteBriefing(C,H,T.id),i.ue.success("Briefing deleted"),P(null),se()}catch(G){i.ue.error(G instanceof Error?G.message:"Could not delete the briefing.")}finally{I(null)}},xe=E.length;return e.jsxs(i.Sheet,{open:x,onOpenChange:y,children:[e.jsx(xn,{disabled:o||!K,briefingCount:xe,className:l,onClick:me}),e.jsxs(i.SheetContent,{side:"right",hideClose:!0,className:"flex h-full w-full flex-col overflow-hidden p-0 sm:max-w-[560px]",children:[e.jsxs(i.SheetHeader,{className:"sr-only",children:[e.jsx(i.SheetTitle,{children:"Briefings"}),e.jsx(i.SheetDescription,{children:"Manage briefings for this dashboard."})]}),p==="list"?e.jsx(eo,{briefings:E,dashboardLabel:ae,error:$,loading:w,onClose:()=>y(!1),onEdit:T=>{z(T)},onNew:ge,onRunNow:T=>{Se(T)},onTogglePause:T=>{we(T)},onDelete:T=>P(T),selectingId:F,busyId:B,manageBriefingsHref:d}):e.jsx(hn,{apiServiceUrl:C,token:H,briefing:j,sourceContext:j?void 0:te,title:j?"Edit briefing":"Create briefing",className:"h-full min-h-0 max-w-none border-0 shadow-none",onBack:()=>f("list"),onCancel:()=>y(!1),onDeleted:()=>{i.ue.success("Briefing deleted"),b(null),f("list"),se()},onRunStarted:()=>{},onSaved:T=>{b(T),se()},onMinimizeRun:({briefing:T,run:G})=>{U({briefing:T,run:G}),y(!1)}})]}),_&&C&&H?e.jsx(oo,{briefingId:_.briefing.id,initialRun:_.run,apiServiceUrl:C,token:H,onTerminal:T=>{q({briefing:_.briefing,run:T}),U(null),se()},onTimeout:()=>{U(null),se()},onExpand:()=>{b(_.briefing),f("author"),U(null),y(!0)}}):null,L?e.jsx("div",{className:"fixed bottom-4 right-4 z-50 w-[360px]",children:e.jsx(Ta,{title:L.run.status==="SUCCESS"?`${L.briefing.name} is ready`:`${L.briefing.name} run failed`,durationSeconds:L.run.startedAt&&L.run.completedAt?Math.max(0,Math.floor((new Date(L.run.completedAt).getTime()-new Date(L.run.startedAt).getTime())/1e3)):null,status:L.run.status==="SUCCESS"?"success":"failed",onView:()=>{b(L.briefing),f("author"),q(null),y(!0)},onDismiss:()=>q(null)})}):null,e.jsx(i.AlertDialog,{open:!!D,onOpenChange:T=>{T||P(null)},children:e.jsxs(i.AlertDialogContent,{children:[e.jsxs(i.AlertDialogHeader,{children:[e.jsx(i.AlertDialogTitle,{children:"Delete briefing?"}),e.jsxs(i.AlertDialogDescription,{children:["This permanently deletes ",e.jsx("strong",{children:D==null?void 0:D.name}),". Recipients will stop receiving it."]})]}),e.jsxs(i.AlertDialogFooter,{children:[e.jsx(i.AlertDialogCancel,{children:"Cancel"}),e.jsx(i.AlertDialogAction,{className:"bg-destructive/90 hover:bg-destructive",onClick:he,children:"Delete briefing"})]})]})})]})}function lo(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`briefing-run-now-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}exports.AdvancedModeToggle=Kn;exports.BriefingAuthor=hn;exports.BriefingsApiError=wt;exports.DashboardBriefingLauncher=io;exports.DashboardControlsSettings=Ds;exports.DashboardFilterControlsButton=Es;exports.DashboardFilterControlsLauncher=fr;exports.DocumentControlsSettings=ks;exports.ExportNotificationItem=Cs;exports.ExportNotificationList=Ss;exports.NotificationBell=ar;exports.UnsavedChangesAlert=Xn;exports.VisualEditingControls=Gn;exports.WatchDashboardButton=xn;exports.applyBriefingFormPatch=ze;exports.briefingFormDraftToCreateRequest=bt;exports.briefingFormDraftToUpdateRequest=Ys;exports.briefingToFormDraft=Te;exports.cancelBriefingRun=Bs;exports.createBriefing=Rs;exports.createBriefingFormDraft=Js;exports.deleteBriefing=Dt;exports.deleteBriefingRun=Vs;exports.getBriefing=Nt;exports.getBriefingArtifact=vr;exports.getBriefingEvidence=wr;exports.getBriefingPreviewRun=Ms;exports.getBriefingRun=Et;exports.listBriefingRuns=jr;exports.listBriefingTenantSummaries=yr;exports.listBriefings=Fs;exports.pauseBriefing=Ct;exports.previewBriefingPlan=Ps;exports.resumeBriefing=St;exports.runBriefingNow=kt;exports.runBriefingPreview=Ls;exports.updateBriefing=Je;exports.useExportPolling=sr;exports.useExportRecovery=nr;exports.validateBriefingFormDraft=yt;