1import{y as qe,z as ne,D as re,E as ie,e as R,r as $,dm as U,f as de,j as e,C as Z,a as G,b as J,c as ce,B as _,dA as se,bi as te,ab as W,ac as K,ad as Q,ae as Y,af as A,ag as ts,ah as as,a0 as ae,ai as ns,d as je,N as B,$ as rs,K as ee,t as F,k as D,dk as is,S as ue,au as ve,a5 as ls,P as cs,dB as ds,dC as os,dD as ms,aJ as Ae,ak as He,at as Ue,ar as us,dE as xs,aS as hs,aD as ps,bj as gs,M as fs}from"./index-DHwBXtP2.js";import{u as js}from"./auth-context-CZDSnG7n.js";import{l as vs}from"./workspace-client-BDKm4vHd.js";import{T as bs,a as ys,b as Ns,c as ws}from"./tooltip-h8hPhwqz.js";import{f as _e,C as _s}from"./calendar-Cu-Vjt7X.js";import{T as be}from"./trending-up-BjyiYEVM.js";import{C as Cs}from"./calendar-DrA7SuiL.js";import{R as Pe,p as Me,X as Fe,Y as De,T as Ee,q as As}from"./generateCategoricalChart-CoD3ZMQ2.js";import{L as Ie}from"./LineChart-YrXPbmt1.js";import{L as Te}from"./Line-BMxNBhzI.js";import{B as $s}from"./brain-C_Lx5IOV.js";import{V as Ss}from"./video-Dk6kj1q-.js";import{I as ks}from"./image-OdvWkqq2.js";import{T as Be}from"./trending-down-CTHoqd69.js";import{C as Ps}from"./chevron-left-B7lTa6YE.js";import{A as Ms}from"./arrow-right-Ck7Z4gCN.js";import{A as Fs}from"./analytics-subnav-DU9k3OM0.js";import{D as Ds,a as Es,b as Is,e as Ce,d as ze}from"./dropdown-menu-HbwjwNig.js";import{A as We}from"./activity-Lkt8o0Ed.js";import{C as ye}from"./circle-pause-ChKrisbe.js";import{A as Ke}from"./archive-Cetlojob.js";import{U as Ts}from"./undo-2-AHg6Dlwc.js";import{E as zs}from"./ellipsis-BGX9xNbu.js";import{C as Le}from"./clock-Rzb6aUHV.js";import"./en-US-D5ynhWGh.js";import"./index-DqP424Co.js";import"./circle-CRPl8R1p.js";const Ls=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}],["path",{d:"M17 14V2",key:"8ymqnk"}]],Rs=qe("thumbs-down",Ls);const Os=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],Vs=qe("thumbs-up",Os),qs=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_matrix-watchtower_functions_ts--getMatrixWatchtower_createServerFn_handler")),Hs=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_matrix-watchtower_functions_ts--listWatchtowerWinnerInsights_createServerFn_handler")),Us=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_matrix-watchtower_functions_ts--explainWatchtowerWinners_createServerFn_handler")),Bs=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_delivery-shifts_functions_ts--getDeliveryShifts_createServerFn_handler")),Ws=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_delivery-shifts_functions_ts--analyzeDeliveryShifts_createServerFn_handler")),Re=["hsl(217 91% 60%)","hsl(142 71% 45%)","hsl(38 92% 50%)","hsl(0 84% 60%)","hsl(280 65% 60%)","hsl(190 75% 45%)","hsl(330 75% 55%)","hsl(60 80% 45%)"];function Ks(s){return Re[s%Re.length]}function ge(s,a){return s&&s.trim().length>0?s:`Ad ${a.slice(-6)}`}function fe(s){const a=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),l=String(s.getDate()).padStart(2,"0");return`${a}-${r}-${l}`}function Qs(s,a){const r=new Date,l=new Date(r.getFullYear(),r.getMonth(),r.getDate());let j=l,c=l;switch(s){case"today":j=l,c=l;break;case"yesterday":{const u=new Date(l);u.setDate(l.getDate()-1),j=u,c=l;break}case"last_7":{const u=new Date(l);u.setDate(l.getDate()-6),j=u,c=l;break}case"last_14":{const u=new Date(l);u.setDate(l.getDate()-13),j=u,c=l;break}case"last_30":{const u=new Date(l);u.setDate(l.getDate()-29),j=u,c=l;break}case"this_month":{j=new Date(l.getFullYear(),l.getMonth(),1),c=l;break}case"custom":{j=a.from??l,c=a.to??a.from??l;break}}return{days:Math.max(1,Math.round((c.getTime()-j.getTime())/864e5)+1),startDate:fe(j),endDate:fe(c),rangeLabel:`${fe(j)} â ${fe(c)}`}}function Ys({status:s}){const r={rising:{label:"Rising",cls:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30",icon:be}
1,new:{label:"New",cls:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30",icon:ue},falling:{label:"Falling",cls:"bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/30",icon:Be},steady:{label:"Steady",cls:"bg-muted text-muted-foreground border-border",icon:is}}[s],l=r.icon;return e.jsxs(D,{variant:"outline",className:r.cls,children:[e.jsx(l,{className:"mr-1 h-3 w-3"}),r.label]})}function Oe({ad:s}){return s.thumbnail_url?e.jsx("img",{src:s.thumbnail_url,alt:s.name??"Ad creative",className:"h-12 w-12 rounded-md object-cover border border-border bg-muted",loading:"lazy",onError:a=>{a.currentTarget.style.display="none"}}):e.jsx("div",{className:"h-12 w-12 rounded-md border border-border bg-muted flex items-center justify-center text-muted-foreground",children:s.creative_kind==="video"?e.jsx(Ss,{className:"h-4 w-4"}):e.jsx(ks,{className:"h-4 w-4"})})}function Xs({workspaceId:s}){const a=R(Bs),r=R(Ws),[l,j]=$.useState("last_14"),[c,h]=$.useState({}),{days:u,startDate:f,endDate:C}=$.useMemo(()=>Qs(l,c),[l,c]),[S,N]=U(`delivery-shifts:campaign:${s??"anon"}`,null),[b,p]=U(`delivery-shifts:compare:${s??"anon"}`,null),[d,k]=U(`delivery-shifts:open:${s??"anon"}`,!0),x=de({queryKey:["delivery-shifts",s,f,C,S],queryFn:()=>a({data:{workspaceId:s,days:u,startDate:f,endDate:C,campaignId:S??void 0}}),enabled:!!s&&!!f&&!!C,staleTime:5*6e4}),v=de({queryKey:["delivery-shifts",s,f,C,"compare",b],queryFn:()=>a({data:{workspaceId:s,days:u,startDate:f,endDate:C,campaignId:b}}),enabled:!!s&&!!b&&!!f&&!!C,staleTime:5*6e4});if(!s)return null;const g=x.data,w=g?.campaigns??[],i=S??g?.campaign?.campaign_id??"";return e.jsxs(Z,{children:[e.jsx(G,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(be,{className:"h-4 w-4"}),"Delivery Shifts"]}),e.jsx(ce,{children:"Where Meta is spending its delivery budget across every ad in a campaign, day by day. Catches which creative the algorithm is currently favoring before the verdict job runs. Pick a second campaign to compare side-by-side."})]}),e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7 shrink-0","aria-label":d?"Collapse":"Expand",onClick:()=>k(t=>!t),children:d?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(W,{value:i,onValueChange:t=>N(t),disabled:!g||w.length===0,children:[e.jsx(K,{className:"w-[260px]",children:e.jsx(Q,{placeholder:"Pick a campaign"})}),e.jsx(Y,{children:w.map(t=>e.jsxs(A,{value:t.campaign_id,children:[t.campaign_name??`Campaign ${t.campaign_id.slice(-6)}`," ·"," ",t.ad_count," ads",t.total_impressions===0?" · idle":""]},t.campaign_id))})]}),e.jsxs(W,{value:b??"__none__",onValueChange:t=>p(t==="__none__"?null:t),disabled:!g||w.length<2,children:[e.jsx(K,{className:"w-[240px]",children:e.jsx(Q,{placeholder:"Compare withâ¦"})}),e.jsxs(Y,{children:[e.jsx(A,{value:"__none__",children:"No comparison"}),w.filter(t=>t.campaign_id!==i).map(t=>e.jsxs(A,{value:t.campaign_id,children:[t.campaign_name??`Campaign ${t.campaign_id.slice(-6)}`," ·"," ",t.ad_count," ads",t.total_impressions===0?" · idle":""]},t.campaign_id))]})]}),e.jsxs(W,{value:l,onValueChange:t=>j(t),children:[e.jsx(K,{className:"w-[170px]",children:e.jsx(Q,{})}),e.jsxs(Y,{children:[e.jsx(A,{value:"today",children:"Today"}),e.jsx(A,{value:"yesterday",children:"Today & yesterday"}),e.jsx(A,{value:"last_7",children:"Last 7 days"}),e.jsx(A,{value:"last_14",children:"Last 14 days"}),e.jsx(A,{value:"last_30",children:"Last 30 days"}),e.jsx(A,{value:"this_month",children:"This month"}),e.jsx(A,{value:"custom",children:"Custom rangeâ¦"})]})]}),l==="custom"?e.jsxs(ts,{children:[e.jsx(as,{asChild:!0,children:e.jsxs(_,{variant:"outline",size:"sm",className:ae("h-9 justify-start gap-2 font-normal",!c.from&&"text-muted-foreground"),children:[e.jsx(Cs,{className:"h-4 w-4"}),c.from&&c.to?`${_e(c.from,"MMM d")} â ${_e(c.to,"MMM d")}`:c.from?`${_e(c.from,"MMM d")} â â¦`:"Pick dates"]})}),e.jsx(ns,{className:"w-auto p-0",align:"end",children:e.jsx(_s,{mode:"range",selected:c,onSelect:t=>h({from:t?.from,to:t?.to}),numberOfMonths:2,initialFocus:!0,className:ae("p-3 pointer-events-auto"),disabled:t=>t>new Date})})]}):null]})]})}),d?e.jsx(je,{children:x.isLoading?e.jsx(B,{className:"h-64 w-full"}):!g||w.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No campaigns with delivery data in the selected window."}):e.jsxs("div",{className:b?"grid gap-4 lg:grid-cols-2":"space-y-4",children:[e.jsx(Ve,{workspaceId:s,data:g,days:u,startDate:f,endDate:C,isFetching:x.isFetching,forensicsFn:r,compareCampaignId:b}),b?v.isLoading||!v.data?e.jsx(B,{className:"h-64 w-full"}):e.jsxs("div",{className:"relative",children:[e.jsx(_,{size:"icon",variant:"ghost",className:"absolute right-0 top-0 z-10 h-7 w-7",onClick:()=>
1p(null),"aria-label":"Remove comparison",children:e.jsx(rs,{className:"h-4 w-4"})}),e.jsx(Ve,{workspaceId:s,data:v.data,days:u,startDate:f,endDate:C,isFetching:v.isFetching,forensicsFn:r,compareCampaignId:i,isComparison:!0})]}):null]})}):null]})}function Ve({workspaceId:s,data:a,days:r,startDate:l,endDate:j,isFetching:c,forensicsFn:h,compareCampaignId:u,isComparison:f=!1}){const C=$.useMemo(()=>{const n=new Map;return(a.ads??[]).forEach((I,m)=>n.set(I.ad_id,Ks(m))),n},[a.ads]),S=$.useMemo(()=>(a.series??[]).map(n=>{const I={date:n.date.slice(5)};for(const m of a.ads??[])I[m.ad_id]=Number(((n.shares[m.ad_id]??0)*100).toFixed(1));return I}),[a.series,a.ads]),N=$.useMemo(()=>(a.series??[]).map(n=>{const I=Object.values(n.spend??{}).reduce((z,X)=>z+X,0),m=Object.values(n.conversions??{}).reduce((z,X)=>z+X,0),M=m>0?I/m:null;return{date:n.date.slice(5),cpl:M==null?null:Number(M.toFixed(2)),spend:Number(I.toFixed(2)),conversions:m}}),[a.series]),b=N.some(n=>n.cpl!=null),[p,d]=$.useState("share"),k=`delivery-forensics:${s}:${a.campaign?.campaign_id??"none"}:${u??"none"}`,[x,v]=U(k,[]),g=Array.isArray(x)?x:[],w=3,[i,t]=$.useState(0),y=Math.max(1,Math.ceil(g.length/w)),E=g.slice(i*w,i*w+w),V=g[0]??null,q=ee({mutationFn:()=>h({data:{workspaceId:s,campaignId:a.campaign.campaign_id,compareCampaignId:u??null,days:r,startDate:l,endDate:j}}),onSuccess:n=>{v([{...n,generated_at:new Date().toISOString()},...g].slice(0,30)),t(0),n.patterns_recorded>0?F.success(`Forensics saved · ${n.patterns_recorded} pattern${n.patterns_recorded===1?"":"s"} added to your brain`):F.success("Forensics generated")},onError:n=>F.error(n.message)});return a.campaign?a.ads.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No ad delivery in this campaign for the selected window."}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f?e.jsx(D,{variant:"outline",className:"text-xs",children:"Comparison"}):null,e.jsx("span",{className:"text-sm font-medium truncate",children:a.campaign.campaign_name??a.campaign.campaign_id}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",a.campaign.adset_count," adset",a.campaign.adset_count===1?"":"s"," · ",a.ads.length," ads"]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(W,{value:p,onValueChange:n=>d(n),children:[e.jsx(K,{className:"w-[260px]",children:e.jsx(Q,{})}),e.jsxs(Y,{children:[e.jsx(A,{value:"share",children:"Delivery share by ad"}),e.jsxs(A,{value:"cpl",disabled:!b,children:["Cost per lead",b?"":" (no conversions)"]})]})]})})]}),p==="share"?e.jsx("div",{className:"h-56 w-full",children:e.jsx(Pe,{children:e.jsxs(Ie,{data:S,margin:{top:8,right:16,left:0,bottom:0},children:[e.jsx(Me,{strokeDasharray:"3 3",className:"stroke-border"}),e.jsx(Fe,{dataKey:"date",tick:{fontSize:11},stroke:"currentColor",className:"text-muted-foreground"}),e.jsx(De,{tick:{fontSize:11},stroke:"currentColor",className:"text-muted-foreground",tickFormatter:n=>`${n}%`,domain:[0,100]}),e.jsx(Ee,{contentStyle:{background:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},formatter:(n,I)=>{const m=a.ads.find(M=>M.ad_id===I);return[`${n}%`,ge(m?.name??null,I)]}}),e.jsx(As,{wrapperStyle:{fontSize:11},formatter:n=>{const I=a.ads.find(m=>m.ad_id===n);return ge(I?.name??null,n)}}),a.ads.map(n=>e.jsx(Te,{type:"monotone",dataKey:n.ad_id,stroke:C.get(n.ad_id),strokeWidth:2,dot:!1,activeDot:{r:4}},n.ad_id))]})})}):e.jsx("div",{className:"h-56 w-full",children:e.jsx(Pe,{children:e.jsxs(Ie,{data:N,margin:{top:8,right:16,left:0,bottom:0},children:[e.jsx(Me,{strokeDasharray:"3 3",className:"stroke-border"}),e.jsx(Fe,{dataKey:"date",tick:{fontSize:11},stroke:"currentColor",className:"text-muted-foreground"}),e.jsx(De,{tick:{fontSize:11},stroke:"currentColor",className:"text-muted-foreground",tickFormatter:n=>`$${n}`}),e.jsx(Ee,{contentStyle:{background:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},formatter:(n,I,m)=>{const M=m?.payload?.conversions,z=typeof n=="number"?n:null;return z==null?["â","CPL"]:[`$${z.toFixed(2)} (${M??0} conv)`,"CPL"]}}),e.jsx(Te,{type:"monotone",dataKey:"cpl",stroke:"var(--primary)",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),e.jsx("div",{className:"space-y-2",children:a.ads.map(n=>e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-border p-2.5",children:[e.jsx("div",{className:"h-8 w-1 rounded-full shrink-0",style:{background:C.get(n.ad_id)}}),e.jsx(Oe,{ad:n}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium break-all",children:ge(n.name,n.ad_id)}),e.jsx(Ys,{status:n.status})]}),n.headline||n.primary_text?e.jsx(bs,{delayDuration:150,children:e.jsxs(ys,{children:[e.jsx(Ns,{asChild:!0,children:e.jsx("p",{className:"text-xs text-muted-foreground truncate cursor-help",children:n.headline??n.primary_text?.slice(0,80)??""})}),e.jsx(ws,{className:"max-w-sm",children:e.jsxs("p",{className:"text-xs whitespace-pre-wrap",children:[n.headline?e.jsx("span",{className:"font-semibold block mb-1",children:n.headline}):null,n.primary_text?.slice(0,400)]})})]})}):null]}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsxs("div",{className:"text-sm font-mono tabular-nums",children:[(n.recent_share*100).toFixed(1),"%"]}),e.jsxs("div",{className:`text-xs font-mono tabular-nums ${n.momentum>0?"text-emerald-600 dark:text-emerald-400":n.momentum<0?"text-rose-600 dar
1k:text-rose-400":"text-muted-foreground"}`,children:[n.momentum>0?"+":"",(n.momentum*100).toFixed(1),"pp"]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20 hidden sm:block",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.total_impressions.toLocaleString()," imp"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.total_conversions," conv"]})]})]},n.ad_id))}),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:["AI Forensics",u?" · vs. other campaign":""]}),V?e.jsxs(D,{variant:"outline",className:"capitalize",children:[V.confidence," confidence"]}):null]}),e.jsx(_,{size:"sm",variant:"outline",onClick:()=>q.mutate(),disabled:q.isPending||c,children:q.isPending?"Analyzingâ¦":V?"Re-run":"Run forensics"})]}),g.length>0?e.jsxs("div",{className:"space-y-3",children:[q.isPending?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Refreshing analysis â showing last pulled insights until the new run finishes."}):null,E.map((n,I)=>{const m=i*w+I;return e.jsxs("div",{className:"space-y-2 text-sm border-t border-border first:border-t-0 pt-3 first:pt-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[m===0?"Latest · ":"",new Date(n.generated_at).toLocaleString()]}),e.jsx(D,{variant:"outline",className:"capitalize text-[10px]",children:n.confidence})]}),e.jsx("p",{className:"text-foreground/90 whitespace-pre-wrap",children:n.narrative}),n.predicted_winner_ad_id?e.jsxs("div",{className:"rounded-md border border-emerald-500/30 bg-emerald-500/5 p-2",children:[e.jsx("div",{className:"text-xs font-semibold text-emerald-700 dark:text-emerald-400 mb-1",children:"Predicted 7-day winner"}),e.jsx("div",{className:"flex items-center gap-2",children:(()=>{const M=a.ads.find(z=>z.ad_id===n.predicted_winner_ad_id);return M?e.jsxs(e.Fragment,{children:[e.jsx(Oe,{ad:M}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium break-all",children:ge(M.name,M.ad_id)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:n.predicted_winner_reason})]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:n.predicted_winner_reason})})()})]}):null,n.recommendations.length>0?e.jsx("ul",{className:"list-disc list-inside space-y-1 text-xs text-muted-foreground",children:n.recommendations.map((M,z)=>e.jsx("li",{children:M},z))}):null,n.patterns_recorded>0?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["â ",n.patterns_recorded," creative pattern",n.patterns_recorded===1?"":"s"," saved to your workspace brain."]}):null]},n.generated_at+":"+m)}),g.length>w?e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",i+1," / ",y," ·"," ",g.length," insights"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(_,{size:"sm",variant:"outline",onClick:()=>t(n=>Math.max(0,n-1)),disabled:i===0,children:"Prev"}),e.jsx(_,{size:"sm",variant:"outline",onClick:()=>t(n=>Math.min(y-1,n+1)),disabled:i>=y-1,children:"Next"})]})]}):null]}):e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click ",e.jsx("span",{className:"font-medium",children:"Run forensics"})," to identify the pattern Meta is favoring",u?", contrast it with the other campaign,":""," ","and store the learning for upcoming campaigns."]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No live ads in this campaign for the selected window."})}function Zs({workspaceId:s,rows:a,effectiveCpl:r,offerId:l=null,offerName:j=null}){const c=`winner-insights:${s??"anon"}:${l??"all"}`,[h,u]=U(`${c}:open`,!0),[f,C]=U(`${c}:list`,[]),[S,N]=$.useState(null),[b,p]=$.useState(0),d=R(Us),k=R(Hs),x=ve(),v=de({queryKey:["watchtower-winner-insights",s,l],queryFn:()=>k({data:{workspaceId:s,offerId:l,limit:30}}),enabled:!!s,initialData:f.length>0?{insights:f}:void 0}),g=v.data?.insights??f,w=ee({mutationFn:async()=>
1{if(!s)throw new Error("No workspace selected");return await d({data:{workspaceId:s,offerId:l,offerName:j,rows:a.map(m=>({offerName:m.offerName??null,awareness:m.awareness,format:m.format,framework:m.framework,headline:m.headline,cta:m.cta,cpl7:m.cpl7,spend7:m.spend7,conv7:m.conv7,vsHistoricalPct:m.vsHistoricalPct,health:m.health,trueRoas7:m.trueRoas7})),effectiveCpl:r}})},onSuccess:m=>{m.ok&&!m.empty?(C(M=>[{...m.insight,generatedAt:new Date().toISOString(),offerId:l,offerName:j,source:m.source??null},...M].slice(0,30)),p(0),N(null),x.invalidateQueries({queryKey:["watchtower-winner-insights",s,l]}),F.success(m.source==="live_ads"?"New analysis from your live ads (last 7 days).":"New analysis generated.")):m.ok&&m.empty?(N(m.message),F.info(m.message)):m.ok===!1&&(N(m.message),F.error(m.message))},onError:m=>F.error(m.message)}),i=!s||w.isPending,t=3,y=Math.max(1,Math.ceil(g.length/t)),E=Math.min(b,y-1),V=g.slice(E*t,E*t+t),q=g[0]??null,n=q?(Date.now()-new Date(q.generatedAt).getTime())/864e5:null,I=n!=null&&n>3;return e.jsxs(Z,{children:[e.jsx(G,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(ue,{className:"h-4 w-4"}),"Winner insights",g.length>0?e.jsxs("span",{className:"text-[10px] font-normal text-muted-foreground",children:["· ",g.length," saved"]}):null]}),e.jsxs(ce,{children:["AI pattern analysis â which creative attributes are driving your CPL up or down",l?e.jsxs(e.Fragment,{children:[" for ",e.jsx("strong",{children:j??"this offer"})]}):e.jsx(e.Fragment,{children:" across every offer in this workspace"}),"."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_,{size:"sm",onClick:()=>w.mutate(),disabled:i,children:w.isPending?"Analyzingâ¦":g.length>0?"Re-run analysis":"Analyze patterns"}),e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7","aria-label":h?"Collapse":"Expand",onClick:()=>u(m=>!m),children:h?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})})]})]})}),h?e.jsx(je,{className:"space-y-4",children:v.isLoading&&g.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{className:"h-4 w-3/4"}),e.jsx(B,{className:"h-4 w-full"}),e.jsx(B,{className:"h-4 w-2/3"})]}):g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:S??e.jsxs(e.Fragment,{children:["Click ",e.jsx("span",{className:"font-medium",children:"Analyze patterns"})," to surface the attribute combinations behind your wins and losses. One AI call per run."]})}):e.jsxs(e.Fragment,{children:[w.isPending?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Refreshing analysis â showing the latest saved insights until the new run finishes."}):null,S?e.jsx("p",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs",children:S}):null,I&&!w.isPending?e.jsxs("p",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs",children:["Latest insight is ",Math.round(n)," days old â press"," ",e.jsx("span",{className:"font-medium",children:"Re-run analysis"})," to score the last 7 days."]}):null,e.jsx("div",{className:"space-y-5",children:V.map((m,M)=>e.jsx(Gs,{insight:m,isLatest:E===0&&M===0},m.generatedAt+M))}),g.length>t?e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Showing ",E*t+1,"â",Math.min(g.length,E*t+t)," of ",g.length]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>p(m=>Math.max(0,m-1)),disabled:E===0,"aria-label":"Newer insights",children:e.jsx(Ps,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:[E+1," / ",y]}),e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>p(m=>Math.min(y-1,m+1)),disabled:E>=y-1,"aria-label":"Older insights",children:e.jsx(ls,{className:"h-4 w-4"})})]})]}):null]})}):null]})}function Gs({insight:s,isLatest:a}){return e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium leading-snug flex-1 min-w-0",children:s.headline}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[s.offerName?e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground",children:s.offerName}):null,s.source==="live_ads"?e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground",children:"live ads"}):null,a?e.jsx("span",{className:"rounded-full bg-primary/10 text-primary px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide",children:"Latest"}):null,e.jsx("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:new Date(s.generatedAt).toLocaleStr
1ing()})]})]}),s.winningPatterns.length>0?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(be,{className:"h-3.5 w-3.5 text-emerald-500"}),"Winning patterns"]}),e.jsx("ul",{className:"space-y-1 text-sm",children:s.winningPatterns.map((r,l)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-emerald-500 mt-0.5",children:"â¢"}),e.jsx("span",{children:r})]},l))})]}):null,s.losingPatterns.length>0?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(Be,{className:"h-3.5 w-3.5 text-destructive"}),"Losing patterns"]}),e.jsx("ul",{className:"space-y-1 text-sm",children:s.losingPatterns.map((r,l)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-destructive mt-0.5",children:"â¢"}),e.jsx("span",{children:r})]},l))})]}):null,e.jsxs("div",{className:"flex gap-2 items-start pt-1.5 border-t",children:[e.jsx(Ms,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Next move: "}),s.nextAction]})]})]})}const Js=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_matrix-iterate_functions_ts--runMatrixIteration_createServerFn_handler")),Qe=ne({method:"POST"}).middleware([re]).handler(ie("src_lib_meta-controls_functions_ts--setMetaEntityStatus_createServerFn_handler"));function Ot(){const s=ve(),{session:a,loading:r}=js(),l=R(cs),j=R(qs),c=R(ds),h=R(os),u=R(Js),f=R(Qe),C=R(ms),{data:S,isLoading:N,error:b}=de({queryKey:["workspaces"],queryFn:async()=>{try{return await l({})}catch(o){if(!(o instanceof Error?o.message:String(o)).includes("No authorization header provided"))throw o;return vs()}},enabled:!!a}),p=S?.[0],{data:d,isLoading:k,error:x}=de({queryKey:["matrix-watchtower",p?.id],queryFn:()=>j({data:{workspaceId:p.id}}),enabled:!!a&&!!p,refetchInterval:300*1e3}),v=ee({mutationFn:o=>c({data:{id:o,execute:!0}}),onSuccess:()=>{F.success("Approved â Meta updated."),s.invalidateQueries({queryKey:["matrix-watchtower",p?.id]})},onError:o=>F.error(o.message)}),g=ee({mutationFn:o=>h({data:{id:o}}),onSuccess:()=>{F.success("Dismissed."),s.invalidateQueries({queryKey:["matrix-watchtower",p?.id]})},onError:o=>F.error(o.message)}),w=ee({mutationFn:async()=>{const[o,P]=await Promise.allSettled([C({data:{workspaceId:p.id}}),u({data:{workspaceId:p.id}})]);return{brainRes:o,iterRes:P}},onSuccess:({brainRes:o,iterRes:P})=>{const L=[];if(o.status==="fulfilled"&&L.push("Brain analysis complete"),P.status==="fulfilled"){const T=P.value;T.proposed>0&&L.push(`${T.proposed} AI call${T.proposed===1?"":"s"} queued`),(T.compounded??0)>0&&L.push(`${T.compounded} winner variation${T.compounded===1?"":"s"} seeded`)}const O=[o,P].filter(T=>T.status==="rejected");L.length>0?F.success(L.join(" · ")):O.length===0&&F.info("No new signals to surface.");for(const T of O)F.error(T.reason?.message??"Run failed");s.invalidateQueries({queryKey:["opt-actions"]}),s.invalidateQueries({queryKey:["matrix-watchtower"]})}}),[i,t]=$.useState({}),[y,E]=$.useState(new Set),[V,q]=$.useState(null),[n,I]=$.useState("ALL"),[m,M]=U(`watchtower:offer-filter:${p?.id??"anon"}`,"ALL"),z=d?.offers??[],X=z.find(o=>o.id===m)??null,oe=$.useMemo(()=>(d?.rows??[]).filter(o=>m==="ALL"||(o.offerId??"unassigned")===m),[d?.rows,m]),[Ne,Ze]=U(`watchtower:matrix-card:open:${p?.id??"anon"}`,!0),xe=o=>(o.metaCampaignId&&i[o.metaCampaignId])??o.status,he=$.useMemo(()=>{const o={ALL:0,ACTIVE:0,PAUSED:0,ARCHIVED:0};for(const P of oe){o.ALL+=1;const L=xe(P);L==="ACTIVE"?o.ACTIVE+=1:L==="ARCHIVED"?o.ARCHIVED+=1:o.PAUSED+=1}return o},[oe,i]),pe=$.useMemo(()=>oe.filter(o=>{if(n==="ALL")return!0;const P=xe(o);return n==="PAUSED"?P!=="ACTIVE"&&P!=="ARCHIVED":P===n}),[oe,i,n]),le=$.useMemo(()=>pe.filter(o=>o.metaCampaignId&&xe(o)==="ACTIVE"),[pe,i]),$e=le.length>0&&le.every(o=>y.has(o.metaCampaignId)),Ge=y.size>0&&!$e;function Je(o,P){E(L=>{const O=new Set(L);return P?O.add(o):O.delete(o),O})}function es(o){E(o?new Set(le.map(P=>P.metaCampaignId)):new Set)}async function Se(o){if(y.size===0||!p)return;const P=o==="PAUSED"?"pause":"archive";if(!confirm(`${P[0].toUpperCase()+P.slice(1)} ${y.size} campaign${y.size===1?"":"s"} in Meta? This will stop spending immediately.`))return;q(o);const L=Array.from(y);let O=0;const T=[];for(const ke of L)try{await f({data:{workspaceId:p.id,level:"campaign",metaId:ke,status:o}}),O+=1,t(we=>({...we,[ke]:o}))}catch(we){T.push(we.message)}q(null),E(new Set),s.invalidateQueries({queryKey:["matrix-watchtower",p.id]}),T.length===0?F.success(`${O} campaign${O===1?"":"s"} ${P}d in Meta.`):F.error(`${O} ${P}d, ${T.length} failed. First error: ${T[0]}`)}function ss(o,P){t(L=>({...L,[o]:P}))}return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{}),e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Matrix Watchtower"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Live health of every matrix push, plus AI calls awaiting approval."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(_,{size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!p,children:[e.jsx(ue,{className:ae("mr-1.5 h-3.5 w-3.5",w.isPending&&"animate-pulse")}),w.isPending?"Analyzing & scanningâ¦":"Analyze & scan"]})})]}),r||N?e.jsx(B,{className:"h-28 w-full"}):b?e.jsx(Z,{children:e.jsxs(G,{children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ae,{className:"h-4 w-4 text-destructive"}),"Watchtower couldnât load your workspace"]}),e.jsx(ce,{children:b instanceof Error?b.message:String(b)})]})}):p?x?e.jsx(Z,{children:e.jsxs(G,{children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ae,{className:"h-4 w-4 text-destructive"}),"Watchtower failed to load"]}),e.jsx(ce,{children:x instanceof Error?x.message:String(x)})]})}):null:e.jsx(Z,{children:e.jsxs(G,{children:[e.jsx(J,{className:"text-base",children:"No workspace found"}),e.jsx(ce,{children:"Sign in to a workspace with connected Meta assets to
1see Watchtower data."})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[e.jsx(me,{label:"Active campaigns",value:d?String(d.account.activeCampaigns):"â",sub:d?`of ${d.account.totalCampaigns} total`:void 0}),e.jsx(me,{label:"Active ads",value:d?String(d.account.activeAds):"â",sub:d?`of ${d.account.totalAds} total · ${d.totals.cellsPushed} from matrix`:void 0}),e.jsx(me,{label:"Spend 7d",value:d?`${d.account.currency==="USD"||!d.account.currency?Ye(d.account.spend7):d.account.spend7.toFixed(d.account.spend7<10?2:0)}${d.account.currency&&d.account.currency!=="USD"?` ${d.account.currency}`:""}`:"â"}),e.jsx(me,{label:"Conv 7d",value:d?String(d.account.conv7):"â"}),e.jsx(me,{label:"CPL 7d",value:d?.account.cpl7!=null?`$${d.account.cpl7.toFixed(2)}`:"â",sub:d?.effectiveCpl!=null?`vs $${d.effectiveCpl.toFixed(2)} hist`:void 0})]}),d?.account.unavailable?e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:d.account.reason==="no_meta_creds"?"Connect Meta to populate live account totals.":`Couldn't load live Meta totals: ${d.account.reason??"unknown error"}`}):null,e.jsx(Xs,{workspaceId:p?.id??null}),e.jsx(dt,{workspaceId:p?.id??null,pending:d?.pendingProposals??[],isLoading:k,onApprove:o=>v.mutate(o),onReject:o=>g.mutate(o),approvingId:v.isPending?v.variables??null:null,rejectingId:g.isPending?g.variables??null:null}),e.jsx(Zs,{workspaceId:p?.id??null,rows:oe,effectiveCpl:d?.effectiveCpl??null,offerId:m!=="ALL"&&m!=="unassigned"?m:null,offerName:X?.name??null}),e.jsxs(Z,{children:[e.jsx(G,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(We,{className:"h-4 w-4"}),"Matrix campaigns"]}),e.jsxs(ce,{children:["Sorted by what needs attention first · last 7d",X?e.jsxs(e.Fragment,{children:[" · offer ",e.jsx("strong",{children:X.name})]}):null,d?.effectiveCpl!=null?e.jsxs(e.Fragment,{children:[" ","· baseline CPL ",e.jsxs("strong",{children:["$",d.effectiveCpl.toFixed(2)]})]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z.length>1?e.jsxs(W,{value:m,onValueChange:o=>{M(o),E(new Set)},children:[e.jsx(K,{className:"h-8 w-[200px] text-xs","aria-label":"Filter by offer",children:e.jsx(Q,{})}),e.jsxs(Y,{children:[e.jsxs(A,{value:"ALL",children:["All offers (",d?.rows.length??0,")"]}),z.map(o=>e.jsxs(A,{value:o.id,children:[o.name," (",o.cells,")"]},o.id))]})]}):null,e.jsxs(W,{value:n,onValueChange:o=>{I(o),E(new Set)},children:[e.jsx(K,{className:"h-8 w-[170px] text-xs",children:e.jsx(Q,{})}),e.jsxs(Y,{children:[e.jsxs(A,{value:"ACTIVE",children:["Active (",he.ACTIVE,")"]}),e.jsxs(A,{value:"PAUSED",children:["Paused (",he.PAUSED,")"]}),e.jsxs(A,{value:"ARCHIVED",children:["Archived (",he.ARCHIVED,")"]}),e.jsxs(A,{value:"ALL",children:["All (",he.ALL,")"]})]})]}),e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7","aria-label":Ne?"Collapse":"Expand",onClick:()=>Ze(o=>!o),children:Ne?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})})]})]})}),Ne?e.jsxs(je,{className:"space-y-3",children:[le.length>0?e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border bg-muted/40 px-3 py-2 sticky top-0 z-10 backdrop-blur supports-[backdrop-filter]:bg-muted/30",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer select-none",children:[e.jsx(He,{checked:$e?!0:Ge?"indeterminate":!1,onCheckedChange:o=>es(o===!0),"aria-label":"Select all active campaigns"}),e.jsx("span",{className:"font-medium",children:y.size>0?`${y.size} of ${le.length} selected`:`Select all active · ${le.length}`})]}),y.size>0?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(_,{size:"sm",variant:"outline",disabled:V!==null,onClick:()=>Se("PAUSED"),children:[e.jsx(ye,{className:"mr-1 h-3.5 w-3.5"}),V==="PAUSED"?"Pausingâ¦":"Pause"]}),e.jsxs(_,{size:"sm",variant:"outline",disabled:V!==null,onClick:()=>Se("ARCHIVED"),children:[e.jsx(Ke,{className:"mr-1 h-3.5 w-3.5"}
1),V==="ARCHIVED"?"Archivingâ¦":"Archive"]})]}):null]}):null,k?e.jsx(B,{className:"h-40 w-full"}):d?.rows.length?pe.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match this filter."}):e.jsx(lt,{rows:pe,workspaceId:p.id,selected:y,toggleRow:Je,statusOverrides:i,markStatus:ss,statusFilter:n,effectiveStatusOf:xe}):e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground max-w-md mx-auto",children:"Live Ads tracks every campaign you've pushed to Meta â spend, ROAS, and the Brain's verdict on what to kill or scale. Push your first matrix cell to fill this view."})]}):null]})]})}function me({label:s,value:a,sub:r}){return e.jsxs("div",{className:"rounded-md border bg-card p-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s}),e.jsx("p",{className:"text-lg font-semibold",children:a}),r?e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:r}):null]})}function Ye(s){return!Number.isFinite(s)||s===0?"$0":Math.abs(s)<10?`$${s.toFixed(2)}`:`$${s.toFixed(0)}`}function et(s){return s==null||!Number.isFinite(s)?"â":`${(s*100).toFixed(2)}%`}function st(s){return s==null||!Number.isFinite(s)?"â":s.toFixed(1)}function Xe({action:s}){return s.startsWith("pause")?e.jsx(ye,{className:"h-4 w-4 text-destructive"}):s.includes("scale")?e.jsx(be,{className:"h-4 w-4 text-emerald-500"}):s.includes("refresh")||s.includes("fatigue")?e.jsx(Ue,{className:"h-4 w-4 text-amber-500"}):s.includes("duplicate")?e.jsx(us,{className:"h-4 w-4 text-blue-500"}):e.jsx(ue,{className:"h-4 w-4 text-primary"})}function tt({status:s,overridden:a}){const l={ACTIVE:{label:"Active",cls:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30"},PAUSED:{label:"Stopped",cls:"bg-muted text-muted-foreground border-muted-foreground/30"},ARCHIVED:{label:"Archived",cls:"bg-muted text-muted-foreground border-muted-foreground/30"}}[s]??{label:s||"Unknown",cls:"bg-muted text-muted-foreground border-muted-foreground/20"};return e.jsxs("span",{className:ae("inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",l.cls),title:a?"Just confirmed in Meta":void 0,children:[l.label,a?" â":""]})}function at({h:s}){const a={healthy:{label:"Healthy",cls:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30",Icon:fs},warming:{label:"Learning",cls:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30",Icon:Le},warning:{label:"Watch",cls:"bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30",Icon:Ae},critical:{label:"Act now",cls:"bg-destructive/10 text-destructive border-destructive/30",Icon:gs},unknown:{label:"Idle",cls:"bg-muted text-muted-foreground border-muted-foreground/20",Icon:Le}},{label:r,cls:l,Icon:j}=a[s];return e.jsxs("span",{className:ae("inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium",l),children:[e.jsx(j,{className:"h-3 w-3"}),r]})}function nt({r:s,workspaceId:a,checked:r,onToggle:l,statusOverride:j,onConfirmedStatus:c}){const h=ve(),u=R(Qe),[f,C]=U(`watchtower:cell:${s.id}:open`,!1),S=ee({mutationFn:x=>u({data:{workspaceId:a,level:"campaign",metaId:s.metaCampaignId,status:x}}),onSuccess:x=>{const v=x.status;c(v),F.success(`Confirmed ${v.toLowerCase()} in Meta (effective ${x.effectiveStatus??"?"}).`),h.invalidateQueries({queryKey:["matrix-watchtower",a]})},onError:x=>F.error(x.message)}),N=j??s.status,b=N==="PAUSED"||N==="ARCHIVED",p=N==="ARCHIVED",d=N==="ACTIVE",k=s.metaCampaignId?(()=>{const x=s.metaAdAccountId?.replace(/^act_/,""),v="https://business.facebook.com/adsmanager/manage/campaigns";return x?`${v}?act=${x}&selected_campaign_ids=${s.metaCampaignId}`:`${v}?selected_campaign_ids=${s.metaCampaignId}`})():null;return e.jsxs("div",{"data-app-row":"","data-selected":r?"true":void 0,className:ae("rounded-lg border bg-card p-3 space-y-3 transition-colors hover:border-foreground
1/20",b&&"bg-muted/20 opacity-75",r&&"ring-1 ring-primary/50 border-primary/50"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[s.metaCampaignId?e.jsx(He,{checked:r,onCheckedChange:x=>l(x===!0),"aria-label":"Select campaign",className:"mt-1"}):e.jsx("div",{className:"w-4"}),s.thumbnailUrl?e.jsx("img",{src:s.thumbnailUrl,alt:"",loading:"lazy",className:"h-12 w-12 flex-shrink-0 rounded border object-cover bg-muted"}):e.jsx("div",{className:"h-12 w-12 flex-shrink-0 rounded border bg-muted/40 text-[10px] uppercase flex items-center justify-center text-muted-foreground",children:"Ad"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[s.headline?k?e.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1.5 text-sm font-medium leading-snug truncate hover:text-primary transition-colors",title:"Open campaign in Meta Ads Manager",children:[e.jsx("span",{className:"truncate",children:s.headline}),e.jsx(ps,{className:"h-3 w-3 shrink-0 opacity-50 group-hover:opacity-100"})]}):e.jsx("p",{className:"text-sm font-medium leading-snug truncate",children:s.headline}):null,e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap mt-1",children:[e.jsx(at,{h:s.health}),N!=="ACTIVE"?e.jsx(tt,{status:N,overridden:!!j}):null,e.jsxs("span",{className:"text-[10px] text-muted-foreground capitalize",children:[s.awareness.replace(/_/g," ")," · ",s.format,s.variationCount>0?` · +${s.variationCount} var${s.variationCount===1?"":"s"}`:"",b&&s.pausedAt?` · paused ${rt(s.pausedAt)}`:s.daysSincePush!=null?` · ${s.daysSincePush}d live`:""]}),!b&&s.isLearning&&s.learningUntil?e.jsxs(D,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-600 dark:text-amber-400",title:`Watchtower will not propose changes until ${new Date(s.learningUntil).toLocaleString()}`,children:["Learning â ",Math.max(0,Math.round((new Date(s.learningUntil).getTime()-Date.now())/36e5)),"h left"]}):null,b&&s.pausedByBrain?e.jsxs(D,{variant:"outline",className:"text-[10px] border-destructive/40 text-destructive",title:s.pausedReason??"Paused by Watchtower",children:["Paused by Brain",s.pausedReason?` · ${it(s.pausedReason,60)}`:""]}):null]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:s.verdict})]}),s.metaCampaignId?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",onClick:()=>C(x=>!x),"aria-label":f?"Collapse metrics":"Expand metrics","aria-expanded":f,children:f?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})}),e.jsxs(Ds,{children:[e.jsx(Es,{asChild:!0,children:e.jsx(_,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",disabled:S.isPending,"aria-label":"Campaign actions",children:S.isPending?e.jsx(Ue,{className:"h-4 w-4 animate-spin"}):e.jsx(zs,{className:"h-4 w-4"})})}),e.jsxs(Is,{align:"end",className:"w-44",children:[e.jsxs(Ce,{disabled:d,onClick:()=>{confirm("Activate this campaign in Meta? It will start spending immediately.")&&S.mutate("ACTIVE")},children:[e.jsx(We,{className:"mr-2 h-4 w-4"}),d?"Already active":"Activate campaign"]}),e.jsx(ze,{}),e.jsxs(Ce,{disabled:b,onClick:()=>{confirm("Pause this campaign in Meta? It will stop spending immediately.")&&S.mutate("PAUSED")},children:[e.jsx(ye,{className:"mr-2 h-4 w-4"}),N==="PAUSED"?"Already stopped":"Pause campaign"]}),e.jsx(ze,{}),e.jsxs(Ce,{disabled:p,onClick:()=>{confirm("Archive this campaign in Meta? It will stop spending and be hidden from the active list.")&&S.mutate("ARCHIVED")},className:"text-destructive focus:text-destructive",children:[e.jsx(Ke,{className:"mr-2 h-4 w-4"}),p?"Already archived":"Archive campaign"]})]})]})]}):e.jsx(_,{size:"icon",variant:"ghost",className:"h-8 w-8 shrink-0",onClick:()=>C(x=>!x),"aria-label":f?"Collapse metrics":"Expand metrics","aria-expanded":f,children:f?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})})]}),f&&(()=>{const x=s.vsHistoricalPct==null?null:`${s.vsHistoricalPct>0?"+":""}${Math.round(s.vsHistoricalPct*100)}% vs hist`,v=s.vsHistoricalPct==null?void 0:s.vsHistoricalPct>.3?"bad":s.vsHistoricalPct<-.2?"good":void 0,g=s.sold7>0||s.booked7>0||s.showed7>0||s.revenue7>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-5 ga
1p-1.5 text-xs pl-7",children:[e.jsx(H,{label:"Spend 7d",value:Ye(s.spend7)}),e.jsx(H,{label:"CPL 7d",value:s.cpl7!=null?`$${s.cpl7.toFixed(2)}`:"â",sub:x??void 0,tone:v}),e.jsx(H,{label:"Conv 7d",value:String(s.conv7)}),e.jsx(H,{label:"CTR 7d",value:et(s.ctr7),tone:s.ctr7==null?void 0:s.ctr7>=.02?"good":s.ctr7<.008?"bad":void 0}),e.jsx(H,{label:"Freq 7d",value:st(s.freq7),tone:s.freq7==null?void 0:s.freq7>=4?"bad":s.freq7>=3?"warn":void 0,sub:s.freq7!=null&&s.freq7>=3?"fatigue risk":void 0})]}),g?e.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-5 gap-1.5 text-xs pl-7",children:[e.jsx(H,{label:"True ROAS 7d",value:s.trueRoas7!=null?`${s.trueRoas7.toFixed(2)}Ã`:"â",tone:s.trueRoas7==null?void 0:s.trueRoas7>=2?"good":s.trueRoas7<1&&s.spend7>0?"bad":void 0,sub:`$${s.revenue7.toFixed(0)} rev`}),e.jsx(H,{label:"Cost / sale",value:s.costPerSale7!=null?`$${s.costPerSale7.toFixed(0)}`:"â"}),e.jsx(H,{label:"Booked",value:String(s.booked7)}),e.jsx(H,{label:"Showed",value:String(s.showed7),sub:s.booked7>0?`${Math.round(s.showed7/s.booked7*100)}% show`:void 0}),e.jsx(H,{label:"Sold",value:String(s.sold7),sub:s.showed7>0?`${Math.round(s.sold7/s.showed7*100)}% close`:void 0})]}):s.spend7>0?e.jsx("p",{className:"text-[10px] text-muted-foreground/70 pl-7",children:"No CRM events yet â revenue metrics will appear once leads convert downstream."}):null]})})()]})}function H({label:s,value:a,tone:r,sub:l}){return e.jsxs("div",{className:"rounded-md border bg-background/60 px-2 py-1.5",children:[e.jsx("p",{className:"text-[9px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("p",{className:ae("text-xs font-semibold tabular-nums",r==="good"&&"text-emerald-600 dark:text-emerald-400",r==="bad"&&"text-destructive",r==="warn"&&"text-amber-600 dark:text-amber-400"),children:a}),l?e.jsx("p",{className:"text-[9px] text-muted-foreground/80 truncate",children:l}):null]})}function rt(s){const a=Date.now()-new Date(s).getTime();if(!Number.isFinite(a)||a<0)return"just now";const r=Math.round(a/6e4);if(r<60)return`${r}m ago`;const l=Math.round(r/60);return l<48?`${l}h ago`:`${Math.round(l/24)}d ago`}function it(s,a){return s.length>a?`${s.slice(0,a-1)}â¦`:s}function lt({rows:s,workspaceId:a,selected:r,toggleRow:l,statusOverrides:j,markStatus:c,statusFilter:h,effectiveStatusOf:u}){const[f,C]=$.useState(!1),S=h==="ACTIVE"||h==="ALL",{main:N,brainPaused:b}=$.useMemo(()=>{if(!S)return{main:s,brainPaused:[]};const d=[],k=[];for(const x of s){const v=u(x);(v==="PAUSED"||v==="ARCHIVED")&&x.pausedByBrain?k.push(x):d.push(x)}return{main:d,brainPaused:k}},[s,S,u]),p=d=>e.jsx(nt,{r:d,workspaceId:a,checked:d.metaCampaignId?r.has(d.metaCampaignId):!1,onToggle:k=>d.metaCampaignId&&l(d.metaCampaignId,k),statusOverride:d.metaCampaignId?j[d.metaCampaignId]:void 0,onConfirmedStatus:k=>d.metaCampaignId&&c(d.metaCampaignId,k)},d.id);return e.jsxs(e.Fragment,{children:[N.length>0?N.map(p):b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match this filter."}):null,b.length>0?e.jsxs("div",{className:"rounded-lg border bg-muted/20",children:[e.jsxs("button",{type:"button",onClick:()=>C(d=>!d),className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-xs font-medium hover:bg-muted/40 transition-colors","aria-expanded":f,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ye,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Paused by Brain â ",b.length,e.jsx("span",{className:"text-muted-foreground font-normal",children:"· nothing to do here"})]}),f?e.jsx(se,{className:"h-3.5 w-3.5"}):e.jsx(te,{className:"h-3.5 w-3.5"})]}),f?e.jsx("div",{className:"space-y-2 p-2 pt-0",children:b.map(p)}):null]}):null]})}function ct(s){const a=s.payload??{},r=a.meta_action??null,l=s.targetType==="campaign"?"campaign":s.targetType==="ad_set"?"ad set":s.targetType==="ad"?"ad":s.targetType,j=typeof a.ad_name=="string"&&a.ad_name||s.targetName||s.campaignName||`this ${l}`;if(!r){if(s.action==="review_structure"){const c=Array.isArray(a.losers_in_campaign)?a.losers_in_campaign:[],h=["Mark this recommendation as reviewed (no Meta change executed automatically)."];return c.length&&h.push(`Approve the separate Pause recommendations for ${c.length} underperforming ad${c.length===1?"":"s"} in this campaign to concentrate budget on the winner.`),h.push(`In Ads Manager, duplicate "${j}
1" into a new ABO ad set with its own dedicated budget.`),h}return["Approval is acknowledgement-only â no Meta API call is executed. You'll handle this change manually in Ads Manager."]}switch(r.kind){case"pause_ad":return[`Call Meta Ads API: set ad ${r.meta_id} status â PAUSED.`,"The ad stops spending immediately; the ad set, campaign and other ads remain untouched."];case"activate_ad":return[`Call Meta Ads API: set ad ${r.meta_id} status â ACTIVE.`,"Meta resumes delivery using the existing ad set budget and targeting."];case"pause_campaign":return[`Call Meta Ads API: set campaign ${r.meta_id} status â PAUSED.`,"Every ad set and ad inside this campaign stops delivering."];case"scale_adset":{const c=typeof a.current_daily_budget_usd=="number"?a.current_daily_budget_usd:null,h=r.daily_budget_usd??null;return[`Call Meta Ads API: update ad set ${r.meta_id} â daily_budget = $${h?.toFixed(2)??"â"}.`,c!=null&&h!=null?`Effective change: $${c.toFixed(2)} â $${h.toFixed(2)} per day (+${Math.round((h-c)/c*100)}%).`:`Effective change: raise this ad set's daily budget to $${h?.toFixed(2)??"â"}.`,"Only this ad set is affected; sibling ad sets in the same campaign keep their current budgets."]}case"scale_campaign":{const c=typeof a.current_daily_budget_usd=="number"?a.current_daily_budget_usd:null,h=r.daily_budget_usd??null,u=typeof a.campaign_active_ads=="number"?a.campaign_active_ads:null;return[`Call Meta Ads API: update campaign ${r.meta_id} â daily_budget = $${h?.toFixed(2)??"â"}.`,c!=null&&h!=null?`Effective change: $${c.toFixed(2)} â $${h.toFixed(2)} per day (+${Math.round((h-c)/c*100)}%).`:"Effective change: raise this campaign's daily budget.",u!=null?`Because this is a CBO campaign, Meta will distribute the new budget across all ${u} active ad${u===1?"":"s"} â proven winner gets the majority.`:"Meta distributes the campaign budget across active ad sets based on performance."]}case"bid_strategy_adset":{const c=typeof r.bid_amount_cents=="number"?r.bid_amount_cents/100:null;return[`Call Meta Ads API: update ad set ${r.meta_id} â bid_strategy = ${r.bid_strategy}${c!=null?`, bid_amount = $${c.toFixed(2)}`:""}.`,r.bid_strategy==="COST_CAP"&&c!=null?`Meta will keep delivering, but stop bidding on auctions where the projected CPA would exceed $${c.toFixed(2)}.`:r.bid_strategy==="LOWEST_COST_WITHOUT_CAP"?"Meta removes the cap and bids freely to maximise volume â re-evaluate CPA after 3â4 days.":"Meta switches to the new bid strategy and re-enters a brief learning phase.","Only this ad set's bidding changes; budgets, creative and targeting stay the same."]}case"bid_strategy_campaign":return[`Call Meta Ads API: update campaign ${r.meta_id} â bid_strategy = ${r.bid_strategy}.`,r.bid_strategy==="COST_CAP"?"All ad sets in this campaign inherit COST_CAP and protect against CPA drift.":`All ad sets in this campaign switch to ${r.bid_strategy} and re-enter a brief learning phase.`];case"change_optimization_goal_campaign":return[`Call Meta Ads API: update campaign ${r.meta_id} â optimization_goal = ${r.optimization_goal}${r.custom_event_type?` (event: ${r.custom_event_type})`:""}.`,"Meta re-enters the learning phase for this campaign â expect 3â7 days of CPA volatility before stabilising."];case"launch_parallel_manual_campaign":{const c=r.target_placement,h=c?`${c.publisher_platform}/${c.position}`:"the target placement",u=r.new_daily_budget_usd??null;return[`Create a new manual CBO campaign "${r.new_campaign_name??"Parallel campaign"}" (PAUSED) at $${u?.toFixed(2)??"â"}/day.`,`Deep-copy the top-converting ad set from the source campaign into the new campaign and narrow its targeting to ${h} only.`,"Leaves the original ASC campaign untouched. You flip the new campaign live from Ads Manager after reviewing for auction overlap with the existing ASC."]}case"start_placement_split_test":{const c=r.dropped_placement,h=c?`${c.publisher_platform}/${c.position}`:"the candidate placement",u=r.test_days??7,f=typeof a.estimated_test_cost_usd=="number"?a.estimated_test_cost_usd:null;return[`Duplicate this ad set; on the variant, strip ${h} from the placement allow-list.`,`Split the ad set's daily budget 50/50 between control (with the placement) and variant (without). Both run ACTIVE for ${u}
1 days.`,f!=null?`Estimated test spend: ~$${f.toLocaleString()}. After ${u} days, Brain reads both arms and only queues a prune approval if variant CPA is â¥10% lower with nâ¥30 conversions per arm.`:`After ${u} days, Brain reads both arms and only queues a prune approval if variant beat control on total CPA.`]}case"prune_placement_after_test":{const c=a.dropped_placement??null,h=c?`${c.publisher_platform}/${c.position}`:"the tested placement",u=typeof a.control_cpa=="number"?a.control_cpa:null,f=typeof a.variant_cpa=="number"?a.variant_cpa:null;return[`Pause control ad set ${r.control_adset_id} (the one still serving ${h}).`,`Variant ad set ${r.variant_adset_id} becomes the live one â it continues delivering without ${h}.`,u!=null&&f!=null?`Test result: CPA $${u.toFixed(2)} â $${f.toFixed(2)} (${Math.round((1-f/u)*100)}% improvement). Reversible: rollback re-activates control.`:"Reversible: rollback re-activates control if you want the placement back."]}default:return[`Approval executes Meta action "${r.kind}" on ${l} ${r.meta_id??s.targetId??""}.`]}}function dt({workspaceId:s,pending:a,isLoading:r,onApprove:l,onReject:j,approvingId:c,rejectingId:h}){const u=s?`ai-calls-open:${s}`:"ai-calls-open",[f,C]=$.useState(()=>{if(typeof window>"u")return!0;const i=window.localStorage.getItem(u);return i==null?!0:i==="1"}),S=()=>{C(i=>{const t=!i;return typeof window<"u"&&window.localStorage.setItem(u,t?"1":"0"),t})},[N,b]=$.useState("pending"),p=a.length,[d,k]=$.useState(0),x=5,v=Math.max(1,Math.ceil(p/x)),g=Math.min(d,v-1),w=a.slice(g*x,g*x+x);return e.jsxs(Z,{children:[e.jsx(G,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(J,{className:"flex items-center gap-2 text-base",children:[e.jsx(ue,{className:"h-4 w-4 text-primary"}),"AI calls",p>0?e.jsxs(D,{variant:"secondary",children:[p," pending"]}):e.jsx(D,{variant:"outline",className:"text-[10px]",children:"up to date"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[f?e.jsxs("div",{className:"flex items-center gap-1 mr-1",children:[e.jsx(_,{size:"sm",variant:N==="pending"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>b("pending"),children:"Pending"}),e.jsx(_,{size:"sm",variant:N==="history"?"secondary":"ghost",className:"h-7 px-2 text-xs",onClick:()=>b("history"),children:"History"})]}):null,e.jsx(_,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:S,children:f?e.jsx(se,{className:"h-4 w-4"}):e.jsx(te,{className:"h-4 w-4"})})]})]})}),f?e.jsx(je,{className:"space-y-2",children:N==="pending"?r?e.jsx(B,{className:"h-20 w-full"}):p===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No new recommendations â you're caught up."}):e.jsxs(e.Fragment,{children:[w.map(i=>e.jsx("div",{"data-app-row":"",className:"rounded-md border bg-card p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0 flex-1",children:[i.thumbnailUrl?e.jsx("img",{src:i.thumbnailUrl,alt:"",loading:"lazy",className:"h-12 w-12 flex-shrink-0 rounded border object-cover bg-muted"}):e.jsx("div",{className:"h-12 w-12 flex-shrink-0 rounded border bg-muted/40 text-[10px] uppercase flex items-center justify-center text-muted-foreground",children:i.targetType==="ad_set"?"Set":i.targetType==="campaign"?"Camp":"Ad"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Xe,{action:i.action}),e.jsx("span",{className:"font-medium text-sm capitalize",children:i.action.replace(/_/g," ")}),e.jsx(D,{variant:"outline",className:"text-[10px]",children:i.targetType}),i.priority?e.jsx(D,{variant:i.priority==="high"?"destructive":"secondary",className:"text-[10px]",children:i.priority}):null,i.aiConfidence!=null?e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Math.round(i.aiConfidence*100),"% confidence"]}):null]}),i.campaignName||i.adAccountName||i.targetName?e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground flex flex-wrap gap-x-3 gap-y-0.5",children:[i.adAccountName?e.jsxs("span",{children:["Account: ",e.jsx("span",{className:"text-foreground",children:i.adAccountName}),i.adAccountId?` (${i.adAccountId})`:""]}
1):null,i.campaignName?e.jsxs("span",{children:["Campaign: ",e.jsx("span",{className:"text-foreground",children:i.campaignName})]}):null,i.targetName&&i.targetName!==i.campaignName?e.jsxs("span",{children:[i.targetType,": ",e.jsx("span",{className:"text-foreground",children:i.targetName})]}):null,i.targetId?e.jsx("span",{className:"font-mono text-[10px] opacity-70",children:i.targetId}):null]}):null,i.problem?e.jsx("p",{className:"text-sm mt-1",children:i.problem}):null,i.rationale?e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i.rationale}):null,i.expected?e.jsxs("p",{className:"text-[11px] text-emerald-600 dark:text-emerald-400 mt-1",children:["â ",i.expected]}):null,(()=>{const t=ct(i);return t.length?e.jsxs("div",{className:"mt-2 rounded border border-border/60 bg-muted/30 p-2",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Action plan on approval"}),e.jsx("ol",{className:"list-decimal pl-4 space-y-0.5 text-[11px] text-foreground/90",children:t.map((y,E)=>e.jsx("li",{children:y},E))})]}):null})()]})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsxs(_,{size:"sm",variant:"default",onClick:()=>l(i.id),disabled:c===i.id,children:[e.jsx(Vs,{className:"mr-1 h-3.5 w-3.5"}),c===i.id?"Approvingâ¦":"Approve"]}),e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>j(i.id),disabled:h===i.id,children:[e.jsx(Rs,{className:"mr-1 h-3.5 w-3.5"}),h===i.id?"Dismissingâ¦":"Dismiss"]})]})]})},i.id)),p>x?e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Showing ",g*x+1,"â",Math.min(p,g*x+x)," of ",p]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(_,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>k(i=>Math.max(0,i-1)),disabled:g===0,children:"Prev"}),e.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:[g+1," / ",v]}),e.jsx(_,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>k(i=>Math.min(v-1,i+1)),disabled:g>=v-1,children:"Next"})]})]}):null]}):e.jsx(ot,{workspaceId:s})}):null]})}function ot({workspaceId:s}){const a=R(xs),r=R(hs),l=ve(),[j,c]=$.useState("all"),h=5,[u,f]=$.useState(0),[C,S]=$.useState("all"),{data:N,isLoading:b,isFetching:p}=de({queryKey:["ai-calls-history",s,j,u],queryFn:()=>a({data:{workspaceId:s,status:j,limit:h,offset:u*h}}),enabled:!!s}),d=ee({mutationFn:t=>r({data:{id:t}}),onSuccess:()=>{F.success("Reverted on Meta."),l.invalidateQueries({queryKey:["ai-calls-history",s]}),l.invalidateQueries({queryKey:["matrix-watchtower",s]})},onError:t=>F.error(t.message)});if(!s)return null;const k=Array.from(new Set((N?.rows??[]).map(t=>t.campaignName??null).filter(t=>!!t))).sort(),x=(N?.rows??[]).filter(t=>C==="all"?!0:(t.campaignName??null)===C),v=N?.total??0,g=Math.max(1,Math.ceil(v/h)),w=v===0?0:u*h+1,i=Math.min(v,u*h+(N?.rows.length??0));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(W,{value:j,onValueChange:t=>{c(t),f(0)},children:[e.jsx(K,{className:"h-7 w-[140px] text-xs",children:e.jsx(Q,{})}),e.jsxs(Y,{children:[e.jsx(A,{value:"all",children:"All"}),e.jsx(A,{value:"executed",children:"Executed"}),e.jsx(A,{value:"rejected",children:"Dismissed"}),e.jsx(A,{value:"failed",children:"Failed"}),e.jsx(A,{value:"no_op",children:"No-op"}),e.jsx(A,{value:"stale",children:"Stale"})]})]}),e.jsxs(W,{value:C,onValueChange:t=>{S(t),f(0)},children:[e.jsx(K,{className:"h-7 w-[180px] text-xs",children:e.jsx(Q,{placeholder:"All campaigns"})}),e.jsxs(Y,{children:[e.jsx(A,{value:"all",children:"All campaigns"}),k.map(t=>e.jsx(A,{value:t,className:"text-xs",children:t},t))]})]})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:N?`${w}â${i} of ${v}`:""})]}),b?e.jsx(B,{className:"h-20 w-full"}):x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No past recommendations yet."}):x.map(t=>{const y=t;return e.jsx("div",{"data-app-row":"",className:"rounded-md border bg-card/60 p-3 space-y-1.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0 flex-1",children:[y.thumbnailUrl?e.jsx("img",{src:y.thumbnailUrl,alt:"",loading:"lazy",className:"h-10 w-10 flex-shrink-0 rounded border object-cover bg-muted"}):e.jsx("div",{className:"h-10 w-10 flex-shrink-0 rounded border bg-muted/40 text-[10px] uppercase flex items-center justify-center text-muted-foreground",children:t.targetType==="ad_set"?"Set":t.targetType==="campaign"?"Camp":"Ad"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Xe,{action:t.action}),e.jsx("span",{className:"font-medium text-sm capitalize",children:t.action.replace(/_/g," ")}),e.jsx(D,{variant:"outline",className:"text-[10px]",children:t.targetType}),e.jsx(mt,{status:t.status,autoExecuted:t.autoExecuted}),t.status==="proposed"&&t.error&&t.error.includes("autopilot_spend_cap_exceeded")?e.jsx(D,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-700 dark:text-amber-300",title:t.error,children:"cap reached"}):null,t.outcome?e.jsx(ut,{outcome:t.outcome}):null,t.revertedAt?e.jsx(D,{variant:"outline",className:"text-[10px]",children:"reverted"}):null,e.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(t.executedAt??t.createdAt).toLocaleStr
1ing()})]}),y.adName||y.campaignName?e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground flex flex-wrap gap-x-3",children:[y.adName?e.jsxs("span",{className:"truncate max-w-[260px]",title:y.adName,children:["Ad: ",e.jsx("span",{className:"text-foreground",children:y.adName})]}):null,y.campaignName?e.jsxs("span",{className:"truncate max-w-[260px]",title:y.campaignName,children:["Campaign: ",e.jsx("span",{className:"text-foreground",children:y.campaignName})]}):null]}):null,t.problem?e.jsx("p",{className:"text-sm mt-1",children:t.problem}):null,t.rationale?e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:t.rationale}):null,t.error?e.jsxs("p",{className:"text-[11px] text-destructive mt-1",children:["Error: ",t.error]}):null,t.preflightReason&&(t.status==="no_op"||t.status==="stale")?e.jsxs("p",{className:"text-[11px] text-amber-600 dark:text-amber-400 mt-1",children:["Preflight: ",t.preflightReason]}):null]})]}),t.status==="executed"&&!t.revertedAt?e.jsxs(_,{size:"sm",variant:"outline",onClick:()=>d.mutate(t.id),disabled:d.isPending,className:"shrink-0",children:[e.jsx(Ts,{className:"mr-1 h-3.5 w-3.5"}),"Revert"]}):null]})},t.id)}),N&&v>h?e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums",children:["Page ",u+1," / ",g]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(_,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>f(t=>Math.max(0,t-1)),disabled:u===0||p,children:"Prev"}),e.jsx(_,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>f(t=>Math.min(g-1,t+1)),disabled:u>=g-1||p,children:"Next"})]})]}):null]})}function mt({status:s,autoExecuted:a}){return s==="executed"?e.jsx(D,{variant:"secondary",className:"text-[10px] bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",children:a?"auto":"executed"}):s==="rejected"?e.jsx(D,{variant:"outline",className:"text-[10px]",children:"dismissed"}):s==="failed"?e.jsx(D,{variant:"destructive",className:"text-[10px]",children:"failed"}):s==="no_op"?e.jsx(D,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-700 dark:text-amber-300",children:"no-op"}):s==="stale"?e.jsx(D,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-700 dark:text-amber-300",children:"stale"}):e.jsx(D,{variant:"outline",className:"text-[10px]",children:s})}function ut({outcome:s}){const a=s.status==="beat"?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30":s.status==="met"?"bg-sky-500/15 text-sky-700 dark:text-sky-300 border-sky-500/30":s.status==="missed"?"bg-rose-500/15 text-rose-700 dark:text-rose-300 border-rose-500/30":"bg-muted text-muted-foreground border-border",r=s.actual_value==null?"":` · ${s.expected_metric==="spend_saved_usd"?"$":""}${s.actual_value.toFixed(1)}${s.expected_metric?.endsWith("_pct")?"%":""}`;return e.jsxs(D,{variant:"outline",className:`text-[10px] ${a}`,title:s.expected_metric??void 0,children:[s.status,r]})}export{Ot as component};
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.