1import{r as o,j as e,al as ce,N as qe,I as Ge,q as We,g as ue,ct as Ye,y as Je,m as Re,a8 as ie,b1 as le,an as He,Z as Ze,am as Qe,A as Xe,bu as et,t as Oe,Y as tt,af as at,D as xe,F as ne,Q as rt,bM as st,a4 as ot,s as lt}from"./vendor-DG5Dz7Ik.js";import{a as _,c as Be,u as Ie,b as me,a2 as pe,a3 as nt,ar as dt,ae as Me}from"./view-analytics-BkPD6vG9.js";import{R as ct}from"./RoleGuard-7uEILPCc.js";import"./pdf-vendor-BQyayL6K.js";import"./socket-vendor-DENoLIvz.js";import"./auth-vendor-CeReGQmr.js";import"./view-admin-B4Sdd-uD.js";import"./view-workflow-builder-CDc7AhbV.js";import"./index-DCGMzhq2.js";import"./view-project-Ccb3hXyh.js";import"./view-wizard-CJQ0Ev0i.js";import"./view-mission-control-BbTzX6ZV.js";import"./shared-components-CRZb49ua.js";import"./view-reasoning-i8UqGU0O.js";import"./pdf-export-BE1eaTrw.js";import"./supportChatService-BdLELBT8.js";import"./view-pricing-oUXlOXyX.js";function te(t){const a=t.toString();return a?`?${a}`:""}async function it(t){const a=new URLSearchParams;return t!=null&&t.agentType&&a.set("agentType",t.agentType),a.set("limit",String(t.limit)),t!=null&&t.offset&&a.set("offset",String(t.offset)),t!=null&&t.fromDate&&a.set("fromDate",t.fromDate),t!=null&&t.toDate&&a.set("toDate",t.toDate),_(`/v1/agents/dashboard/activity-feed${te(a)}`)}async function mt(t){const a=["proposed","pending_approval","approved"],r=new URLSearchParams;return r.set("status",a.join(",")),r.set("requiresAttention","true"),r.set("limit",String(t.limit)),t!=null&&t.offset&&r.set("offset",String(t.offset)),t!=null&&t.fromDate&&r.set("fromDate",t.fromDate),t!=null&&t.toDate&&r.set("toDate",t.toDate),_(`/v1/agents/dashboard/activity-feed${te(r)}`)}async function ut(t){const a=["completed","executing","rolled_back"],r=new URLSearchParams;return r.set("status",a.join(",")),t!=null&&t.agentType&&r.set("agentType",t.agentType),r.set("limit",String(t.limit)),t!=null&&t.offset&&r.set("offset",String(t.offset)),t!=null&&t.fromDate&&r.set("fromDate",t.fromDate),t!=null&&t.toDate&&r.set("toDate",t.toDate),_(`/v1/agents/dashboard/activity-feed${te(r)}`)}async function xt(){return _("/v1/agents/dashboard/stats")}async function pt(){return _("/v1/agents/dashboard/autonomy-summary")}async function ge(t){const a=new URLSearchParams;return t!=null&&t.limit&&a.set("limit",String(t.limit)),t!=null&&t.offset&&a.set("offset",String(t.offset)),t!=null&&t.fromDate&&a.set("fromDate",t.fromDate),t!=null&&t.toDate&&a.set("toDate",t.toDate),t!=null&&t.agentType&&a.set("agentType",t.agentType),t!=null&&t.actionType&&a.set("actionType",t.actionType),_(`/v1/agents/dashboard/timeline${te(a)}`)}async function gt(t){const{agentType:a,...r}=t;return Be(`/v1/agents/guardrails/${a}`,r)}async function bt(){return _("/v1/agents/dashboard/email-ab-promotions")}const yt=6e4;function ht(){const t=Ie(),[a,r]=o.useState([]),[s,c]=o.useState([]),[l,n]=o.useState([]),[i,x]=o.useState(null),[g,N]=o.useState([]),[m,h]=o.useState(!0),[y,p]=o.useState({}),b=o.useRef(0),f=o.useCallback(async()=>{const k=++b.current,[C,A,$,E,D]=await Promise.allSettled([it({limit:50}),mt({limit:50}),ut({limit:50}),xt(),pt()]);if(k!==b.current)return;const T={},L=R=>R instanceof Error?R.message:"This data is currently unavailable.";C.status==="fulfilled"?r(C.value.items):(r([]),T.monitoring=L(C.reason)),A.status==="fulfilled"?c(A.value.items):(c([]),T.anomalies=L(A.reason)),$.status==="fulfilled"?n($.value.items):(n([]),T.optimization=L($.reason)),E.status==="fulfilled"?x(E.value):(x(null),T.stats=L(E.reason)),D.status==="fulfilled"?N(D.value):(N([]),T.settings=L(D.reason)),p(T),h(!1)},[t]),j=o.useCallback(()=>{h(!0),f()},[f]);return o.useEffect(()=>{r([]),c([]),n([]),x(null),N([]),p({}),h(!0),f();const k=setInterval(()=>{f()},yt);return()=>{b.current++,clearInterval(k)}},[f]),{monitoringLogs:a,anomalyAlerts:s,optimizationActivity:l,stats:i,autonomySummary:g,loading:m,error:Object.values(y).join(" ")||null,errors:y,refresh:j}}function vt(t){const a=Date.now()-new Date(t).getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;const s=Math.floor(r/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}const ft={bid_optimizer:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",budget_allocator:"bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",creative_optimizer:"bg-pink-100 text-pink-800 dark:bg-pink-900/40 dark:text-pink-300",audie
1nce_optimizer:"bg-teal-100 text-teal-800 dark:bg-teal-900/40 dark:text-teal-300",schedule_optimizer:"bg-indigo-100 text-indigo-800 dark:bg-indigo-900/40 dark:text-indigo-300",content_publisher:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"},jt={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pending_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"};function Nt(t){return{proposed:"Proposed",pending_approval:"Pending",approved:"Approved",executing:"Executing",completed:"Completed",rolled_back:"Rolled Back",rejected:"Rejected",blocked:"Blocked",failed:"Failed"}[t]??t}const kt=({items:t,loading:a})=>a&&t.length===0?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 border-t-transparent animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading"})}):t.length===0?e.jsx("div",{className:"flex flex-col items-center justify-center h-48 text-center px-6",children:e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-secondary)"},children:"No monitoring activity recorded yet. Open Pause & limits to review enabled schedules, data prerequisites and the most recent checks."})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Time"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Agent"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Action"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:t.map(r=>e.jsxs("tr",{className:"border-b transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums",style:{color:"var(--color-text-secondary)"},children:vt(r.createdAt)}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ft[r.agentType]??"bg-gray-100 text-gray-700"}`,children:r.agentDisplayName})}),e.jsxs("td",{className:"px-4 py-3 max-w-xs truncate",style:{color:"var(--color-text-primary)"},title:r.description,children:[e.jsx("span",{className:"font-medium",children:r.title}),r.description&&e.jsx("span",{className:"block text-xs mt-0.5",style:{color:"var(--color-text-secondary)"},children:r.description})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${jt[r.status]??"bg-gray-100 text-gray-700"}`,children:Nt(r.status)})})]},r.id))})]})});function wt(t){const a=Math.abs(t)/100,r=t<0?"-":"";return a>=1e3?`${r}$${(a/1e3).toFixed(1)}k`:`${r}$${a.toFixed(2)}`}function Ct(t){const a=Date.now()-new Date(t).getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;const s=Math.floor(r/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function St(t){return t.status==="blocked"||t.status==="failed"?"critical":t.status==="pending_approval"?"high":t.status==="proposed"?"medium":"low"}const At={critical:"bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300",high:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",medium:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-300",low:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"},_t={critical:"border-l-red-500",high:"border-l-orange-400",medium:"border-l-yellow-400",low:"border-l-gray-300"},Tt={proposed:"Proposed",pending_approval:"Pending Approval",approved:"Approved",executing:"Executing",completed:"Completed",rolled_back:"Rolled Back",rejected:"Rejected",blocked:"Blocked",failed:"Failed"},Lt={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pen
1ding_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},$t=({items:t,loading:a})=>{if(a&&t.length===0)return e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading"})});if(t.length===0)return e.jsx("div",{className:"flex flex-col items-center justify-center h-48 text-center px-6",children:e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-secondary)"},children:"No alerts recorded in this view. This does not confirm that every campaign is monitored or performing normally. Check Pause & limits for monitoring status and prerequisites."})});const r=t.filter(s=>s.requiresAttention).length;return e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[r>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg px-4 py-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800/40",children:[e.jsx(ce,{className:"w-4 h-4 text-yellow-600 dark:text-yellow-400 shrink-0","aria-hidden":!0}),e.jsxs("span",{className:"text-sm font-medium text-yellow-800 dark:text-yellow-300",children:[r," ",r===1?"alert requires":"alerts require"," your attention"]})]}),t.map(s=>{const c=St(s);return e.jsxs("div",{className:`rounded-lg border border-l-4 p-4 ${_t[c]}`,style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-1",children:[e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${At[c]}`,children:c.charAt(0).toUpperCase()+c.slice(1)}),e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Lt[s.status]??"bg-gray-100 text-gray-700"}`,children:Tt[s.status]??s.status})]}),e.jsx("p",{className:"text-sm font-medium truncate",style:{color:"var(--color-text-primary)"},children:s.title}),s.description&&e.jsx("p",{className:"text-sm mt-0.5",style:{color:"var(--color-text-secondary)"},children:s.description})]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:Ct(s.createdAt)}),s.estimatedImpactCents!==0&&e.jsxs("p",{className:"text-xs mt-0.5",style:{color:"var(--color-text-secondary)"},children:["Est. impact:"," ",e.jsx("span",{className:"font-medium",style:{color:"var(--color-text-primary)"},children:wt(s.estimatedImpactCents)})]})]})]}),e.jsxs("div",{className:"mt-2 text-xs",style:{color:"var(--color-text-secondary)"},children:[e.jsx("span",{children:s.agentDisplayName}),s.actionType&&e.jsxs("span",{children:[" ⢠",s.actionType.replace(/_/g," ")]})]})]},s.id)})]})};function be(t){const a=Math.abs(t)/100,r=t<0?"-":"";return a>=1e3?`${r}$${(a/1e3).toFixed(1)}k`:`${r}$${a.toFixed(2)}`}function Et(t){const a=Date.now()-new Date(t).getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;const s=Math.floor(r/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}const Pt={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pen
1ding_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},Dt={proposed:"Proposed",pending_approval:"Pending",approved:"Approved",executing:"Executing",completed:"Completed",rolled_back:"Rolled Back",rejected:"Rejected",blocked:"Blocked",failed:"Failed"},Rt={closed:"text-emerald-500",open:"text-red-500",half_open:"text-yellow-500"},Ot={closed:"Healthy",open:"Circuit Open",half_open:"Recovering"};function Bt({state:t}){const a=`w-4 h-4 ${Rt[t]}`;return t==="closed"?e.jsx(qe,{className:a,"aria-hidden":!0}):t==="open"?e.jsx(Ge,{className:a,"aria-hidden":!0}):e.jsx(We,{className:a,"aria-hidden":!0})}const It={L1_suggest:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",L2_approve:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",L3_auto_small:"bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",L4_full_auto:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"},Mt=({items:t,autonomySummary:a,loading:r})=>r&&t.length===0&&a.length===0?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading"})}):e.jsxs("div",{className:"flex flex-col gap-6 p-4",children:[a.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-sm font-semibold mb-3",style:{color:"var(--color-text-secondary)"},children:"Agent Status"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:a.map(s=>e.jsxs("div",{className:"rounded-lg border p-4",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",style:{color:"var(--color-text-primary)"},children:s.displayName}),e.jsx("span",{className:`shrink-0 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${It[s.autonomyLevel]??"bg-gray-100 text-gray-700"}`,children:s.autonomyLevelName})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3",children:[e.jsx(Bt,{state:s.circuitBreakerState}),e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:Ot[s.circuitBreakerState]})]}),e.jsxs("div",{className:"flex gap-4 text-xs",style:{color:"var(--color-text-secondary)"},children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",style:{color:"var(--color-text-primary)"},children:s.completedLast24h})," ","completed"]}),e.jsxs("span",{children:[e.jsx("span",{className:`font-medium ${s.failedLast24h>0?"text-red-500":""}`,children:s.failedLast24h})," ","failed"]}),s.pendingCount>0&&e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-amber-500",children:s.pendingCount})," ","pending"]})]})]},s.agentType))})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-sm font-semibold mb-3",style:{color:"var(--color-text-secondary)"},children:"Recent Activity"}),t.length===0?e.jsx("div",{className:"flex items-center justify-center h-32 text-center px-6",children:e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-secondary)"},children:"No optimization activity yet."})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Time"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Agent"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Action"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Impact"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:t.map(s=>{const c=s.actualImpactCents!=null?s.actualImpactCents:s.estimatedImpactCents,l=s.actualImpactCents!=null?be(c):`~${be(c)}`;return e.jsxs("tr",{className:"border-b transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums",style:{color:"var(--color-text-secondary)"},children:Et(s.createdAt)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-xs",style:{color:"var(--color-text-secondary)"},children:s.agentDisplayName}),e.jsxs("td",{className:"px-4 py-3 max-w-xs",style:{color:"var(--color-text-primary)"},children:[e.jsx("p",{className:"font-medium truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs mt-0.5 truncate",style:{color:"var(--color-text-secondary)"},title:s.description,children:s.description})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums text-xs",style:{color:"var(--color-text-secondary)"},children:c!==0?l:"â"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Pt[s.status]??"bg-gray-100 text-gray-700"}`,children:Dt[s.status]??s.status})})]},s.id)})})]})})]})]});function ye(t){const a=Date.now()-new Date(t).getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const s=Math.floor(r/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function he(t){const a=Math.abs(t)/100,r=t<0?"-":"+";return a>=1e3?`${r}$${(a/1e3).toFixed(1)}k`:`${r}$${a.toFixed(2)}`}function se(t,a){return t.length<=a?t:`${t.slice(0,a)}â¦`}const ve={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pen
1ding_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},fe={proposed:"Proposed",pending_approval:"Pending",approved:"Approved",executing:"Executing",completed:"Completed",rolled_back:"Rolled Back",rejected:"Rejected",blocked:"Blocked",failed:"Failed"},Ut=({cols:t})=>e.jsx("tr",{style:{borderColor:"var(--color-border-muted)"},className:"border-b",children:Array.from({length:t}).map((a,r)=>e.jsx("td",{className:"px-4 py-3",children:e.jsx("div",{className:"h-3 rounded animate-pulse",style:{backgroundColor:"var(--color-border-muted)",width:r===0?"4rem":"80%"}})},r))}),je=({title:t,emptyMessage:a,loading:r,isEmpty:s,colCount:c,children:l,headerRow:n})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-sm font-semibold px-4 pt-4 pb-2",style:{color:"var(--color-text-secondary)"},children:t}),r&&s?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:n}),e.jsx("tbody",{children:[0,1,2].map(i=>e.jsx(Ut,{cols:c},i))})]})}):s?e.jsx("div",{className:"flex items-center justify-center h-20 text-sm",style:{color:"var(--color-text-secondary)"},children:a}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:n}),e.jsx("tbody",{children:l})]})})]}),Ft=({items:t,loading:a})=>{const r=t.filter(l=>l.agentType==="content_publisher"),s=t.filter(l=>l.agentType==="budget_allocator"&&l.actionType==="budget_reallocation"),c={borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"};return e.jsxs("div",{className:"flex flex-col gap-2 pb-4",children:[e.jsx(je,{title:"Publishing Queue",emptyMessage:"No recent publishing activity",loading:a,isEmpty:r.length===0,colCount:4,headerRow:e.jsxs("tr",{className:"border-b text-left",style:c,children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Time"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Platform"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Post Title"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Status"})]}),children:r.map(l=>{var i;const n=typeof((i=l.metadata)==null?void 0:i.platform)=="string"?l.metadata.platform:l.agentDisplayName;return e.jsxs("tr",{className:"border-b transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums text-xs",style:{color:"var(--color-text-secondary)"},children:ye(l.createdAt)}),e.jsx("td",{className:"px-4 py-3 text-xs capitalize",style:{color:"var(--color-text-secondary)"},children:n}),e.jsx("td",{className:"px-4 py-3 max-w-xs",style:{color:"var(--color-text-primary)"},title:l.description,children:se(l.description||l.title,60)}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ve[l.status]??"bg-gray-100 text-gray-700"}`,children:fe[l.status]??l.status})})]},l.id)})}),e.jsx("div",{className:"border-t mx-4",style:{borderColor:"var(--color-border-muted)"}}),e.jsx(je,{title:"Budget Rebalancing",emptyMessage:"No recent budget rebalancing",loading:a,isEmpty:s.length===0,colCount:5,headerRow:e.jsxs("tr",{className:"border-b text-left",style:c,children:[e.jsx("th",{className:"px-4 py-3 font-medium",children:"Time"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Campaign"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Change"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Status"}),e.jsx("th",{className:"px-4 py-3 font-medium",children:"Impact"})]}),children:s.map(l=>{var m,h,y;const n=typeof((m=l.metadata)==null?void 0:m.currentValue)=="number"?l.metadata.currentValue:null,i=typeof((h=l.metadata)==null?void 0:h.proposedValue)=="number"?l.metadata.proposedValue:null,x=n!=null&&i!=null?`${he(n)} â ${he(i)}`:"â",g=(y=l.metadata)==null?void 0:y.targetEntityId,N=typeof g=="string"?se(g,24):se(l.description,30);return e.jsxs("tr",{className:"border-b transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums text-xs",style:{color:"var(--color-text-secondary)"},children:ye(l.createdAt)}),e.jsx("td",{className:"px-4 py-3 text-xs max-w-[10rem] truncate",style:{color:"var(--color-text-primary)"},title:l.description,children:N}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums text-xs",style:{color:"var(--color-text-secondary)"},children:x}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ve[l.status]??"bg-gray-100 text-gray-700"}`,children:fe[l.status]??l.status})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap tabular-nums text-xs",style:{color:"var(--color-text-secondary)"},children:l.estimatedImpactCents>0?`$${(l.estimatedImpactCents/100).toFixed(2)}`:"â"})]},l.id)})})]})};async function zt(){return _("/v1/agents/actions/pending")}async function Vt(t,a){return me(`/v1/agents/actions/${t}/approve`,{approvalRevision:a})}async function Kt(t,a){return me(`/v1/agents/actions/${t}/reject`,{reason:a})}async function qt(t="today"){return _(`/v1/agents/dashboard/value-summary?period=${encodeURIComponent(t)}`)}
1function Gt(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function Wt(t){return t.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}const Yt={bid_optimizer:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",budget_allocator:"bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",creative_optimizer:"bg-pink-100 text-pink-800 dark:bg-pink-900/40 dark:text-pink-300",audience_optimizer:"bg-teal-100 text-teal-800 dark:bg-teal-900/40 dark:text-teal-300",schedule_optimizer:"bg-indigo-100 text-indigo-800 dark:bg-indigo-900/40 dark:text-indigo-300",content_publisher:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"},Jt={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pending_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},Ht={budget_guard_pause:"Budget Guard: Pause",publish_scheduled_post:"Publish Scheduled Post",budget_reallocation:"Budget Reallocation",budget_reallocation_owned:"Budget Reallocation (Owned)",bid_decrease:"Bid Decrease",bid_increase:"Bid Increase",budget_decrease:"Budget Decrease",budget_increase:"Budget Increase",ab_promote_email:"Email A/B Auto-Promote",ab_promote_sms:"SMS A/B Auto-Promote"};function Zt(t){return Ht[t]??t.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}function Qt(t){const a=t==null?void 0:t.currentBudgetCents,r=t==null?void 0:t.recommendedBudgetCents;return typeof a!="number"||typeof r!="number"?null:`$${(a/100).toFixed(2)} â $${(r/100).toFixed(2)}`}const Ne=25,Xt=[{value:"",label:"All Agents"},{value:"content_publisher",label:"Content Publisher"},{value:"budget_allocator",label:"Budget Allocator"},{value:"bid_optimizer",label:"Bid Optimizer"},{value:"creative_optimizer",label:"Creative Optimizer"},{value:"audience_optimizer",label:"Audience Optimizer"},{value:"schedule_optimizer",label:"Schedule Optimizer"}],ea=[{value:"",label:"All Actions"},{value:"publish_scheduled_post",label:"Publish Scheduled Post"},{value:"budget_reallocation",label:"Budget Reallocation"},{value:"budget_reallocation_owned",label:"Budget Reallocation (Owned)"},{value:"bid_decrease",label:"Bid Decrease"},{value:"bid_increase",label:"Bid Increase"},{value:"budget_decrease",label:"Budget Decrease"},{value:"budget_increase",label:"Budget Increase"},{value:"budget_guard_pause",label:"Budget Guard: Pause"},{value:"ab_promote_email",label:"Email A/B Auto-Promote"},{value:"ab_promote_sms",label:"SMS A/B Auto-Promote"}],ta=({orgId:t,initialActionType:a})=>{const[r,s]=o.useState([]),[c,l]=o.useState(0),[n,i]=o.useState(!0),[x,g]=o.useState(!1),[N,m]=o.useState(null),[h,y]=o.useState(0),[p,b]=o.useState([]),[f,j]=o.useState(!0),[k,C]=o.useState(null),[A,$]=o.useState(null),[E,D]=o.useState(null),[T,L]=o.useState(0);o.useEffect(()=>{let d=!1;return j(!0),b([]),C(null),zt().then(v=>{d||b(v.filter(S=>S.status==="pending_approval"))}).catch(v=>{d||C(v instanceof Error?v.message:"Pending reviews unavailable")}).finally(()=>{d||j(!1)}),()=>{d=!0}},[t,T]);const R=async(d,v)=>{if(d.approvalChainId===null){$(d.id),D(null),C(null);try{const S=v?await Kt(d.id,v):await Vt(d.id,d.approvalRevision);D(`Review saved. Action state: ${S.status}. This is not a delivery receipt.`),L(q=>q+1)}catch(S){C(S instanceof Error?S.message:"Review could not be submitted. Refresh to check its current state.")}finally{$(null)}}},[M,G]=o.useState(""),[U,O]=o.useState(a??""),[F,z]=o.useState(""),[P,ae]=o.useState(""),V=o.useCallback(()=>({limit:Ne,offset:0,agentType:M||void 0,actionType:U||void 0,fromDate:F||void 0,toDate:P||void 0}),[M,U,F,P]);o.useEffect(()=>{let d=!1;return i(!0),y(0),m(null),ge(V()).then(v=>{d||(s(v.items),l(v.total),i(!1))}).catch(v=>{d||(m(v instanceof Error?v.message:"Failed to load timeline"),i(!1))}),()=>{d=!0}},[V,t,T]);const re=o.useCallback(async()=>{const d=h+Ne;g(!0);try{const v=await ge({...V(),offset:d});s(S=>[...S,...v.items]),y(d)}catch(v){m(v instanceof Error?v.message:"Failed to load more")}finally{g(!1)}},[h,V]),W="rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-0",K={backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"},Y={backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4 py-3 border-b",style:{borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Agent"}),e.jsx("select",{value:M,onChange:d=>G(d.target.value),className:W,style:K,children:Xt.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Action"}),e.jsx("select",{value:U,onChange:d=>O(d.target.value),className:W,style:K,children:ea.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"From"}),e.jsx("input",{type:"date",value:F,onChange:d=>z(d.target.value),className:"rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-2",style:Y})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"To"}),e.jsx("input",{type:"date",value:P,onChange:d=>
1ae(d.target.value),className:"rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-2",style:Y})]})]}),!n&&e.jsxs("div",{className:"px-4 py-2 text-xs",style:{color:"var(--color-text-secondary)"},children:["Showing ",r.length," of ",c]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:[e.jsxs("section",{"aria-label":"Pending action reviews",className:"py-4 border-b border-slate-700 mb-4",children:[e.jsx("h2",{className:"font-semibold",children:"Pending action reviews"}),e.jsx("button",{type:"button",onClick:()=>L(d=>d+1),disabled:f||A!==null,className:"my-2 underline",children:"Refresh pending reviews"}),f&&e.jsx("p",{role:"status",children:"Loading saved actions for reviewâ¦"}),k&&e.jsx("p",{role:"alert",children:k}),E&&e.jsx("p",{role:"status",children:E}),!f&&!k&&p.length===0&&e.jsx("p",{children:"No pending action reviews returned by the server."}),p.map(d=>e.jsxs("details",{className:"my-3 p-3 border border-slate-600 rounded-lg",children:[e.jsx("summary",{className:"cursor-pointer font-medium",children:d.description||d.actionType}),e.jsxs("p",{className:"mt-2",children:["Action: ",d.id," · State: ",d.status]}),e.jsx(pe,{actionType:d.actionType,metadata:d.metadata}),!d.actionType.includes("_generative_")&&e.jsx("pre",{className:"whitespace-pre-wrap break-words my-3",children:d.metadata?JSON.stringify(d.metadata,null,2):"Saved execution parameters unavailable"}),d.approvalChainId!==null?e.jsx("a",{href:"/approvals",className:"underline",children:"Review this action through its approval workflow"}):e.jsxs(ct,{minRole:"editor",children:[e.jsx("button",{type:"button",disabled:A!==null||!d.approvalRevision||!nt(d.actionType,d.metadata),onClick:()=>void R(d),className:"px-4 py-2 rounded bg-nexus-600 text-white disabled:opacity-50",children:"Approve reviewed action"}),e.jsxs("form",{className:"mt-3",onSubmit:v=>{v.preventDefault();const S=String(new FormData(v.currentTarget).get("reason")??"").trim();S&&R(d,S)},children:[e.jsxs("label",{className:"block",children:["Reason for rejecting this action",e.jsx("textarea",{name:"reason",required:!0,className:"block w-full my-2 p-2 bg-slate-900 border border-slate-600 rounded"})]}),e.jsx("button",{type:"submit",disabled:A!==null,className:"px-4 py-2 rounded border border-red-500 disabled:opacity-50",children:"Reject reviewed action"})]}),e.jsx("p",{className:"mt-2 text-sm",children:"Approval may queue execution after current checks. It does not mean sent, delivered or measured."})]})]},d.id))]}),n?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading"})}):N?e.jsx("div",{className:"flex items-center justify-center h-32 text-sm text-red-500",children:N}):r.length===0?e.jsx("div",{className:"flex items-center justify-center h-32 text-sm text-center",style:{color:"var(--color-text-secondary)"},children:"No autonomous actions recorded yet."}):e.jsx("ol",{className:"relative border-l mt-3",style:{borderColor:"var(--color-border-muted)"},children:r.map(d=>{var I,u;const v=(I=d.metadata)==null?void 0:I.nativeBudgetWrite,S=v!==void 0||["budget_increase","budget_decrease"].includes(d.actionType),q=dt(v)?v.currency:S?null:"USD",J=d.estimatedImpactCents>0&&q?new Intl.NumberFormat("en-US",{style:"currency",currency:q,currencyDisplay:S?"code":"symbol"}).format(d.estimatedImpactCents/100):null,H=d.autonomyLevel??(typeof((u=d.metadata)==null?void 0:u.autonomyLevel)=="string"?d.metadata.autonomyLevel:null),B=d.actionType==="budget_reallocation_owned"?Qt(d.metadata):null;return e.jsxs("li",{className:"mb-6 ml-4",children:[e.jsx("span",{className:"absolute -left-1.5 mt-1 w-3 h-3 rounded-full border-2",style:{backgroundColor:"var(--color-brand-500)",borderColor:"var(--color-bg-base)"},"aria-hidden":!0}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("time",{className:"text-xs tabular-nums",style:{color:"var(--color-text-secondary)"},dateTime:d.timestamp,children:Gt(d.timestamp)}),e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-primary)"},children:d.description}),e.jsx(pe,{actionType:d.actionType,metadata:d.metadata}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Yt[d.agentType]??"bg-gray-100 text-gray-700"}`,children:Wt(d.agentType)}),e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",children:Zt(d.actionType)}),e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Jt[d.status]??"bg-gray-100 text-gray-700"}`,children:d.status}),J&&e.jsxs("span",{className:"text-xs tabular-nums",style:{color:"var(--color-text-secondary)"},children:["Estimated impact (not measured): ",J]}),B&&e.jsx("span",{className:"text-xs tabular-nums",style:{color:"var(--color-text-secondary)"},children:B}),H&&e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:H})]})]})]},d.id)})}),!n&&r.length<c&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx("button",{type:"button",onClick:()=>void re(),disabled:x,className:"px-4 py-2 rounded-lg text-sm font-medium border transition-colors disabled:opacity-50",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},children:x?"Loadingâ¦":"Load more"})})]})]})},ke=[{value:"L1_suggest",label:"L1 - Suggest Only"},{value:"L2_approve",label:"L2 - Approval Before Execution"},{value:"L3_auto_small",label:"L3 - Auto (Small)"},{value:"L4_full_auto",label:"L4 - Auto Within Safety Limits"}],aa=["publish_scheduled_post","marketing_review","budget_guard_pause","budget_reallocation_owned","bid_decrease","bid_increase","budget_decrease","budget_increase","creative_pause","creative_resume","creative_promote","creative_demote","ab_promote_email","ab_promote_sms","sms_generative_winback","sms_generative_ab","email_generative_winback"],we={marketing_review:"Delegated marketing review",budget_guard_pause:"Pause SMS Campaign at Spend Cap",budget_reallocation_owned:"Reallocate Owned Campaign Budgets",budget_increase:"Increase Ad Platform Budget",budget_decrease:"Decrease Ad Platform Budget",ab_promote_email:"Promote Email A/B Winner",ab_promote_sms:"Promote SMS A/B Winner",sms_generative_winback:"Generate and Send SMS Win-back",sms_generative_ab:"Generate SMS A/B Test",email_generative_winback:"Generate and Send Email Win-back"};function Ce(t){return we[t]?we[t]:t.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}function Se(t){return t.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}const ra={L1_suggest:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",L2_approve:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",L3_auto_small:"bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",L4_full_auto:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"},sa=({agent:t,onSaved:a})=>{const[r,s]=o.useState({autonomyLevel:t.autonomyLevel,activityOverrides:{...t.activityTypeOverrides},saving:!1,saved:!1,error:null}),c=o.useRef(null),l=o.useRef(null);o.useEffect(()=>{c.current||s(m=>({...m,autonomyLevel:t.autonomyLevel,activityOverrides:{...t.activityTypeOverrides}}))},[t.autonomyLevel,t.activityTypeOverrides]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current)},[]);const n=o.useCallback((m,h)=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>
1{s(p=>({...p,saving:!0,saved:!1,error:null}));const y={};for(const[p,b]of Object.entries(h))b&&(y[p]=b);gt({agentType:t.agentType,autonomyLevel:m,activityTypeOverrides:Object.keys(y).length>0?y:null}).then(()=>{c.current=null,s(p=>({...p,saving:!1,saved:!0})),a(),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{s(p=>({...p,saved:!1}))},2500)}).catch(p=>{c.current=null,s(b=>({...b,saving:!1,error:p instanceof Error?p.message:"Save failed"}))})},500)},[t.agentType,a]),i=m=>{s(h=>({...h,autonomyLevel:m})),n(m,r.activityOverrides)},x=(m,h)=>{const y={...r.activityOverrides,[m]:h};s(p=>({...p,activityOverrides:y})),n(r.autonomyLevel,y)},g="rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-0 w-full",N={backgroundColor:"var(--color-bg-base)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"};return e.jsxs("div",{className:"rounded-lg border p-4 flex flex-col gap-4",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold",style:{color:"var(--color-text-primary)"},children:Se(t.agentType)}),e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${ra[r.autonomyLevel]??"bg-gray-100 text-gray-700"}`,children:r.autonomyLevel})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-medium ${t.isActive?"text-emerald-500":"text-gray-400"}`,children:t.isActive?"Active":"Inactive"}),r.saving&&e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Savingâ¦"}),r.saved&&e.jsx("span",{className:"text-xs text-emerald-500",children:"Saved"}),r.error&&e.jsx("span",{className:"text-xs text-red-500",children:r.error})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Default Autonomy Level"}),e.jsx("select",{value:r.autonomyLevel,disabled:r.saving,onChange:m=>i(m.target.value),className:g,style:N,"aria-label":`Default autonomy level for ${Se(t.agentType)}`,children:ke.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Activity Overrides"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Array.from(new Set([...aa,...Object.keys(r.activityOverrides)])).map(m=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:Ce(m)}),e.jsxs("select",{value:r.activityOverrides[m]??"",disabled:r.saving,onChange:h=>x(m,h.target.value),className:g,style:N,"aria-label":`Autonomy override for ${Ce(m)}`,children:[e.jsx("option",{value:"",children:"Use Default"}),ke.map(h=>e.jsx("option",{value:h.value,children:h.label},h.value))]})]},m))})]}),e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"L1 and L2 require approval before execution. Higher levels still enforce spending limits, mandatory approval thresholds, rate limits, and circuit breakers."})]})},oa=({guardrails:t,loading:a,onRefresh:r})=>a&&t.length===0?e.jsx("div",{className:"flex items-center justify-center h-48",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading"})}):t.length===0?e.jsx("div",{className:"flex items-center justify-center h-48 text-sm",style:{color:"var(--color-text-secondary)"},children:"No agent guardrails configured yet."}):e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"mb-4 text-sm",style:{color:"var(--color-text-secondary)"},children:"Organization-wide agent settings apply across all businesses and projects. These are autonomy controls, not per-business budgets."}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:t.map(s=>e.jsx(sa,{agent:s,onSaved:r},s.agentType))})]});function la(t){if(!t)return"â";const a=new Date(t);return isNaN(a.getTime())?"â":a.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ae(t){return`${Math.round(t*100)}%`}const na=({promotion:t})=>{const{testName:a,winnerSubject:r,winnerVariantName:s,confidenceThreshold:c,concludedAt:l,winnerSentCount:n,winnerOpenCount:i,campaignRecipientCount:x}=t,g=n&&i&&n>0?i/n:null;return e.jsxs("div",{className:"rounded-lg border p-4 flex flex-col gap-3",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 rounded-md p-1.5 shrink-0",style:{backgroundColor:"var(--color-brand-500)20"},children:e.jsx(Ye,{className:"w-4 h-4",style:{color:"var(--color-brand-500)"},"aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",style:{color:"var(--color-text-primary)"},children:a}),s&&e.jsxs("p",{className:"text-xs mt-0.5 truncate",style:{color:"var(--color-text-secondary)"},children:["Winner: ",s]})]}),e.jsxs("span",{className:"shrink-0 text-xs px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:"var(--color-brand-500)20",color:"var(--color-brand-500)"},children:["Bayesian ⥠",Ae(c)]})]}),r&&e.jsxs("div",{className:"rounded border-l-2 pl-3 py-1 text-sm italic",style:{borderColor:"var(--color-brand-500)",color:"var(--color-text-secondary)"},children:['"',r,'"']}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Sent"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",style:{color:"var(--color-text-primary)"}
1,children:n!=null?n.toLocaleString():"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Open rate"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",style:{color:"var(--color-text-primary)"},children:g!=null?Ae(g):"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Campaign size"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",style:{color:"var(--color-text-primary)"},children:x!=null?x.toLocaleString():"â"})]})]}),e.jsxs("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:["Declared ",la(l)]})]})},da=()=>{const[t,a]=o.useState([]),[r,s]=o.useState(!0),[c,l]=o.useState(null);return o.useEffect(()=>{let n=!1;async function i(){s(!0),l(null);try{const x=await bt();n||a(x)}catch{n||l("Failed to load A/B promotion history.")}finally{n||s(!1)}}return i(),()=>{n=!0}},[]),r?e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-label":"Loading A/B promotion data"})}):c?e.jsx("div",{className:"flex items-center justify-center h-32 px-6 text-center",children:e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-secondary)"},children:c})}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 gap-2 text-center px-6",children:[e.jsx(ue,{className:"w-6 h-6",style:{color:"var(--color-text-secondary)"},"aria-hidden":!0}),e.jsx("p",{className:"text-sm",style:{color:"var(--color-text-secondary)"},children:"No completed A/B tests yet. Winners will appear here once the AI declares them."})]}):e.jsxs("div",{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ue,{className:"w-4 h-4",style:{color:"var(--color-brand-500)"},"aria-hidden":!0}),e.jsx("h2",{className:"text-sm font-semibold",style:{color:"var(--color-text-primary)"},children:"Email A/B Auto-Promotions"}),e.jsxs("span",{className:"ml-auto text-xs px-2 py-0.5 rounded-full",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)",border:"1px solid"},children:[t.length," completed"]})]}),t.map(n=>e.jsx(na,{promotion:n},n.abTestId))]})};async function ca(){return _("/v1/autonomy/loops")}async function X(t,a){return Be(`/v1/autonomy/loops/${t}`,a)}async function ia(t){return me(`/v1/autonomy/loops/${t}/preview`,{})}function ma(t){return t.masterEnabled?t.mode==="auto_apply"?"auto":"shadow":"off"}const _e={off:"Off",shadow:"Shadow",auto:"Auto"},ua={off:"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400",shadow:"bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",auto:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300"},xa=({status:t})=>e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-semibold ${ua[t]}`,"aria-label":`Loop status: ${_e[t]}`,children:[t==="auto"&&e.jsx(Ze,{className:"w-3 h-3","aria-hidden":!0}),t==="shadow"&&e.jsx(Qe,{className:"w-3 h-3","aria-hidden":!0}),t==="off"&&e.jsx(le,{className:"w-3 h-3","aria-hidden":!0}),_e[t]]}),pa=({loopKey:t})=>{const[a,r]=o.useState(!1),[s,c]=o.useState(null),[l,n]=o.useState(null),i=async()=>{r(!0),n(null),c(null);try{const x=await ia(t);c(x)}catch(x){n(x instanceof Error?x.message:"Preview failed.")}finally{r(!1)}};return e.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[e.jsxs("button",{onClick:i,disabled:a,"aria-label":"Run preview now",className:"self-start flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",style:{backgroundColor:"var(--color-brand-500)",color:"#fff",opacity:a?.6:1,cursor:a?"not-allowed":"pointer"},children:[a?e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":!0}):e.jsx(Xe,{className:"w-3.5 h-3.5","aria-hidden":!0}),a?"Runningâ¦":"Run preview now"]}),l&&e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},role:"alert",children:l}),s&&!s.ready&&e.jsxs("p",{className:"text-xs rounded-md px-3 py-2 border",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},role:"status",children:["Not ready: ",s.notReadyReason??"Missing prerequisites."]}),s&&s.ready&&s.proposals.length===0&&e.jsx("p",{className:"text-xs rounded-md px-3 py-2 border",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},role:"status",children:"Nothing to act on right now."}),s&&s.ready&&s.proposals.length>0&&e.jsx("ul",{className:"flex flex-col gap-1.5",role:"list","aria-label":"Preview proposals",children:s.proposals.map(x=>e.jsxs("li",{className:"text-xs rounded-md px-3 py-2 border",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"},children:[e.jsx("span",{className:"font-medium",children:x.campaignName})," â ",x.description]},x.campaignId))})]})},ga=({loop:t,onSaved:a})=>{const[r,s]=o.useState(String(t.caps.maxActionsPerRun)),[c,l]=o.useState(String(t.caps.maxBudgetDeltaCentsPerRun/100)),[n,i]=o.useState(String(t.caps.maxBudgetDeltaCentsPerDay/100)),[x,g]=o.useState(!1),[N,m]=o.useState(null),h=async()=>{const p=parseInt(r,10),b=parseFloat(c),f=parseFloat(n);if(isNaN(p)||p<1||isNaN(b)||b<0||isNaN(f)||f<0){m("Invalid cap values. Actions must be â¥1; budgets must be â¥0.");return}g(!0),m(null);try{const j=await X(t.loopKey,{maxActionsPerRun:p,maxBudgetDeltaCentsPerRun:Math.round(b*100),maxBudgetDeltaCentsPerDay:Math.round(f*100)});a({...t,...j})}catch(j){m(j instanceof Error?j.message:"Save failed.")}finally{g(!1)}},y={backgroundColor:"var(--color-bg-base)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"};return e.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[e.jsx("p",{className:"text-xs font-semibold",style:{color:"var(--color-text-secondary)"},children:"Caps"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Actions / run"}),e.jsx("input",{type:"number",min:1,step:1,value:r,onChange:p=>s(p.target.value),"aria-label":"Max actions per run",className:"rounded border px-2 py-1 text-xs",style:y})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Budget / run ($)"}
1),e.jsx("input",{type:"number",min:0,step:.01,value:c,onChange:p=>l(p.target.value),"aria-label":"Max budget delta per run in dollars",className:"rounded border px-2 py-1 text-xs",style:y})]}),e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Budget / day ($)"}),e.jsx("input",{type:"number",min:0,step:.01,value:n,onChange:p=>i(p.target.value),"aria-label":"Max budget delta per day in dollars",className:"rounded border px-2 py-1 text-xs",style:y})]})]}),N&&e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},role:"alert",children:N}),e.jsxs("button",{onClick:h,disabled:x,"aria-label":"Save caps",className:"self-start flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)",opacity:x?.6:1,cursor:x?"not-allowed":"pointer"},children:[x?e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":!0}):null,x?"Savingâ¦":"Save caps"]})]})},ba=({loop:t,onUpdated:a})=>{const[r,s]=o.useState(!1),[c,l]=o.useState(!1),[n,i]=o.useState(!1),[x,g]=o.useState(null),N=ma(t),m=async()=>{const b=!t.masterEnabled;if(!(b&&t.mode==="auto_apply"&&!window.confirm(`Enable "${t.name}" in Auto mode? 2 3This restores the saved Auto mode and permits live campaign changes when its worker runs, subject to existing approval and budget guardrails. Cancel to choose observe-only mode first.`))){l(!0),g(null);try{const f=await X(t.loopKey,{masterEnabled:b});a({...t,...f})}catch(f){g(f instanceof Error?f.message:"Update failed.")}finally{l(!1)}}},h=async b=>{if(!(b==="auto_apply"&&!window.confirm(`Save Auto mode for "${t.name}"? 4 5When enabled, this permits live campaign changes when its worker runs, subject to existing approval and budget guardrails. This is not an observe-only preview.`))){i(!0),g(null);try{const f=await X(t.loopKey,{mode:b});a({...t,...f})}catch(f){g(f instanceof Error?f.message:"Mode change failed.")}finally{i(!1)}}},y=async()=>{l(!0),g(null);try{const b=await X(t.loopKey,{masterEnabled:!1});a({...t,...b})}catch(b){g(b instanceof Error?b.message:"Pause failed.")}finally{l(!1)}},p={backgroundColor:"var(--color-bg-base)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"};return e.jsxs("div",{className:"rounded-lg border p-4 flex flex-col gap-3",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},"aria-label":`Autonomy loop: ${t.name}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-semibold truncate",style:{color:"var(--color-text-primary)"},children:t.name}),e.jsx(xa,{status:N}),!t.dataReady&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400","aria-label":"Data not ready for this loop",children:[e.jsx(ce,{className:"w-3 h-3","aria-hidden":!0}),"No data"]})]}),e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:t.description})]}),e.jsx("button",{onClick:()=>s(b=>!b),"aria-expanded":r,"aria-label":r?"Collapse loop controls":"Expand loop controls",className:"shrink-0 rounded p-1 transition-colors",style:{color:"var(--color-text-secondary)"},children:r?e.jsx(Je,{className:"w-4 h-4","aria-hidden":!0}):e.jsx(Re,{className:"w-4 h-4","aria-hidden":!0})})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[e.jsxs("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:["Channel: ",e.jsx("strong",{style:{color:"var(--color-text-primary)"},children:t.channel})]}),e.jsxs("span",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:["Requires: ",e.jsx("strong",{style:{color:"var(--color-text-primary)"},children:t.prerequisites})]})]}),e.jsxs("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:["Saved mode: ",t.mode==="shadow"?"Observe only â proposals, no campaign changes.":"Auto â live campaign changes permitted, subject to guardrails."," ","Changes save immediately. Enabling uses this
5saved mode on subsequent worker runs; it does not run a preview."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:m,disabled:c||n,"aria-label":t.masterEnabled?"Disable loop":t.mode==="shadow"?"Enable observe-only mode":"Enable live Auto mode",className:"flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)",opacity:c?.6:1,cursor:c?"not-allowed":"pointer"},children:[c?e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin","aria-hidden":!0}):t.masterEnabled?e.jsx(le,{className:"w-3.5 h-3.5","aria-hidden":!0}):e.jsx(He,{className:"w-3.5 h-3.5","aria-hidden":!0}),t.masterEnabled?"Disable loop":t.mode==="shadow"?"Enable observe-only mode":"Enable live Auto mode"]}),e.jsxs("select",{value:t.mode,onChange:b=>void h(b.target.value),disabled:n||c,"aria-label":"Loop mode",className:"rounded border px-2 py-1.5 text-xs",style:p,children:[e.jsx("option",{value:"shadow",children:"Observe only (no campaign changes)"}),e.jsx("option",{value:"auto_apply",children:"Auto (live campaign changes)"})]}),t.masterEnabled&&e.jsxs("button",{onClick:y,disabled:c,"aria-label":"Emergency pause â disable loop immediately",className:"ml-auto flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors",style:{backgroundColor:"rgba(220,38,38,0.1)",border:"1px solid rgba(220,38,38,0.3)",color:"#dc2626",opacity:c?.6:1,cursor:c?"not-allowed":"pointer"},children:[e.jsx(le,{className:"w-3.5 h-3.5","aria-hidden":!0}),"Pause (kill-switch)"]})]}),x&&e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},role:"alert",children:x}),r&&e.jsxs("div",{className:"border-t pt-3 flex flex-col gap-4",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx(ga,{loop:t,onSaved:a}),e.jsx("div",{style:{borderTop:"1px solid var(--color-border-muted)",paddingTop:"0.75rem"},children:e.jsx(pa,{loopKey:t.loopKey})})]})]})},ya=()=>{const[t,a]=o.useState([]),[r,s]=o.useState(!0),[c,l]=o.useState(null);o.useEffect(()=>{let i=!1;return(async function(){s(!0),l(null);try{const g=await ca();i||a(g)}catch(g){i||l(g instanceof Error?g.message:"Failed to load loops.")}finally{i||s(!1)}})(),()=>{i=!0}},[]);const n=i=>{a(x=>x.map(g=>g.loopKey===i.loopKey?i:g))};return r?e.jsx("div",{className:"h-32 flex items-center justify-center",role:"status","aria-label":"Loading autonomy loops",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},"aria-hidden":!0})}):c?e.jsxs("div",{className:"h-32 flex items-center justify-center gap-2",role:"alert",style:{color:"var(--color-text-secondary)"},children:[e.jsx(ce,{className:"w-5 h-5","aria-hidden":!0}),e.jsx("p",{className:"text-sm",children:c})]}):t.length===0?e.jsx("div",{className:"h-32 flex items-center justify-center",role:"status",style:{color:"var(--color-text-secondary)"},children:e.jsx("p",{className:"text-sm",children:"No autonomy loops configured for this workspace."})}):e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{className:"text-base font-semibold",style:{color:"var(--color-text-primary)"},children:"Autonomy Control"}),e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:"Loops need connected campaign data and running workers. Observe-only mode computes proposals without campaign changes. Auto mode permits live changes subject to each loopâs approval and budget guardrails."})]}),e.jsx("div",{className:"flex flex-col gap-3",role:"list","aria-label":"Autonomy loops",children:t.map(i=>e.jsx("div",{role:"listitem",children:e.jsx(ba,{loop:i,onUpdated:n})},i.loopKey))})]})},Ue=[{value:"today",label:"Today"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"}];function de(t){if(t===0)return"$0";const a=t/100;return a>=1e3?`$${(a/1e3).toFixed(1)}k`:a>=1?`$${a.toFixed(0)}`:`$${a.toFixed(2)}`}const oe=({icon:t,label:a,value:r,sub:s,accent:c="default","data-testid":l})=>{const n=c==="green"?"var(--color-success-500, #22c55e)":c==="blue"?"var(--color-brand-500)":c==="amber"?"var(--color-warning-500, #f59e0b)":"var(--color-text-secondary)";return e.jsxs("div",{className:"rounded-lg border p-4 flex flex-col gap-2",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},"data-testid":l,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{style:{color:n}
5,"aria-hidden":!0,children:t}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",style:{color:"var(--color-text-secondary)"},children:a})]}),e.jsx("p",{className:"text-3xl font-semibold tabular-nums",style:{color:"var(--color-text-primary)"},children:r}),e.jsx("p",{className:"text-xs",style:{color:"var(--color-text-secondary)"},children:s})]})},Te={ab_lift:"A/B lift",avoided_spend:"Avoided spend",budget_moved:"Budget reallocation",budget_delta:"Budget change",bid_projection:"Bid projection",unknown:"Unclassified"};function ha(t){switch(t){case"avoided_spend":return"budget_guard_pause";case"budget_moved":return"budget_reallocation_owned";case"ab_lift":return"ab_promote_email";default:return}}const va=({byBasis:t,onViewActions:a})=>{const r=Object.entries(t).filter(([,s])=>s!==0);return r.length===0?null:e.jsxs("div",{className:"rounded-lg border p-4",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},"data-testid":"basis-breakdown",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide mb-3",style:{color:"var(--color-text-secondary)"},children:"Impact by basis"}),e.jsx("div",{className:"flex flex-col gap-2",children:r.sort(([,s],[,c])=>c-s).map(([s,c])=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{style:{color:"var(--color-text-secondary)"},children:Te[s]??s}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"tabular-nums font-medium",style:{color:"var(--color-text-primary)"},children:de(c)}),a&&e.jsx("button",{type:"button",onClick:()=>a(ha(s)),className:"text-xs underline underline-offset-2",style:{color:"var(--color-brand-500)"},"aria-label":`View timeline actions for ${Te[s]??s}`,children:"View â"})]})]},s))})]})},fa=({opensDelta:t,clicksDelta:a,onViewActions:r})=>e.jsxs("div",{className:"rounded-lg border p-4",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},"data-testid":"engagement-card",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(at,{className:"w-4 h-4",style:{color:"var(--color-brand-500)"},"aria-hidden":!0}),e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide",style:{color:"var(--color-text-secondary)"},children:"A/B engagement lift"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums",style:{color:"var(--color-text-primary)"},children:t>0?`+${t.toLocaleString()}`:t.toLocaleString()}),e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--color-text-secondary)"},children:"Opens"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums",style:{color:"var(--color-text-primary)"},children:a>0?`+${a.toLocaleString()}`:a.toLocaleString()}),e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--color-text-secondary)"},children:"Clicks"})]})]}),e.jsx("p",{className:"text-xs mt-3",style:{color:"var(--color-text-secondary)"},children:"Incremental opens and clicks from A/B winner promotions. Not converted to dollars."}),r&&e.jsx("button",{type:"button",onClick:()=>r("ab_promote_email"),className:"text-xs underline underline-offset-2 mt-2 block",style:{color:"var(--color-brand-500)"},"aria-label":"View email A/B promotion actions on the timeline",children:"View email A/B actions on the timeline â"})]}),ja=({period:t})=>{var r;const a=((r=Ue.find(s=>s.value===t))==null?void 0:r.label)??t;return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3 text-center","data-testid":"empty-state",children:[e.jsx(Oe,{className:"w-10 h-10",style:{color:"var(--color-text-secondary)",opacity:.4},"aria-hidden":!0}),e.jsxs("p",{className:"text-sm font-medium",style:{color:"var(--color-text-secondary)"},children:["No completed actions for ",a]}),e.jsx("p",{className:"text-xs max-w-xs",style:{color:"var(--color-text-secondary)",opacity:.7},children:"Impact figures appear once autonomous agents complete actions in this period."})]})},Na=({onViewActions:t})=>{const[a,r]=o.useState("today"),[s,c]=o.useState(null),[l,n]=o.useState(!0),[i,x]=o.use
5State(null),g=o.useCallback(async m=>{n(!0),x(null);try{const h=await qt(m);c(h)}catch{x("Failed to load value summary. Please retry.")}finally{n(!1)}},[]);o.useEffect(()=>{g(a)},[a,g]);const N=!l&&!i&&s!==null&&s.actionCount===0&&s.engagement.opensDelta===0&&s.engagement.clicksDelta===0;return e.jsxs("div",{className:"flex flex-col h-full p-6 gap-5",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--color-text-primary)"},children:"Autonomy Value"}),e.jsx("p",{className:"text-sm mt-0.5",style:{color:"var(--color-text-secondary)"},children:"Measured and estimated impact from autonomous agent actions."})]}),e.jsx("div",{className:"flex items-center gap-1 rounded-lg border p-0.5",style:{borderColor:"var(--color-border-muted)",backgroundColor:"var(--color-bg-elevated)"},children:Ue.map(m=>e.jsx("button",{type:"button","aria-pressed":a===m.value,onClick:()=>r(m.value),className:"px-3 py-1.5 rounded-md text-sm font-medium transition-colors",style:{backgroundColor:a===m.value?"var(--color-brand-500)":"transparent",color:a===m.value?"#fff":"var(--color-text-secondary)"},"data-testid":`period-${m.value}`,children:m.label},m.value))})]}),l&&e.jsx("div",{className:"flex items-center justify-center py-16","data-testid":"loading-state",children:e.jsx("div",{className:"w-7 h-7 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},role:"status","aria-label":"Loading value summary"})}),!l&&i&&e.jsx("div",{className:"rounded-lg border px-4 py-3 text-sm",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},"data-testid":"error-state",role:"alert",children:i}),N&&e.jsx(ja,{period:a}),!l&&!i&&s!==null&&!N&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(oe,{icon:e.jsx(et,{className:"w-4 h-4"}),label:"Measured impact",value:de(s.measuredCents),sub:"Directly observed outcomes with real data",accent:"green","data-testid":"measured-card"}),e.jsx(oe,{icon:e.jsx(Oe,{className:"w-4 h-4"}),label:"Estimated impact",value:de(s.estimatedCents),sub:"Projections and avoided-spend calculations",accent:"blue","data-testid":"estimated-card"}),e.jsx(oe,{icon:e.jsx(tt,{className:"w-4 h-4"}),label:"Pending classification",value:String(s.pendingCount),sub:"Actions not yet classified (pre-v65 or in-flight)",accent:"amber","data-testid":"pending-card"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(fa,{opensDelta:s.engagement.opensDelta,clicksDelta:s.engagement.clicksDelta,onViewActions:t}),e.jsx(va,{byBasis:s.byBasis,onViewActions:t})]}),t&&e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>t(void 0),className:"text-xs underline underline-offset-2",style:{color:"var(--color-brand-500)"},"data-testid":"view-all-actions","aria-label":"View all autonomous actions on the timeline",children:"View all actions on the timeline â"})})]})]})};function Fe(t){const a=new URLSearchParams;return t!=null&&t.loopKey&&a.set("loopKey",t.loopKey),t!=null&&t.actionType&&a.set("actionType",t.actionType),t!=null&&t.impactClass&&a.set("impactClass",t.impactClass),t!=null&&t.period&&a.set("period",t.period),t!=null&&t.limit&&a.set("limit",String(t.limit)),t!=null&&t.offset&&a.set("offset",String(t.offset)),a}async function Le(t){const a=Fe(t).toString();return _(`/v1/agents/ledger${a?`?${a}`:""}`)}async function ka(t){const a=new URLSearchParams;t!=null&&t.loopKey&&a.set("loopKey",t.loopKey),t!=null&&t.actionType&&a.set("actionType",t.actionType),t!=null&&t.impactClass&&a.set("impactClass",t.impactClass),t!=null&&t.period&&a.set("period",t.period);const r=a.toString();return _(`/v1/agents/ledger/learning-proof${r?`?${r}`:""}`)}async function wa(t){const a=Fe(t).toString(),r=await Me(),s=await fetch(`/api/v1/agents/ledger/export${a?`?${a}`:""}`,{headers:r,credentials:"include"});if(!s.ok)throw new Error(`Export failed: ${s.statusText}`);const c=await s.blob(),l=URL.createObjectURL(c),n=document.createElement("a");n.href=l,n.download=`decision-ledger-${Date.now()}.csv`,n.click(),URL.revokeObjectURL(l)}function Ca(t){const a=new Date,r=a.toISOString();let s;switch(t){case"today":{const c=new Date(a);c.setHours(0,0,0,0),s=c.toISOString();break}case"7d":s=new Date(a.getTime()-10080*60*1e3).toISOString();break;case"30d":s=new Date(a.getTime()-720*60*60*1e3).toISOString();break;case"all":default:s=new Date(a.getTime()-366*24*60*60*1e3).toISOString();break}return{from:s,to:r}}async function ze(t,a){const{from:r,to:s}=Ca(a),c=new URLSearchParams({from:r,to:s}).toString(),l=await Me(),n=await fetch(`/api/v1/agents/ledger/attestation/${t}?${c}`,{headers:l,credentials:"include"});if(!n.ok){let p=n.statusText;
5try{const b=await n.text();b&&(p=b)}catch{}throw new Error(`Attestation ${t} export failed (${n.status}): ${p}`)}const i=n.headers.get("Content-Disposition")??n.headers.get("content-disposition"),x=i==null?void 0:i.match(/filename="?([^";]+)"?/i),g=t==="pack"?"json":"pdf",N=(x==null?void 0:x[1])??`attestation-${r}-${s}.${g}`,m=await n.blob(),h=URL.createObjectURL(m),y=document.createElement("a");y.href=h,y.download=N,y.click(),URL.revokeObjectURL(h)}async function Sa(t){await ze("pack",t)}async function Aa(t){await ze("pdf",t)}const _a=[{value:"today",label:"Today"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"},{value:"all",label:"All time"}],$e=25,Ta=[{id:"ledger",label:"Ledger"},{id:"learning",label:"Learning"}];function ee(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function La(t){return t.split("_").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}function Ve(t){return t.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}function Ee(t){if(t===null)return null;const a=t/100;return a<0?`-$${Math.abs(a).toFixed(2)}`:`$${a.toFixed(2)}`}function Pe(t){return t===null?"â":`${(t*100).toFixed(1)}%`}function $a(t,a){const r=s=>new Date(s).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return`${r(t)} â ${r(a)}`}const Ea={proposed:"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",pen
5ding_approval:"bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",approved:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300",executing:"bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",completed:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",rolled_back:"bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",rejected:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",blocked:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",failed:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",guardrail_paused:"bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300"},Pa={measured:"Measured",estimated:"Estimated",pending:"Pending"};function Da({outcome:t}){return t.performanceStatus==="measured"?e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",children:"Measured"}):t.performanceStatus==="unmeasurable"?e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",children:"Unmeasurable"}):e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",children:t.performanceStatus==="pending"?"Pending":"Unknown"})}function Ra({series:t}){const a=[...t.windows].sort((r,s)=>new Date(r.windowStart).getTime()-new Date(s.windowStart).getTime());return e.jsxs("div",{className:"rounded-lg border overflow-hidden",style:{borderColor:"var(--color-border-muted)",backgroundColor:"var(--color-bg-elevated)"},"data-testid":`learning-series-${t.loopKey}`,children:[e.jsx("div",{className:"px-4 py-3 border-b",style:{borderColor:"var(--color-border-muted)"},children:e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--color-text-primary)"},children:Ve(t.loopKey)})}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{style:{color:"var(--color-text-secondary)"},children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Window"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Total"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Delivery rate"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Reply rate"})]})}),e.jsx("tbody",{children:a.map((r,s)=>e.jsxs("tr",{className:"border-t",style:{borderColor:"var(--color-border-muted)"},"data-testid":`learning-window-${t.loopKey}-${s}`,children:[e.jsx("td",{className:"px-4 py-2",style:{color:"var(--color-text-primary)"},children:$a(r.windowStart,r.windowEnd)}),e.jsx("td",{className:"px-4 py-2 text-right tabular-nums",style:{color:"var(--color-text-primary)"},children:r.total}),e.jsx("td",{className:"px-4 py-2 text-right tabular-nums",style:{color:"var(--color-text-primary)"},children:Pe(r.deliveryRate)}),e.jsx("td",{className:"px-4 py-2 text-right tabular-nums",style:{color:"var(--color-text-primary)"},children:Pe(r.replyRate)})]},r.windowStart))})]})]})}function Oa({loading:t,error:a,data:r}){return t?e.jsx("div",{className:"flex items-center justify-center h-48","data-testid":"learning-loading-state",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},role:"status","aria-label":"Loading learning proof"})}):a?e.jsx("div",{className:"flex items-center justify-center h-32 text-sm text-red-500",role:"alert","data-testid":"learning-error-state",children:a}):!r||!r.enoughHistory||r.series.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3 text-center","data-testid":"learning-empty-state",children:[e.jsx(ne,{className:"w-10 h-10",style:{color:"var(--color-text-secondary)",opacity:.4},"aria-hidden":!0}),e.jsx("p",{className:"text-sm font-medium max-w-sm",style:{color:"var(--color-text-secondary)"},children:"Not enough measured history yet â this fills in as your autonomous actions accumulate first-party outcomes."})]}):e.jsx("div",{className:"flex flex-col gap-4 mt-2","data-testid":"learning-series-list",children:r.series.map(s=>e.jsx(Ra,{series:s},s.loopKey))})}function Z({title:t,children:a}){return e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide mb-1.5",style:{color:"var(--color-text-secondary)"},children:t}),a]})}function Ba({entry:t}){const a=t.inputs?Object.entries(t.inputs):[],r=Ee(t.outcome.actualImpactCents),s=Ee(t.outcome.estimatedImpactCents),l=["approvalBinding","executionState","executionResult","reconciliationRequired"].filter(n=>{var i;return((i=t.inputs)==null?void 0:i[n])!=null});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 px-4 py-4 border-t text-sm",style:{borderColor:"var(--color-border-muted)",backgroundColor:"var(--color-bg-base)"},"data-testid":`row-detail-${t.id}`,children:[e.jsx(Z,{title:"Why â reasoning inputs",children:a.length===0?e.jsx("p",{style:{color:"var(--color-text-secondary)"},children:"No structured inputs recorded."}):e.jsx("dl",{className:"flex flex-col gap-1",children:a.map(([n,i])=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{style:{color:"var(--color-text-secondary)"},children:n}),e.jsx("dd",{className:"text-right break-all",style:{color:"var(--color-text-primary)"},children:typeof i=="object"?JSON.stringify(i):String(i)})]},n))})}),e.jsxs(Z,{title:"Recorded action provenance",children:[e.jsxs("p",{children:["Action: ",t.id]}),e.jsxs("p",{children:["Target: ",t.targetEntityType??"Unknown"," / ",t.targetEntityId??"Unknown"]}),e.jsxs("p",{children:["Executed: ",t.executedAt?ee(t.executedAt):"Not recorded"]}),l.length===0?e.jsx("p",{children:"No revision binding or execution receipt recorded."}):e.jsx("dl",{children:l.map(n=>{var i;return e.jsxs("div",{children:[e.jsx("dt",{children:n}),e.jsx("dd",{className:"break-all",children:JSON.stringify((i=t.inputs)==null?void 0:i[n])})]},n)})}),e.jsx("p",{className:"text-xs",children:"Recorded acceptance is not delivery. Integrity is not proof of correct approval, source truth, or causal uplift."})]}),e.jsxs(Z,{title:"Governance",children:[e.jsxs("div",{className:"flex flex-col gap-1 mb-2",children:[t.governance.approvedBy&&e.jsxs("p",{style:{color:"var(--color-text-primary)"},children:["Approved by ",t.governance.approvedBy,t.governance.approvedAt?` on ${ee(t.governance.approvedAt)}`:""]}),t.governance.rejectedBy&&e.jsxs("p",{style:{color:"var(--color-text-primary)"},children:["Rejected by ",t.governance.rejectedBy,t.governance.rejectionReason?` â ${t.governance.rejectionReason}`:""]}),t.governance.riskLevel&&e.jsxs("p",{style:{color:"var(--color-text-secondary)"},children:["Risk: ",t.governance.riskLevel,t.governance.riskScore!==null?` (score ${t.governance.riskScore})`:""]})]}),t.governance.events.length===0?e.jsx("p",{style:{color:"var(--color-text-secondary)"},children:"No governance events recorded."}):e.jsx("ul",{className:"flex flex-col gap-1",children:t.governance.events.map((n,i)=>e.jsxs("li",{style:{color:"var(--color-text-secondary)"},children:[e.jsx("span",{style:{color:"var(--color-text-primary)"},children:n.eventType})," â ",ee(n.timestamp)," â ",n.actorType,n.actorId?`: ${n.actorId}`:"",e.jsxs("p",{children:[n.previousStatus??"Unknown"," â ",n.newStatus??"Unknown"]}),n.metadata&&e.jsx("pre",{className:"whitespace-pre-wrap break-all text-xs",children:JSON.stringify(n.metadata,null,2)})]},i))})]}),e.jsx(Z,{title:"Outcome",children:e.jsxs("dl",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{style:{color:"var(--color-text-secondary)"},children:"Impact class"}),e.jsx("dd",{style:{color:"var(--color-text-primary)"},children:t.outcome.impactClass?Pa[t.outcome.impactClass]??t.outcome.impactClass:"Unclassified"})]}),s&&e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{style:{color:"var(--color-text-secondary)"},children:"Estimated impact"}),e.jsx("dd",{style:{color:"var(--color-text-primary)"},children:s})]}),r&&e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("dt",{style:{color:"var(--color-text-secondary)"},children:"Actual impact"}),e.jsx("dd",{style:{color:"var(--color-text-primary)"},children:r})]}),!r&&e.jsx("p",{className:"text-xs mt-1",style:{color:"var(--color-text-secondary)"},children:"No measured actual impact yet."})]})})]})}const Ia=({initialLoopKey:t})=>{const[a,r]=o.useState("7d"),[s,c]=o.useState(t??""),[l,n]=o.useState(""),[i,x]=o.use
5State(""),[g,N]=o.useState([]),[m,h]=o.useState(0),[y,p]=o.useState(0),[b,f]=o.useState(!0),[j,k]=o.useState(!1),[C,A]=o.useState(null),[$,E]=o.useState(!1),[D,T]=o.useState(null),[L,R]=o.useState(!1),[M,G]=o.useState(!1),[U,O]=o.useState(null),[F,z]=o.useState(!1),[P,ae]=o.useState("ledger"),[V,re]=o.useState(null),[W,K]=o.useState(!1),[Y,d]=o.useState(null),v=o.useCallback(()=>({period:a,loopKey:s||void 0,actionType:l||void 0,impactClass:i||void 0,limit:$e,offset:0}),[a,s,l,i]);o.useEffect(()=>{let u=!1;return f(!0),p(0),A(null),Le(v()).then(w=>{u||(N(w.items),h(w.total),f(!1))}).catch(w=>{u||(A(w instanceof Error?w.message:"Failed to load decision ledger"),f(!1))}),()=>{u=!0}},[v]);const S=o.useCallback(async()=>{const u=y+$e;k(!0);try{const w=await Le({...v(),offset:u});N(Ke=>[...Ke,...w.items]),p(u)}catch(w){A(w instanceof Error?w.message:"Failed to load more")}finally{k(!1)}},[y,v]),q=o.useCallback(async()=>{E(!0);try{await wa(v())}catch(u){A(u instanceof Error?u.message:"Export failed")}finally{E(!1)}},[v]),J=o.useCallback(async()=>{R(!0),O(null),z(!1);try{await Sa(a),O("Attestation JSON downloaded.")}catch(u){O(u instanceof Error?u.message:"Attestation JSON export failed"),z(!0)}finally{R(!1)}},[a]),H=o.useCallback(async()=>{G(!0),O(null),z(!1);try{await Aa(a),O("Attestation PDF downloaded.")}catch(u){O(u instanceof Error?u.message:"Attestation PDF export failed"),z(!0)}finally{G(!1)}},[a]);o.useEffect(()=>{if(P!=="learning")return;let u=!1;return K(!0),d(null),ka(v()).then(w=>{u||(re(w),K(!1))}).catch(w=>{u||(d(w instanceof Error?w.message:"Failed to load learning proof"),K(!1))}),()=>{u=!0}},[P,v]);const B="rounded-md border px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-offset-0",I={backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)",color:"var(--color-text-primary)"};return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3 px-4 py-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--color-text-primary)"},children:"Decision Ledger"}),e.jsx("p",{className:"text-sm mt-0.5",style:{color:"var(--color-text-secondary)"},children:"Recorded decisions, reasoning, governance evidence, and outcomes where available."})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap justify-end",children:[e.jsxs("button",{type:"button",onClick:()=>void q(),disabled:$,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors disabled:opacity-50",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},"data-testid":"export-button",children:[e.jsx(xe,{className:"w-3.5 h-3.5","aria-hidden":!0}),$?"Exportingâ¦":"Export CSV"]}),e.jsxs("button",{type:"button",onClick:()=>void J(),disabled:L,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors disabled:opacity-50",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},"data-testid":"attestation-pack-button",children:[e.jsx(ne,{className:"w-3.5 h-3.5","aria-hidden":!0}),L?"Preparingâ¦":`Attestation JSON (verifiable)${a==="all"?" (last 12 months)":""}`]}),e.jsxs("button",{type:"button",onClick:()=>void H(),disabled:M,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors disabled:opacity-50",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},"data-testid":"attestation-pdf-button",children:[e.jsx(xe,{className:"w-3.5 h-3.5","aria-hidden":!0}),M?"Preparingâ¦":`Attestation PDF${a==="all"?" (last 12 months)":""}`]})]}),e.jsx("p",{className:"text-xs text-right max-w-xs",style:{color:"var(--color-text-secondary)"},children:"Tamper-evident, not a full audit or proof of outcomes. Attestation exports cover recorded actions in the selected period, ignoring row filters, plus declared linked governance events. Limits: 20,000 actions / 100,000 events; oversized or incomplete scans are refused. Verify offline with an independently obtained verifier and pinned key."}),e.jsx("a",{href:"/api/v1/agents/attestation/verifier",download:"verify.cjs",className:"text-xs underline",style:{color:"var(--color-text-secondary)"},children:"Download independent offline verifier"}),U&&e.jsx("p",{role:F?"alert":"status",className:"text-xs text-right max-w-xs",style:{color:F?"#ef4444":"var(--color-text-secondary)"},"data-testid":"attestation-result",children:U})]})]}),e.jsx("div",{className:"flex items-center gap-1 px-4 border-b overflow-x-auto",style:{borderColor:"var(--color-border-muted)"},role:"tablist","aria-label":"Decision ledger views",children:Ta.map(u=>{const w=P===u.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":w,"aria-controls":`ledger-tabpanel-${u.id}`,onClick:()=>ae(u.id),className:"relative px-3 py-2.5 text-sm font-medium transition-colors",style:{color:w?"var(--color-brand-500)":"var(--color-text-secondary)"},"data-testid":`view-tab-${u.id}`,children:[u.label,w&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5",style:{backgroundColor:"var(--color-brand-500)"},"aria-hidden":!0})]},u.id)})}),P==="ledger"&&e.jsxs("div",{id:"ledger-tabpanel-ledger",role:"tabpanel","aria-label":"Ledger",className:"flex flex-col flex-1 min-h-0",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3 px-4 py-3 border-y",style:{borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Period"}),e.jsx("select",{value:a,onChange:u=>r(u.target.value),className:B,style:I,"data-testid":"period-select",children:_a.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Loop"}),e.jsx("input",{type:"text",value:s,onChange:u=>c(u.target.value),placeholder:"e.g. budget_guard",className:B,style:I,"data-testid":"loopkey-input"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Action type"}
5),e.jsx("input",{type:"text",value:l,onChange:u=>n(u.target.value),placeholder:"e.g. budget_guard_pause",className:B,style:I,"data-testid":"actiontype-input"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium",style:{color:"var(--color-text-secondary)"},children:"Impact"}),e.jsxs("select",{value:i,onChange:u=>x(u.target.value),className:B,style:I,"data-testid":"impactclass-select",children:[e.jsx("option",{value:"",children:"All"}),e.jsx("option",{value:"measured",children:"Measured"}),e.jsx("option",{value:"estimated",children:"Estimated"}),e.jsx("option",{value:"pending",children:"Pending"})]})]})]}),!b&&!C&&e.jsxs("div",{className:"px-4 py-2 text-xs",style:{color:"var(--color-text-secondary)"},children:["Showing ",g.length," of ",m]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:[b?e.jsx("div",{className:"flex items-center justify-center h-48","data-testid":"loading-state",children:e.jsx("div",{className:"w-6 h-6 rounded-full border-2 animate-spin",style:{borderColor:"var(--color-brand-500)",borderTopColor:"transparent"},role:"status","aria-label":"Loading decision ledger"})}):C?e.jsx("div",{className:"flex items-center justify-center h-32 text-sm text-red-500",role:"alert","data-testid":"error-state",children:C}):g.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3 text-center","data-testid":"empty-state",children:[e.jsx(ne,{className:"w-10 h-10",style:{color:"var(--color-text-secondary)",opacity:.4},"aria-hidden":!0}),e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--color-text-secondary)"},children:"No autonomous decisions recorded for this filter."})]}):e.jsx("div",{className:"flex flex-col gap-2 mt-2","data-testid":"ledger-table",children:g.map(u=>{const w=D===u.id;return e.jsxs("div",{className:"rounded-lg border",style:{borderColor:"var(--color-border-muted)",backgroundColor:"var(--color-bg-elevated)"},"data-testid":`ledger-row-${u.id}`,children:[e.jsxs("button",{type:"button",onClick:()=>T(w?null:u.id),className:"w-full flex items-center gap-3 px-4 py-3 text-left","aria-expanded":w,"data-testid":`ledger-row-toggle-${u.id}`,children:[w?e.jsx(Re,{className:"w-4 h-4 shrink-0",style:{color:"var(--color-text-secondary)"},"aria-hidden":!0}):e.jsx(rt,{className:"w-4 h-4 shrink-0",style:{color:"var(--color-text-secondary)"},"aria-hidden":!0}),e.jsxs("div",{className:"flex flex-col gap-1 flex-1 min-w-0",children:[e.jsx("time",{className:"text-xs tabular-nums",style:{color:"var(--color-text-secondary)"},dateTime:u.createdAt,children:ee(u.createdAt)}),e.jsx("p",{className:"text-sm truncate",style:{color:"var(--color-text-primary)"},children:u.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 flex-wrap justify-end",children:[e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",children:La(u.agentType)}),e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300",children:Ve(u.actionType)}),e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Ea[u.status]??"bg-gray-100 text-gray-700"}`,children:u.status}),e.jsx(Da,{outcome:u.outcome})]})]}),w&&e.jsx(Ba,{entry:u})]},u.id)})}),!b&&!C&&g.length<m&&e.jsx("div",{className:"flex justify-center pt-4",children:e.jsx("button",{type:"button",onClick:()=>void S(),disabled:j,className:"px-4 py-2 rounded-lg text-sm font-medium border transition-colors disabled:opacity-50",style:{borderColor:"var(--color-border-muted)",color:"var(--color-text-secondary)"},"data-testid":"load-more-button",children:j?"Loadingâ¦":"Load more"})})]})]}),P==="learning"&&e.jsx("div",{id:"ledger-tabpanel-learning",role:"tabpanel","aria-label":"Learning",className:"flex-1 overflow-y-auto px-4 pb-4",children:e.jsx(Oa,{loading:W,error:Y,data:V})})]})},De=[{id:"control",label:"Pause & limits",group:"Controls"},{id:"timeline",label:"Action timeline",group:"Activity & evidence"},{id:"anomalies",label:"Alerts to review",group:"Activity & evidence"},{id:"optimization",label:"Campaign changes",group:"Activity & evidence"},{id:"publishing-budget",label:"Publishing & budget",group:"Activity & evidence"},{id:"ab-promotions",label:"A/B winner activity",group:"Activity & evidence"},{id:"value",label:"Recorded impact",group:"Activity & evidence"},{id:"monitoring",label:"Monitoring logs",group:"Advanced"},{id:"ledger",label:"Decision audit trail",group:"Advanced"},{id:"settings",label:"Permission settings",group:"Advanced"}],Q=({label:t,value:a,accent:r="default"})=>{const s=r==="amber"&&Number(a)>0?"text-amber-500":r==="red"&&Number(a)>0?"text-red-500":void 0;return e.jsxs("div",{className:"rounded-lg border px-4 py-3",style:{backgroundColor:"var(--color-bg-elevated)",borderColor:"var(--color-border-muted)"},children:[e.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--color-text-secondary)"},children:t}),e.jsx("p",{className:`text-2xl font-semibold tabular-nums ${s??""}`,style:s?void 0:{color:"var(--color-text-primary)"},children:a})]})},ar=()=>{var f;const[t,a]=st(),r=((f=De.find(j=>j.id===t.get("tab")))==null?void 0:f.id)??"control",s=o.useCallback(j=>{a(k=>{const C=new URLSearchParams(k);return C.set("tab",j),C})},[a]),[c,l]=o.useState(void 0),n=o.useCallback(j=>{l(j),s("timeline")},[s]),i=Ie(),{monitoringLogs:x,anomalyAlerts:g,optimizationActivity:N,stats:m,autonomySummary:h,loading:y,errors:p,refresh:b}=ht();return e.jsxs("div",{className:"flex flex-col h-full min-h-0",style:{color:"var(--color-text-primary)"},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 sm:px-6 py-5 border-b shrink-0",style:{borderColor:"var(--color-border-muted)"},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ot,{className:"w-5 h-5",style:{color:"var(--color-brand-500)"},"aria-hidden":!0}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold",style:{fontSize:"var(--text-2xl)",fontWeight:"var(--font-semibold)"},children:"Automation controls"}),e.jsx("p",{className:"text-sm mt-0.5",style:{color:"var(--color-text-secondary)"}
5,children:"Workspace-wide: these controls and activity cover all businesses in your account, not just the selected business."}),e.jsx("p",{className:"text-sm mt-1",style:{color:"var(--color-text-secondary)"},children:"Review enabled or paused automations and their prerequisites in Pause & limits. Monitoring depends on enabled schedules and available data."})]})]}),e.jsxs("button",{type:"button",disabled:y,onClick:b,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors border",style:{color:"var(--color-text-secondary)",borderColor:"var(--color-border-muted)"},"aria-label":"Refresh data",children:[e.jsx(lt,{className:`w-3.5 h-3.5 ${y?"animate-spin":""}`,"aria-hidden":!0}),"Refresh"]})]}),p.stats&&e.jsxs("p",{role:"alert",className:"px-6 py-2",children:["Activity totals unavailable: ",p.stats,". Use Refresh to retry; pause and limits remain available."]}),m&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 px-6 py-4 border-b",style:{borderColor:"var(--color-border-muted)"},children:[e.jsx(Q,{label:"Actions Today",value:m.totalToday}),e.jsx(Q,{label:"Pending Approval",value:m.pendingApprovalCount,accent:"amber"}),e.jsx(Q,{label:"Auto-Approved",value:m.autoApprovedToday}),e.jsx(Q,{label:"Failed",value:m.failedToday,accent:"red"})]}),e.jsx("nav",{className:"px-4 sm:px-6 py-3 border-b shrink-0 flex flex-wrap gap-x-6 gap-y-3",style:{borderColor:"var(--color-border-muted)"},"aria-label":"Automation sections",children:["Controls","Activity & evidence","Advanced"].map(j=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold mb-1",style:{color:"var(--color-text-secondary)"},children:j}),e.jsx("div",{className:"flex flex-wrap gap-1",children:De.filter(k=>k.group===j).map(k=>e.jsx("button",{type:"button","aria-current":r===k.id?"page":void 0,"aria-controls":`tabpanel-${k.id}`,onClick:()=>s(k.id),className:"rounded-lg px-3 py-2 text-sm font-medium min-h-11 border",style:{borderColor:r===k.id?"var(--color-brand-500)":"transparent",color:r===k.id?"var(--color-brand-500)":"var(--color-text-secondary)"},children:k.label},k.id))})]},j))}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[Object.entries(p).filter(([j])=>j!=="stats").map(([j,k])=>e.jsxs("p",{role:"alert",className:"mx-4 mt-3 rounded-lg border px-4 py-3 text-sm",children:[j==="settings"?"Permission settings":j==="optimization"?"Campaign activity":j==="anomalies"?"Alerts":"Monitoring logs"," unavailable: ",k,". Use Refresh to retry."]},j)),r==="control"&&e.jsx("div",{id:"tabpanel-control",role:"tabpanel","aria-label":"Autonomy Control",className:"h-full",children:e.jsx(ya,{})}),r==="monitoring"&&!p.monitoring&&e.jsx("div",{id:"tabpanel-monitoring",role:"tabpanel","aria-label":"Monitoring Logs",className:"h-full",children:e.jsx(kt,{items:x,loading:y})}),r==="anomalies"&&!p.anomalies&&e.jsx("div",{id:"tabpanel-anomalies",role:"tabpanel","aria-label":"Anomaly Alerts",className:"h-full",children:e.jsx($t,{items:g,loading:y})}),r==="optimization"&&!p.optimization&&!p.settings&&e.jsx("div",{id:"tabpanel-optimization",role:"tabpanel","aria-label":"Optimization Activity",className:"h-full",children:e.jsx(Mt,{items:N,autonomySummary:h,loading:y})}),r==="publishing-budget"&&!p.optimization&&e.jsx("div",{id:"tabpanel-publishing-budget",role:"tabpanel","aria-label":"Publishing & Budget",className:"h-full",children:e.jsx(Ft,{items:N,loading:y})}),r==="timeline"&&e.jsx("div",{id:"tabpanel-timeline",role:"tabpanel","aria-label":"Action Timeline",className:"h-full",children:e.jsx(ta,{orgId:i,initialActionType:c})}),r==="ab-promotions"&&e.jsx("div",{id:"tabpanel-ab-promotions",role:"tabpanel","aria-label":"A/B Auto-Promote",className:"h-full",children:e.jsx(da,{})}),r==="value"&&e.jsx("div",{id:"tabpanel-value",role:"tabpanel","aria-label":"Autonomy Value",className:"h-full",children:e.jsx(Na,{onViewActions:n})}),r==="ledger"&&e.jsx("div",{id:"tabpanel-ledger",role:"tabpanel","aria-label":"Decision Ledger",className:"h-full",children:e.jsx(Ia,{})}),r==="settings"&&!p.settings&&e.jsx("div",{id:"tabpanel-settings",role:"tabpanel","aria-label":"Autonomy Settings",className:"h-full",children:e.jsx(oa,{guardrails:h,loading:y,onRefresh:b})})]})]})};export{ar as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.