PageSourceSearch

https://trybrain.io/assets/_authenticated.assembler-BJL1huPD.js

js trybrain.io collected 2026-10-02 01:58:50 UTC 110,247 bytes, 7 lines download raw bytes

1import{a8 as kt,ad as H,ae as W,af as Y,r as A,c as S,y as he,d as G,D as B,t as N,j as e,aO as ce,cf as _t,a as E,S as Z,aP as oe,aQ as ue,aR as me,aS as we,a2 as Ue,aU as Me,l as ae,d0 as Mt,al as Ce,B as pe,a5 as vt,am as Zt,d1 as es,a9 as ts,a$ as ss,k as se,I as be,ar as re,as as le,at as ie,au as de,av as X,x as je,F as Xe,P as as,b3 as Ae,a3 as Pt,a4 as It,aT as Ft,bv as Pe,bw as Ie,bx as Fe,by as $e,bz as Te,bA as qe,bB as Oe,bC as Ee,e as $t,f as Tt,g as qt,h as Ot,i as Et,b4 as Lt,n as ns,p as rs,q as ls,A as is,bf as We,bm as ds,z as cs,be as os,L as us}from"./index-DQ05VIVn.js";import{l as ms}from"./offers.functions-DBj35TR6.js";import{o as Ut,a as Dt,b as ps,p as hs}from"./matrix-production.functions-DWP62YsO.js";import{g as xs,p as gs,c as fs,s as vs,b as bs,a as js,d as ys,r as Ns,e as ws,o as Cs,M as Be,f as As,h as Ss,i as ks,D as _s}from"./delivery-mode-toggle-RPvsZMwT.js";import{c as Ms,T as Ps,a as Is,b as Fs}from"./tooltip-CaCN6-tm.js";import{l as $s}from"./meta-lead-forms.functions-Co6_aODP.js";import{l as Ts,r as qs}from"./audiences.functions-DDGkg9Qw.js";import{s as Os}from"./cell-funnel.functions-DotSs9Fa.js";import{R as Ze}from"./rocket-Bj4ez3No.js";import{P as Le}
1from"./play-HvSauGnb.js";import{I as Rt}from"./image-CdOKPbLX.js";import{L as Ne}from"./layers-DE9tzyiz.js";import{A as Vt}from"./archive-BakprMbA.js";import{V as Es}from"./video-CH-uSKxS.js";import"./ad-copy-matrix.functions-BQCpPH-_.js";const Ls=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],et=kt("rotate-cw",Ls);const Us=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],Ds=kt("type",Us),Rs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--listImageVariants_createServerFn_handler")),zt=H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--listVariantReferences_createServerFn_handler")),Vs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--generateImageVariants_createServerFn_handler"));H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--promoteImageVariant_createServerFn_handler"));H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--promoteImageVariantGroup_createServerFn_handler"));const zs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--promoteImageVariantPicks_createServerFn_handler")),Bs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_image-variants_functions_ts--deleteImageVariant_createServerFn_handler"));function bt({workspaceId:t,jobId:n,cellId:h,title:r,triggerLabel:f="Order image"}){const[o,p]=A.useState(!1),[x,m]=A.useState(null),[k,T]=A.useState(!1),_=S(Ut),y=S(Dt),d=S(zt),u=he(),b=G({queryKey:["variant-refs",t],queryFn:()=>d({data:{workspaceId:t}}),enabled:o}).data?.refs??[],C=x,O=B({mutationFn:()=>{if(n)return _({data:{workspaceId:t,jobId:n,primaryRefId:C??void 0,quality:k?"high":"fast"}});if(h)return y({data:{workspaceId:t,cellId:h,primaryRefId:C??void 0,quality:k?"high":"fast"}});throw new Error("Missing jobId or cellId")},onSuccess:()=>{N.success("Image ordered — generating now."),u.invalidateQueries({queryKey:["pipeline-queues",t]}),p(!1)},onError:D=>N.error(D.message)});return e.jsxs(ce,{open:o,onOpenChange:p,children:[e.jsx(_t,{asChild:!0,children:e.jsxs(E,{size:"sm",className:"h-7 px-2 text-xs",title:"Pick a reference and generate this image",children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),f]})}),e.jsxs(oe,{className:"max-w-2xl",children:[e.jsxs(ue,{children:[e.jsx(me,{className:"line-clamp-1",children:r}),e.jsx(we,{children:"Pick an inspiration image to use as the style reference, then generate. Skip the picker to use your workspace default reference."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/30 p-2",children:[e.jsxs("div",{className:"text-xs font-medium",children:["Style reference",e.jsx("span",{className:"ml-2 text-[10px] font-normal text-muted-foreground",children:b.length===0?"Upload an inspiration image first — generation is disabled until a reference is picked.":C?"Click another to change.":"Required — pick the image you want this render to match."})]}),b.length>0&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:b.map(D=>{const i=D.id===C;return e.jsxs("button",{type:"button",onClick:()=>m(i?null:D.id),title:D.label??"",className:`relative h-20 w-20 shrink-0 overflow-hidden rounded-md border-2 transition ${i?"border-primary ring-2 ring-primary/40":"border-border opacity-70 hover:opacity-100"}`,children:[e.jsx("img",{src:D.url,alt:"",className:"h-full w-full object-cover"}),i&&e.jsx("span",{className:"absolute inset-x-0 bottom-0 bg-primary py-0.5 text-center text-[9px] text-primary-foreground",children:"Primary"})]},D.id)})})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2 rounded-md border bg-muted/30 p-2",children:[e.jsxs("div",{className:"min-w-0 text-[11px]",children:[e.jsx("div",{className:"font-medium text-foreground",children:"High quality (slower)"}),e.jsx("div",{className:"text-muted-foreground",children:"Off uses Nano Banana 2 — fast (~5–10s). O
1n uses Gemini 3 Pro Image — slower (~30–60s) but sticks closer to the reference."})]}),e.jsx(Ue,{checked:k,onCheckedChange:T})]})]}),e.jsxs(Me,{children:[e.jsx(E,{variant:"outline",size:"sm",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(E,{size:"sm",disabled:O.isPending||!C,title:C?void 0:"Pick a style reference first",onClick:()=>O.mutate(),children:[O.isPending?e.jsx(ae,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(Z,{className:"mr-1 h-3 w-3"}),C?"Generate image":"Pick a reference to generate"]})]})]})]})}const Qs={meta:20},Ks=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--listPipelineQueues_createServerFn_handler")),Gs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--startArcadsVslForFunnel_createServerFn_handler")),Hs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--cancelQueueItem_createServerFn_handler")),Ws=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--restartQueueItem_createServerFn_handler")),Ys=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--deleteQueueItem_createServerFn_handler")),Js=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--archiveCampaignCells_createServerFn_handler")),Xs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--listArchivedCampaignGroups_createServerFn_handler")),Zs=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-queues_functions_ts--unarchiveCampaignCells_createServerFn_handler")),jt=["1:1","9:16","16:9"];function ea({workspaceId:t,sourceJobId:n,title:h,sourceAspect:r=null}){const[f,o]=A.useState(!1),[p,x]=A.useState(null),[m,k]=A.useState(null),[T,_]=A.useState(!1),[y,d]=A.useState(new Set);A.useEffect(()=>{f||d(new Set)},[f]);const u=S(Rs),g=S(Vs),b=S(zs),C=S(zt),O=S(Bs),D=S(Mt),i=he(),M=G({queryKey:["image-variants",n],queryFn:()=>u({data:{workspaceId:t,sourceJobId:n}}),enabled:f,refetchInterval:f?3e3:!1}),I=G({queryKey:["variant-refs",t],queryFn:()=>C({data:{workspaceId:t}}),enabled:f}),$=G({queryKey:["optimization-settings",t],queryFn:()=>D({data:{workspaceId:t}}),enabled:f,staleTime:6e4}).data?.delivery_mode??"advantage_plus",c=r??M.data?.variants?.find(v=>v.aspect)?.aspect??null,s=c?[c]:$==="advantage_plus"?jt:["1:1"],j=B({mutationFn:()=>g({data:{workspaceId:t,sourceJobId:n,count:1,aspects:s,primaryRefId:m??void 0,quality:T?"high":"fast"}}),onSuccess:v=>{N.success(`Queued ${v.queued} variant${v.queued===1?"":"s"} — generating in the background.`),i.invalidateQueries({queryKey:["image-variants",n]})},onError:v=>N.error(v instanceof Error?v.message:String(v))}),F=B({mutationFn:async v=>{const z=await Promise.allSettled(v.map(te=>b({data:{workspaceId:t,variantIds:[te]}}))),V=z.filter(te=>te.status==="fulfilled").length,ve=z.length-V;return{ok:V,failed:ve}},onSuccess:({ok:v,failed:z})=>{v>0&&N.success(`Staged ${v} image${v===1?"":"s"} in Assembler. Push from Assembler when ready.`),z>0&&N.error(`${z} pick${z===1?"":"s"} failed to stage.`),d(new Set),i.invalidateQueries({queryKey:["image-variants",n]}),i.invalidateQueries({queryKey:["pipeline-queues",t]})},onError:v=>N.error(v instanceof Error?v.message:String(v))}),U=B({mutationFn:v=>O({data:{workspaceId:t,variantId:v}}),onSuccess:()=>{N.success("Variant removed."),i.invalidateQueries({queryKey:["image-variants",n]})},onError:v=>N.error(v instanceof Error?v.message:String(v))}),Q=M.data?.variants??[],ne=M.data?.canPromote??!1,w=I.data?.refs??[],R=m,J=Array.from(y),ee=J.length,xe=v=>d(z=>{const V=new Set(z);return V.has(v)?V.delete(v):V.add(v),V});return e.jsxs(ce,{open:f,onOpenChange:o,children:[e.jsx(_t,{asChild:!0,children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs",children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),"Variants"]})}),e.jsxs(oe,{className:"flex max-h-[85vh] w-[min(96vw,64rem)] max-w-4xl flex-col overflow-hidden",onInteractOutside:v=>{v.target?.closest?.("[data-sonner-toaster], [data-sonner-toast]")&&v.preventDefault()},children:[e.jsxs(ue,{children:[e.jsx(me,{className:"line-clamp-1",children:h}),e.jsx(we,{children:"Order more image renders for this ad using the matrix copy and your inspiration images. Picking one stages a new ad in Assembler — it does NOT push to Meta. Push from Assembler when you're ready."})]}),e.jsxs("div",{className:"min-h-0 space-y-3 overflow-y-auto pr-1",children:[w.length>0&&e.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/30 p-2",children:[e.jsxs("div",{className:"text-xs font-medium",children:["Style reference",e.jsx("span",{className:"ml-2 text-[10px] font-normal text-muted-foreground",children:R?"Click another to change for this generation.":"Required — pick the image whose style you want this render to follow."})]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:w.map(v=>{const z=v.id===R;return e.jsxs("button",{type:"button",onClick:()=>k(v.id),title:v.label??"",className:`relative h-16 w-16 shrink-0 overflow-hidden rounded-md border-2 transition ${z?"border-primary ring-2 ring-primary/40":"border-border opacity-70 hover:opacity-100"}`,children:[e.jsx("img",{src:v.url,alt:"",className:"h-full w-full object-cover"}),z&&e.jsx("span",{className:"absolute inset-x-0 bottom-0 bg-primary py-0.5 text-center text-[9px] text-primary-foreground",children:"Primary"})]},v.id)})}),e.jsxs("div",{className:"flex items-start justify-between gap-2 rounded-md border bg-background/60 p-2",children:[e.jsxs("div",{className:"min-w-0 text-[10px]",children:[e.jsx("div",{className:"font-medium text-foreground",children:"High quality (slower)"}),e.jsx("div",{className:"text-muted-foreground",children:"Off uses Nano Banana 2 — fast (~5–10s per render). On uses Gemini 3 Pro Image — slower (~30–60s) but sticks closer to the reference."})]}),e.jsx(Ue,{checked:T,onCheckedChange:_})]})]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 text-xs text-muted-foreground",children:[Q.length," variant",Q.length===1?"":"s",!ne&&" · push the parent ad to Meta first so staged variants have a campaign to land in"]}),e.jsxs(E,{size:"sm",className:"shrink-0",disabled:j.isPending||!R,title:R?void 0:"Pick a style reference first",onClick:()=>j.mutate(),children:[j.isPending?e.jsx(ae,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(Z,{className:"mr-1 h-3 w-3"}),R?`Generate ${s.length===1?"1 more":`${s.length} (one per aspect)`}`:"Pick a reference to generate"]})]}),Q.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:'No variants yet. Click "Generate 1 more" to create your first render (~5–15s).'}):e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4",children:Q.map(v=>e.jsxs("div",{className:"relative space-y-2 rounded-md border bg-muted/30 p-2",children:[!v.promoted&&e.jsx("button",{type:"button",title:"Remove this variant",disabled:U.isPending&&U.variables===v.id,onClick:z=>{z.stopPropagation(),U.mutate(v.id)},className:"absolute top-1 right-1 z-10 rounded-full bg-background/90 border p-0.5 text-muted-foreground hover:text-destructive hover:border-destructive transition",children:U.isPending&&U.variables===v.id?e.jsx(ae,{className:"h-3 w-3 animate-spin"}):e.jsx(Ce,{className:"h-3 w-3"})}),e.jsx("button",{type:"button",className:"block w-full overflow-hidden rounded-md border bg-muted aspect-square",disabled:!v.outputUrl,onClick:()=>v.outputUrl&&x(v.outputUrl),children:v.outputUrl?e.jsx("img",{src:v.outputUrl,alt:"",className:"h-full w-full object-cover"}):v.status==="failed"?e.jsx("span",{className:"text-xs text-destructive",children:"Failed"}):e.jsx(ae,{className:"h-5 w-5 animate-spin text-muted-foreground mx-auto my-auto"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"flex min-w-0 items-center justify-between gap-1",children:v.promoted?e.jsxs(pe,{variant:"default",className:"gap-1 text-[10px]",children:[e.jsx(vt,{className:"h-3 w-3"})," Staged"]}):e.jsx("span",{className:"text-[10px] text-muted-foreground",children:v.aspect??""})}),!v.promoted&&v.outputUrl&&v.aspect?(()=>{const z=y.has(v.id);return e.jsxs("label",{className:"flex items-center gap-1 cursor-pointer text-[10px] text-muted-foreground hover:text-foreground",children:[e.jsx("input",{type:"checkbox",className:"h-3 w-3 accent-primary",checked:z,onChange:()=>xe(v.id)}),z?`Picked (${v.aspect})`:`Pick for ${v.aspect}`]})})():null]}),v.errorMessage&&e.jsx("p",{className:"line-clamp-2 text-[10px] text-destructive",children:v.errorMessage})]},v.id))})]}),e.jsx("div",{className:"border-t bg-background/95 px-1 pt-3 mt-1",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Picked:"})," ",jt.map((v,z)=>{const V=J.filter(ve=>Q.find(te=>te.id===ve&&te.aspect===v)).length;return e.jsxs("span",{children:[z>0?" · ":"",v," ",V>0?`×${V}`:"—"]},v)}),ne?null:e.jsx("span",{className:"ml-2 italic",children:"· parent ad isn't on Meta yet — staged images will wait in Assembler until you push the parent."})]}),e.jsxs(E,{size:"sm",disabled:ee===0||F.isPending,onClick:()=>F.mutate(J),children:[F.isPending?e.jsx(ae,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(vt,{className:"mr-1 h-3 w-3"}),ee===0?"Pick images to stage":`Stage ${ee} image${ee===1?"":"s"} in Assembler`]})]})}),e.jsx(ce,{open:!!p,onOpenChange:v=>!v&&x(null),children:e.jsxs(oe,{className:"max-w-3xl",children:[e.jsx(ue,{children:e.jsx(me,{children:"Preview"})}),p&&e.jsx("img",{src:p,alt:"",className:"max-h-[70vh] w-full rounded-md object-contain"})]})})]})]})}const ta=H({method:"POST"}).middleware([W]).handler(Y("src_lib_pipeline-variants_functions_ts--spawnArcadsVariant_createServerFn_handler")),sa=H({method:"POST"}).middleware([W]).handler(Y("src_lib_matrix-consolidate_functions_ts--consolidateMatrixCellPushes_createServerFn_handler")),aa={none:"bg-muted text-muted-foreground",queued:"bg-muted-foreground
1/40 text-foreground",processing:"bg-blue-500 text-white animate-pulse",completed:"bg-emerald-500 text-white",failed:"bg-destructive text-destructive-foreground",blocked:"bg-amber-500 text-white"},yt={none:"—",queued:"Queued",processing:"Running",completed:"Done",failed:"Failed",blocked:"Blocked"};function na({label:t,part:n}){const h=e.jsxs("div",{className:"space-y-0.5 text-xs",children:[e.jsxs("div",{className:"font-medium",children:[t,": ",yt[n.status]]}),n.detail&&e.jsx("div",{className:"text-muted-foreground",children:n.detail}),n.message&&e.jsx("div",{className:"max-w-xs whitespace-pre-wrap text-destructive-foreground/90",children:n.message}),n.updatedAt&&e.jsx("div",{className:"text-muted-foreground",children:new Date(n.updatedAt).toLocaleString()})]});return e.jsx(Ms,{delayDuration:150,children:e.jsxs(Ps,{children:[e.jsx(Is,{asChild:!0,children:e.jsx("span",{className:Zt("inline-flex h-6 min-w-[2.5rem] items-center justify-center rounded-full px-2 text-[10px] font-semibold uppercase tracking-wide",aa[n.status]),children:n.status==="none"?"—":n.detail??yt[n.status]})}),e.jsx(Fs,{children:h})]})})}function Nt(t){switch(t){case"unaware":case"problem_aware":return"cold";case"solution_aware":case"product_aware":return"warm";case"most_aware":return"hot";default:return"cold"}}const ra=[{value:"OUTCOME_LEADS",label:"Leads (optimize for conversions)"},{value:"OUTCOME_SALES",label:"Sales (offsite conversions)"},{value:"OUTCOME_TRAFFIC",label:"Traffic (link clicks)"},{value:"OUTCOME_ENGAGEMENT",label:"Engagement"},{value:"OUTCOME_AWARENESS",label:"Awareness (reach)"},{value:"OUTCOME_APP_PROMOTION",label:"App promotion"}],la=["LEARN_MORE","SHOP_NOW","SIGN_UP","SUBSCRIBE","BOOK_TRAVEL","GET_QUOTE","CONTACT_US","DOWNLOAD","APPLY_NOW","GET_OFFER","ORDER_NOW","WATCH_MORE","SEE_MENU"],ia=[{id:"facebook/feed",label:"Facebook Feed"},{id:"instagram/stream",label:"Instagram Feed"},{id:"instagram/explore_home",label:"Instagram Explore"},{id:"instagram/reels",label:"Instagram Reels"},{id:"facebook/instream_video",label:"Facebook In-stream Video"},{id:"facebook/story",label:"Facebook Stories"},{id:"instagram/story",label:"Instagram Stories"},{id:"facebook/marketplace",label:"Facebook Marketplace"},{id:"audience_network/classic",label:"Audience Network"},{id:"messenger/messenger_home",label:"Messenger Inbox"}],wt=/\/architect(\/|$|\?)/i;function Qe({label:t,hint:n,checked:h,onCheckedChange:r}){return e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs font-medium",children:t}),n&&e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:n})]}),e.jsx(Ue,{checked:h,onCheckedChange:r})]})}function Ct({ids:t,options:n,onChange:h,placeholder:r}){const f=n.filter(o=>!t.includes(o.id));return e.jsxs("div",{className:"space-y-1.5",children:[t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:t.map(o=>{const p=n.find(x=>x.id===o);return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary border border-primary/30 px-2 py-0.5 text-[10px]",children:[e.jsx("span",{className:"truncate max-w-[140px]",children:p?.label??o}),e.jsx("button",{type:"button",className:"hover:text-foreground",onClick:()=>h(t.filter(x=>x!==o)),"aria-label":"Remove audience",children:"×"})]},o)})}),f.length>0?e.jsxs(re,{value:"__add__",onValueChange:o=>{!o||o==="__add__"||t.includes(o)||h([...t,o])},children:[e.jsx(le,{className:"h-8 text-[11px]",children:e.jsx(ie,{placeholder:r})}),e.jsxs(de,{className:"max-h-72",children:[e.jsx(X,{value:"__add__",disabled:!0,children:r}),f.map(o=>e.jsx(X,{value:o.id,children:o.label},o.id))]})]}):n.length===0?e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"No synced audiences yet."}):e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"All audiences selected."})]})}function da(t){let n=(t??"").trim();n=n.replace(/^(?:TRAFFIC|SALES|LEADS|ENGAGE|AWARE|APP)\s+·\s+[^·]+·\s+/i,"");const h=/\s+·\s+(?:pushed\s+)?\d{4}-\d{2}(?:-\d{2})?\s*$/i;for(;h.test(n);)n=n.replace(h,"");return n.trim()}function tt(t){const{open:n,onOpenChange:h,workspaceId:r,cellId:f,cellTitle:o}=t,p=t.cellIds&&t.cellIds.length>0?t.cellIds:[f],x=p.slice().sort().join("|"),m=he(),k=S(xs),T=S(gs),_=S(fs),y=S(vs),d=S(bs),u=S($s),g=S(Ts),b=S(qs),C=S(Os),O=S(Mt),D=S(es),i=`pipeline-launch-form::${r}`,M=`pipeline-launch-delivery-mode::${r}`,I=G({queryKey:["matrix-push-defaults",r],queryFn:()=>k({data:{workspaceId:r}}),enabled:n,staleTime:0,refetchOnMount:"always"}),q=G({queryKey:["optimization-settings",r],queryFn:()=>O({data:{workspaceId:r}}),enabled:n,staleTime:3e4}),[$,c]=A.useState("advantage_plus");A.useEffect(()=>{const l=q.data?.delivery_mode;l&&c(l)},[q.data]);const[a,s]=A.useState({campaignName:"",adAccountId:"",objective:"OUTCOME_LEADS",leadCaptureMethod:"appointment",leadGenFormId:"",budget:20,landingUrl:t.defaultLandingUrl??"",cta:"LEARN_MORE",countries:"US",ageMin:18,ageMax:65,gender:"all",savedAudienceColdIds:[],savedAudienceWarmIds:[],savedAudienceHotIds:[],excludedAudienceIds:[],advantagePlacements:!0,advantageAudience:!0,useCbo:!0,manualPlacements:["facebook/feed","instagram/stream","instagram/explore_home"],saveDefaults:!1}),[j,F]=A.useState(!1);A.useEffect(()=>{if(!n){F(!1);return}const l=I.data;if(j||!l)return;const P=(l.accounts??[]).map(L=>L.id),K=L=>L&&P.includes(L)?L:l.adAccountId&&P.includes(l.adAccountId)?l.adAccountId:P.length>0?P[0]:l.adAccountId??"";s(L=>
1({...L,adAccountId:K(L.adAccountId),campaignName:L.campaignName||da(t.pipelineCampaignName?.trim()||o),landingUrl:L.landingUrl||(wt.test(l.defaultLandingUrl??"")?"":l.defaultLandingUrl||t.defaultLandingUrl||""),cta:l.defaultCta||L.cta,countries:(l.defaultCountries??[]).join(",")||L.countries,ageMin:l.defaultAgeMin??L.ageMin,ageMax:l.defaultAgeMax??L.ageMax,gender:l.defaultGenders&&l.defaultGenders.length===1?l.defaultGenders[0]:"all"})),F(!0)},[n,I.data,j,o,t.defaultLandingUrl]);const[U,Q]=A.useState(!1);A.useEffect(()=>{if(!n){Q(!1);return}if(!(U||!j)&&!(typeof window>"u")){try{const l=window.localStorage.getItem(i);if(l){const K=JSON.parse(l);s(L=>({...L,...K,saveDefaults:!1}))}const P=window.localStorage.getItem(M);(P==="advantage_plus"||P==="manual")&&c(P)}catch{}Q(!0)}},[n,j,U,i,M]);const ne=G({queryKey:["matrix-push-funnel-urls",r,x],queryFn:()=>C({data:{workspaceId:r,cellIds:p}}),enabled:n}),w=p.length===1?ne.data?.[p[0]]?.url??null:p.map(l=>ne.data?.[l]?.url).find(Boolean)??null;A.useEffect(()=>{!n||!w||s(l=>{const P=l.landingUrl.trim();if(P===w)return l;const K=!!I.data?.defaultLandingUrl&&P===I.data.defaultLandingUrl,L=wt.test(P);return P&&!K&&!L?l:{...l,landingUrl:w}})},[n,w,I.data?.defaultLandingUrl]);const J=(G({queryKey:["meta-audiences",r],queryFn:()=>g({data:{workspaceId:r}}),enabled:n}).data??[]).map(l=>({id:l.audience_meta_id,label:`${l.name} · ${l.audience_type}${l.approximate_count?` · ${Number(l.approximate_count).toLocaleString()}`:""}`})),ee=B({mutationFn:()=>b({data:{workspaceId:r}}),onSuccess:l=>{N.success(`Synced ${l.synced} audiences from Meta`),m.invalidateQueries({queryKey:["meta-audiences",r]})},onError:l=>N.error(l.message)}),xe=G({queryKey:["meta-lead-forms",r],queryFn:()=>u({data:{workspaceId:r}}),enabled:n&&a.objective==="OUTCOME_LEADS"&&a.leadCaptureMethod==="leadform",staleTime:6e4}),v=G({queryKey:["matrix-push-precheck",r,x,a.leadCaptureMethod],queryFn:()=>d({data:{workspaceId:r,cellIds:p,leadCaptureMethod:a.leadCaptureMethod}}),enabled:n,staleTime:1e4}),z=G({queryKey:["matrix-bundle-preview",r,x],queryFn:()=>ts(()=>Promise.resolve().then(()=>xa),void 0).then(l=>l.previewMatrixBundles({data:{workspaceId:r,cellIds:p}})),enabled:n,staleTime:1e4}),V=I.data,ve=V&&(!V.hasMeta||!V.hasPage),te=V?.historical,Kt=V?.targetCpl??null,Ve=te?.recommendedEvent??"blended",Se=te?.recommendedCpl??null??te?.cpl90??te?.cpl365??Kt??null,Gt=Ve==="appointment"?"your appointment CPA":Ve==="lp_lead"?"your landing-page lead CPL":Ve==="leadform"?"your lead-form CPL":te?.cpl90!=null?"your 90d blended CPL":te?.cpl365!=null?"your 365d blended CPL":"target CPL",ye=Se!=null&&Se>0?Math.max(5,Math.ceil(Se*50/7)):null,nt=l=>{const P=l==="cold"?a.savedAudienceColdIds:l==="warm"?a.savedAudienceWarmIds:a.savedAudienceHotIds;return Math.max(1,P.length)},ge=t.cells?.length?t.cells:p.map(l=>({cellId:l,awarenessLevel:null,formatType:null})),fe=ge.reduce((l,P)=>l+nt(Nt(P.awarenessLevel)),0),Ht=z.data??{},rt=Math.max(1,Number(V?.videosPerAdSet??3)),lt=!!t.bundleId,it=ge.map(l=>{if(lt)return 1;const P=Ht[l.cellId];return P&&P.predictedAdCount>0?P.predictedAdCount:rt}),Wt=it.reduce((l,P)=>l+P,0),dt=ge.length>0?Math.round(Wt/ge.length):rt,ke=ge.reduce((l,P,K)=>l+it[K]*nt(Nt(P.awarenessLevel)),0),ct=a.budget*fe,[ot,ut]=A.useState(null),[mt,pt]=A.useState(!1),Yt=()=>a.countries.split(",").map(P=>P.trim().toUpperCase()).filter(P=>P.length===2).length===0?"Add at least one country code (e.g. US)":a.campaignName.trim()?a.landingUrl.trim()?a.budget<=0?"Daily budget must be > 0":a.ageMin>a.ageMax?"Age min must be ≤ age max":a.objective==="OUTCOME_LEADS"&&a.leadCaptureMethod==="leadform"&&!a.leadGenFormId?"Pick an Instant Form to attach.":null:"Landing URL is required":"Campaign name is required",Jt=async()=>{try{await D({data:{workspaceId:r,delivery_mode:$}})}catch(L){console.warn("[launch] failed to persist delivery_mode",L.message)}const l=a.countries.split(",").map(L=>L.trim().toUpperCase()).filter(L=>L.length===2);if(l.length===0)throw new Error("Add at least one country code (e.g. US)");if(!a.campaignName.trim())throw new Error("Campaign name is required");if(!a.landingUrl.trim())throw new Error("Landing URL is required");if(a.budget<=0)throw new Error("Daily budget must be > 0");if(a.ageMin>a.ageMax)throw new Error("Age min must be ≤ age max");if(a.objective==="OUTCOME_LEADS"&&a.leadCaptureMethod==="leadform"&&!a.leadGenFormId)throw new Error("Pick an Instant Form to attach.");const P=a.gender==="all"?[]:[a.gender],K=t.bundleId?await _({data:{workspaceId:r,bundleId:t.bundleId,dailyBudgetUsd:a.budget,campaignName:a.campaignName.trim(),adAccountId:a.adAccountId||V?.adAccountId||null,landingUrl:a.landingUrl.trim()||V?.defaultLandingUrl||null,objective:a.objective,cta:a.cta,countries:l,ageMin:a.ageMin,ageMax:a.ageMax,genders:P,advantageAudience:a.advantageAudience,advantagePlacements:a.advantagePlacements,manualPlacements:a.advantagePlacements?[]:a.manualPlacements,useCbo:a.useCbo,savedAudienceColdIds:a.savedAudienceColdIds,savedAudienceWarmIds:a.savedAudienceWarmIds,savedAudienceHotIds:a.savedAudienceHotIds,excludedAudienceIds:a.excludedAudienceIds,leadCaptureMethod:a.leadCaptureMethod,leadGenFormId:a.leadGenFormId||null}}):await T({data:{workspaceId:r,cellIds:p,campaignName:a.campaignName.trim(),objective:a.objective,adSetDailyBudgetUsd:a.budget,landingUrl:a.landingUrl.trim(),cta:a.cta,countries:l,includeVariations:!0,ageMin:a.ageMin,ageMax:a.ageMax,genders:P,advantageAudience:a.advantageAudience,advantagePlacements:a.advantagePlacements,manualPlacements:a.advantagePlacements?[]:a.manualPlacements,splitByAwareness:!1,useCbo:a.useCbo,adAccountIdOverride:a.adAccountId||null,savedAudienceColdIds:a.savedAudienceColdIds,savedAudienceWarmIds:a.savedAudienceWarmIds,savedAudienceHotIds:a.savedAudienceHotIds,excludedAudienceIds:a.excludedAudienceIds,leadCaptureMethod:a.leadCaptureMethod,leadGenFormId:a.leadGenFormId||void 0}});if(a.saveDefaults)try{await y({data:{workspaceId:r,landingUrl:a.landingUrl.trim(),cta:a.cta,countries:l,ageMin:a.ageMin,ageMax:a.ageMax,genders:P,savedAudienceCold:a.savedAudienceColdIds[0]??null,savedAudienceWarm:a.savedAudienceWarmIds[0]??null,savedAudienceHot:a.savedAudienceHotIds[0]??null}})}catch(L){console.warn("[pipeline-launch] saveDefaults failed",L)}return K},Xt=()=>{const l=Yt();if(l){ut(l);return}if(ut(null),typeof window<"u")try{const{saveDefaults:K,...L}=a;window.localStorage.setItem(i,JSON.stringify(L)),window.localStorage.setItem(M,$)}catch{}const P=p.length;N.info(`Pushing ${P} asset${P===1?"":"s"} to Meta — track per-asset progress in the Pipeline queue below.`),pt(!0),Jt().then(()=>{N.success(`Meta campaign created — ${P} ad${P===1?"":"s"} queued. The Meta push dot will turn green → "Done" as they land.`),m.invali
1dateQueries({queryKey:["pipeline-rows",r]}),m.invalidateQueries({queryKey:["pipeline-queues",r]})}).catch(K=>{console.error("[pipeline-launch] push failed",K.message??K),N.error(K.message??"Push to Meta failed"),m.invalidateQueries({queryKey:["pipeline-rows",r]}),m.invalidateQueries({queryKey:["pipeline-queues",r]})}).finally(()=>{setTimeout(()=>pt(!1),3e4)}),h(!1)};A.useEffect(()=>{if(!mt)return;const l=setInterval(()=>{m.invalidateQueries({queryKey:["pipeline-queues",r]}),m.invalidateQueries({queryKey:["pipeline-rows",r]})},2e3);return()=>clearInterval(l)},[mt,m,r]);const ze=v.data,_e=[];ze&&(ze.cellsWithoutFunnel>0&&_e.push("This cell has no landing funnel attached — visitors will land on the fallback URL."),a.leadCaptureMethod==="appointment"&&ze.funnelsMissingCalendar>0&&_e.push("Funnel is set to appointment booking but has no calendar embed. Add a calendar in the funnel editor first."));const ht=xe.data,xt=ht?.error??null,gt=ht?.forms??[],ft=ye!=null&&a.budget===ye&&a.useCbo;return e.jsx(ce,{open:n,onOpenChange:h,children:e.jsxs(oe,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ue,{children:[e.jsx(me,{children:"Configure & push to Meta"}),e.jsxs(we,{children:["Launches ",e.jsx("strong",{children:o})," to Meta as a paused campaign. After pressing Push, this dialog closes and Pipeline shows each ad set/ad queue row with progress."]})]}),I.isLoading?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading workspace defaults…"}):ve?e.jsx("p",{className:"text-sm text-destructive",children:V?.hasMeta?"Facebook Page ID missing. Add it in Settings → Workspace.":"Meta is not connected. Connect it in Settings → Workspace first."}):e.jsxs("div",{className:"space-y-3",children:[ye!=null?e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded border bg-muted/30 px-2 py-1.5 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Recommended budget:"," ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",ye,"/day per ad set"]})," ",e.jsxs("span",{className:"text-[10px]",children:["($",Se," × ",Gt," × 50 ÷ 7, learning-phase rule)"]})]}),e.jsxs(E,{type:"button",size:"sm",className:"h-7 px-2 text-[11px]",disabled:ft,onClick:()=>s(l=>({...l,budget:ye,useCbo:!0})),children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),ft?"AI plan applied":"Apply AI plan"]})]}):e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Not enough historical conversions yet. Set a ",e.jsx("strong",{children:"target CPL"})," in Settings → Workspace, or connect Meta + CRM events to build a baseline."]}),e.jsxs("div",{className:"rounded-md border border-primary/30 bg-primary/5 p-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-foreground",children:"Meta launch plan"}),e.jsxs("div",{className:"mt-2 grid grid-cols-4 gap-2",children:[e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Campaigns"}),e.jsx("div",{className:"text-sm font-semibold text-foreground",children:"1"})]}),e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Ad sets"}),e.jsx("div",{className:"text-sm font-semibold text-foreground",children:fe})]}),e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Ads"}),e.jsx("div",{className:"text-sm font-semibold text-foreground",children:ke})]}),e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Daily budget"}),e.jsxs("div",{className:"text-sm font-semibold text-foreground",children:["$",ct.toLocaleString()]})]})]}),e.jsxs("div",{className:"mt-1.5 text-[10px] leading-snug text-muted-foreground",children:[ge.length," cell",ge.length===1?"":"s"," × selected tier audiences = ",fe," ad set",fe===1?"":"s",".",lt?` Advantage+ bundle = 1 DCO ad per ad set (all videos/images/copy ride inside it) → ${ke} ad${ke===1?"":"s"} total.`:z.isLoading?" Counting produced assets…":` Each cell ships every produced video and image as its own ad (~${dt} ad${dt===1?"":"s"} per ad set on average).`]})]}),ot&&e.jsx("div",{className:"rounded border border-destructive/40 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive",children:ot}),_e.length>0&&e.jsx("div",{className:"rounded border border-amber-500/40 bg-amber-500/10 px-2 py-1.5 text-[11px] text-amber-900 dark:text-amber-200",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(ss,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("ul",{className:"space-y-1",children:_e.map((l,P)=>e.jsx("li",{children:l},P))})]})}),e.jsxs("div",{className:"space-y-3 rounded-md border border-border/60 bg-background/40 p-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Essentials"}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Campaign name"}),e.jsx(be,{value:a.campaignName,onChange:l=>s({...a,campaignName:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Ad account"}),(V?.accounts?.length??0)>0?e.jsxs(re,{value:a.adAccountId||V?.adAccountId||"",onValueChange:l=>s({...a,adAccountId:l}),children:[e.jsx(le,{children:e.jsx(ie,{placeholder:"Pick an ad account"})}
1),e.jsx(de,{children:V.accounts.map(l=>e.jsxs(X,{value:l.id,children:[l.name," · ",l.id,l.currency?` · ${l.currency}`:""]},l.id))})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:V?.adAccountId?`Using ${V.adAccountId} (workspace default).`:"No connected ad accounts. Connect one in Settings → Workspace."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Landing URL (UTMs auto-injected)"}),e.jsx(be,{placeholder:"https://yoursite.com/offer",value:a.landingUrl,onChange:l=>s({...a,landingUrl:l.target.value})}),w&&a.landingUrl!==w&&e.jsx("button",{type:"button",className:"mt-1 text-[10px] text-primary hover:underline",onClick:()=>s({...a,landingUrl:w}),children:"Use this cell's funnel URL"})]})]}),e.jsxs("div",{className:"space-y-3 rounded-md border border-border/60 bg-background/40 p-3",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Objective & conversion"}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Campaign objective"}),e.jsxs(re,{value:a.objective,onValueChange:l=>s({...a,objective:l}),children:[e.jsx(le,{children:e.jsx(ie,{})}),e.jsx(de,{children:ra.map(l=>e.jsx(X,{value:l.value,children:l.label},l.value))})]})]}),a.objective==="OUTCOME_LEADS"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Lead capture method"}),e.jsxs(re,{value:a.leadCaptureMethod,onValueChange:l=>s({...a,leadCaptureMethod:l}),children:[e.jsx(le,{children:e.jsx(ie,{})}),e.jsxs(de,{children:[e.jsx(X,{value:"appointment",children:"Appointment booking (funnel calendar)"}),e.jsx(X,{value:"lp_lead",children:"Landing-page lead form (funnel form)"}),e.jsx(X,{value:"leadform",children:"Instant Form (Meta lead gen on-platform)"})]})]})]}),a.leadCaptureMethod==="leadform"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Meta Instant Form"}),xe.isLoading?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Loading forms…"}):xt?e.jsx("p",{className:"text-[11px] text-destructive",children:xt}):gt.length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No Instant Forms found on the connected Page."}):e.jsxs(re,{value:a.leadGenFormId,onValueChange:l=>s({...a,leadGenFormId:l}),children:[e.jsx(le,{children:e.jsx(ie,{placeholder:"Pick an Instant Form"})}),e.jsx(de,{children:gt.map(l=>e.jsxs(X,{value:l.id,children:[l.name,l.status?` · ${l.status}`:""]},l.id))})]})]})]})]}),e.jsxs("details",{className:"rounded-md border border-border/60 group",children:[e.jsxs("summary",{className:"cursor-pointer list-none px-3 py-2 text-xs font-medium flex items-center justify-between hover:bg-muted/40",children:[e.jsxs("span",{children:["Targeting"," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["(",a.countries," · ",a.ageMin,"–",a.ageMax," · ",a.gender,")"]})]}),e.jsx("span",{className:"text-muted-foreground text-[10px] group-open:hidden",children:"edit"})]}),e.jsxs("div",{className:"space-y-3 border-t p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Countries (comma-separated ISO codes)"}),e.jsx(be,{placeholder:"US, CA",value:a.countries,onChange:l=>s({...a,countries:l.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Age min"}),e.jsx(be,{type:"number",min:13,max:65,value:a.ageMin,onChange:l=>s({...a,ageMin:Number(l.target.value)||18})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Age max"}),e.jsx(be,{type:"number",min:13,max:65,value:a.ageMax,onChange:l=>s({...a,ageMax:Number(l.target.value)||65})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Gender"}),e.jsxs(re,{value:a.gender,onValueChange:l=>s({...a,gender:l}),children:[e.jsx(le,{children:e.jsx(ie,{})}),e.jsxs(de,{children:[e.jsx(X,{value:"all",children:"All"}),e.jsx(X,{value:"male",children:"Male"}),e.jsx(X,{value:"female",children:"Female"})]})]})]})]}),e.jsxs("div",{className:"rounded-md border border-border/60 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Saved Audiences (optional, by awareness tier)"}),e.jsx(E,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[11px]",onClick:()=>ee.mutate(),disabled:ee.isPending,children:ee.isPending?"Syncing…":"Sync from Meta"})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["Pick one or more synced Saved Audiences per tier. The push creates ",e.jsx("b",{children:"one ad set per audience"})," in the cell's tier so you can compare CPL per audience. Leave a tier empty to fall back to the geo/age/gender targeting above."]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:["cold","warm","hot"].map(l=>{const P=l==="cold"?"savedAudienceColdIds":l==="warm"?"savedAudienceWarmIds":"savedAudienceHotIds",K=a[P];return e.jsxs("div",{className:"space-y-1.5 rounded-md border border-border/60 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-[11px] capitalize font-medium",children:l}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[K.length," selected"]})]}),e.jsx(Ct,{ids:K,options:J,onChange:L=>s({...a,[P]:L}),placeholder:"Add audience…"})]},l)})})]}),e.jsxs("div",{className:"rounded-md border border-border/60 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Excluded audie
1nces"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:"Always excluded from every ad set in this push (e.g. existing customers, employees)."}),e.jsx(Ct,{ids:a.excludedAudienceIds,options:J,onChange:l=>s({...a,excludedAudienceIds:l}),placeholder:"Exclude an audience…"})]})]})]}),e.jsxs("details",{className:"rounded-md border border-border/60 group",children:[e.jsxs("summary",{className:"cursor-pointer list-none px-3 py-2 text-xs font-medium flex items-center justify-between hover:bg-muted/40",children:[e.jsxs("span",{children:["Delivery"," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["($",a.budget,"/day · ",a.cta.replace(/_/g," ")," ·"," ",a.advantagePlacements?"Advantage+ placements":"manual",")"]})]}),e.jsx("span",{className:"text-muted-foreground text-[10px] group-open:hidden",children:"edit"})]}),e.jsxs("div",{className:"space-y-3 border-t p-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"CTA"}),e.jsxs(re,{value:a.cta,onValueChange:l=>s({...a,cta:l}),children:[e.jsx(le,{children:e.jsx(ie,{})}),e.jsx(de,{children:la.map(l=>e.jsx(X,{value:l,children:l.replace(/_/g," ")},l))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Daily budget per ad set (USD)"}),e.jsx(be,{type:"number",min:1,value:a.budget,onChange:l=>s({...a,budget:Number(l.target.value)||0})}),e.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:["Est. daily total: $",ct.toLocaleString()," ·"," ",fe," ad set",fe===1?"":"s"]})]})]}),e.jsx(Qe,{label:"Advantage+ Audience",hint:"Lets Meta expand beyond your targeting. Auto-skipped on tiers with a Saved Audience (mixing both hurts performance).",checked:a.advantageAudience,onCheckedChange:l=>s({...a,advantageAudience:l})}),e.jsxs("div",{className:"rounded-md border border-primary/30 bg-primary/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs font-medium",children:"Variant delivery mode"}),e.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:$==="advantage_plus"?"Advantage+ — multiple aspect variants bundle into ONE ad. Meta auto-picks the right shape per placement. Recommended for most accounts (~30% better ROAS in Meta's published benchmarks).":"Manual — each aspect variant becomes its own ad. Use for deliberate creative split-testing."})]}),e.jsx(Ue,{checked:$==="advantage_plus",onCheckedChange:l=>c(l?"advantage_plus":"manual")})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",onClick:()=>c("advantage_plus"),className:`rounded-full border px-2 py-1 text-[10px] transition ${$==="advantage_plus"?"border-primary bg-primary text-primary-foreground":"border-border text-muted-foreground"}`,children:"Advantage+ (bundle)"}),e.jsx("button",{type:"button",onClick:()=>c("manual"),className:`rounded-full border px-2 py-1 text-[10px] transition ${$==="manual"?"border-primary bg-primary text-primary-foreground":"border-border text-muted-foreground"}`,children:"Manual (split)"})]})]}),e.jsx(Qe,{label:"Advantage+ Placements",hint:"Off = manual placements (pick below). On = Meta picks all placements.",checked:a.advantagePlacements,onCheckedChange:l=>s({...a,advantagePlacements:l})}),!a.advantagePlacements&&e.jsxs("div",{className:"rounded-md border border-border/60 p-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Manual placements"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:ia.map(l=>{const P=a.manualPlacements.includes(l.id);return e.jsxs("label",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx(je,{checked:P,onCheckedChange:K=>{const L=new Set(a.manualPlacements);K?L.add(l.id):L.delete(l.id),s({...a,manualPlacements:Array.from(L)})}}),l.label]},l.id)})})]}),e.jsx(Qe,{label:"Advantage Campaign Budget (CBO)",hint:"Recommended. One budget per campaign; Meta concentrates spend on the ad sets that perform.",checked:a.useCbo,onCheckedChange:l=>s({...a,useCbo:l})}),e.jsxs("label",{className:"flex items-center gap-2 text-xs pt-1",children:[e.jsx(je,{checked:a.saveDefaults,onCheckedChange:l=>s({...a,saveDefaults:!!l})}),"Save landing URL / CTA / targeting as workspace defaults"]})]})]})]}),e.jsxs(Me,{children:[e.jsx(E,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(E,{onClick:Xt,disabled:!!ve||I.isLoading,children:[e.jsx(Ze,{className:"mr-2 size-4"}),`Push to Meta · 1 campaign · ${fe} ad sets · ${ke} ads`]})]})]})})}function ca({workspaceId:t,cellId:n}){const h=S(js),r=S(ys),f=S(Ns),o=S(ws),p=S(Cs),x=he(),m=["cell-bundles",t,n],[k,T]=A.useState(!1);A.useEffect(()=>{if(k)return;let i=!1;return h({data:{workspaceId:t,cellId:n}}).then(()=>{i||(T(!0),x.invalidateQueries({queryKey:m}))}).catch(M=>{i||N.error(M.message)}),()=>{i=!0}},[t,n]);const{data:_,isLoading:y}=G({queryKey:m,queryFn:()=>r({data:{workspaceId:t,cellId:n}}),refetchInterval:15e3}),[d,u]=A.useState(!1),[g,b]=A.useState(null),C=B({mutationFn:i=>f({data:{workspaceId:t,slotId:i}}),onSuccess:()=>{x.invalidateQueries({queryKey:m}),N.success("Slot rejected — re-order to replace")},onError:i=>N.error(i.message)}),O=B({mutationFn:i=>p({data:{workspaceId:t,slotId:i}}),onSuccess:()=>{x.invalidateQueries({queryKey:m}),N.success("Queued")},onError:i=>N.error(i.message)}),D=B({mutationFn:i=>o({data:{workspaceId:t,bundleId:i,extraVideoVariants:2,extraImages:2,extraCopyVariants:2}}),onSuccess:i=>{x.invalidateQueries({queryKey:m});const M=i.overflowBundlesCreated??0;N.success(M>0?`Added variants — ${M} new Advantage+ bundle(s) created to stay within Meta limits`:"Added 2 video, 2 image, 2 copy variant slots")},onError:i=>N.error(i.message)});return y||!_?e.jsx("div",{className:"mt-3 space-y-2",children:e.jsx(Xe,{className:"h-32 w-full"})}):_.length===0?e.jsx("div",{className:"mt-3 text-xs text-muted-foreground",children:"No Advantage+ bundles planned for this cell yet."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[_.map(i=>e.jsx(oa,{bundle:i,onReject:M=>C.mutate(M),onOrder:M=>O.mutate(M),onAddVariants:()=>D.mutate(i.id),addPending:D.isPending,onPush:()=>{b(i.id),u(!0)}},i.id)),d&&g&&e.jsx(tt,{open:d,onOpenChange:i=>{u(i),i||(b(null),x.invalidateQueries({queryKey:m}))},workspaceId:t,cellId:n,cellTitle:"Advantage+ bundle",bundleId:g})]})}function oa({bundle:t,onReject:n,onOrder:h,onAddVariants:r,addPending:f,onPush:o}){const p=t.counts.video,x=t.counts.image,m=t.counts.copy,k=p.ready+x.ready+m.ready,T=k>0,_=A.useMemo(()=>t.slots.filter(b=>b.kind==="video"),[t.slots]),y=A.useMemo(()=>t.slots.filter(b=>b.kind==="image"),[t.slots]),d=A.useMemo(()=>t.slots.filter(b=>b.kind==="copy"),[t.slots]),u=t.targetAspects,g=new Map;for(const b of _)g.set(`${b.variantIndex}::${b.aspect??""}`,b);return e.jsxs("div",{className:"rounded-md border bg-card/40 p-3",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(Z,{className:"size-3.5 text-primary"}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["Advantage+ bundle ·"," ",t.actorName??(t.actorId==="_unassigned"?"No actor yet":t.actorId)]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[p.ready,"/",p.total," videos · ",x.ready,"/",x.total," images · ",m.ready,"/",m.total," copy",t.metaAdId?" · pushed to Meta":""]}),e.jsxs("div",{className:"mt-0.5 text-[10px] text-muted-foreground
1/80",children:["DCO ad will carry: ",p.total,"/",Be.videos," videos ·"," ",x.total,"/",Be.images," images ·"," ",m.total,"/",Be.bodies," copy variants — served as one Advantage+ ad on Meta."]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(E,{size:"sm",variant:"outline",disabled:f,onClick:r,title:"Add 2 more video + 2 image + 2 copy slots (creative fatigue refresh)",children:[f?e.jsx(ae,{className:"size-3 animate-spin"}):e.jsx(as,{className:"size-3"}),"Add variants"]}),e.jsx(E,{size:"sm",variant:"default",disabled:!T,onClick:o,title:T?`Push this bundle to Meta with ${k} ready asset(s) — pending slots are skipped`:"At least one slot must be ready before pushing",children:"Push bundle"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Ke,{icon:e.jsx(Le,{className:"size-3"}),label:`Videos (${p.ready}/${p.total})`}),e.jsxs("div",{className:"mt-1 grid gap-1",style:{gridTemplateColumns:`48px repeat(${u.length}, minmax(0, 1fr))`},children:[e.jsx("div",{}),u.map(b=>e.jsx("div",{className:"text-center text-[10px] text-muted-foreground",children:b},b)),Array.from({length:t.targetVideoVariants},(b,C)=>C+1).map(b=>e.jsx(ua,{variantIndex:b,aspects:u,slots:g,onReject:n,onOrder:h},b))]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Ke,{icon:e.jsx(Rt,{className:"size-3"}),label:`Images (${x.ready}/${x.total})`}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:y.map(b=>e.jsx(At,{slot:b,onReject:n,onOrder:h},b.id))})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Ke,{icon:e.jsx(Ds,{className:"size-3"}),label:`Copy variants (${m.ready}/${m.total})`}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:d.map(b=>e.jsx(At,{slot:b,onReject:n,onOrder:h},b.id))})]})]})}function Ke({icon:t,label:n}){return e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground",children:[t,n]})}function ua({variantIndex:t,aspects:n,slots:h,onReject:r,onOrder:f}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center text-[10px] text-muted-foreground",children:["v",t]}),n.map(o=>{const p=h.get(`${t}::${o}`);return p?e.jsx(ma,{slot:p,onReject:r,onOrder:f},p.id):e.jsx("div",{className:"h-12 rounded border border-dashed"},o)})]})}function ma({slot:t,onReject:n,onOrder:h}){const r="relative h-12 rounded border flex items-center justify-center text-[10px]";return t.status==="ready"?e.jsxs("div",{className:`${r} overflow-hidden border-emerald-500/40 bg-emerald-500/5`,children:[t.thumbnailUrl?e.jsx("img",{src:t.thumbnailUrl,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-emerald-500",children:"ready"}),e.jsx("button",{type:"button",onClick:()=>n(t.id),className:"absolute right-0.5 top-0.5 rounded-full bg-background/80 p-0.5 text-foreground/70 hover:text-destructive",title:"Reject this asset (will re-order)",children:e.jsx(Ce,{className:"size-3"})})]}):t.status==="queued"||t.status==="running"?e.jsxs("div",{className:`${r} border-amber-500/40 bg-amber-500/5 text-amber-600`,children:[e.jsx(ae,{className:"size-3 animate-spin"}),e.jsx("button",{type:"button",onClick:()=>n(t.id),className:"absolute right-0.5 top-0.5 rounded-full bg-background/80 p-0.5 text-foreground/70 hover:text-destructive",title:"Cancel this asset (stops the Arcads job)",children:e.jsx(Ce,{className:"size-3"})})]}):t.status==="failed"?e.jsx("button",{type:"button",onClick:()=>h(t.id),className:`${r} border-destructive/40 bg-destructive/5 text-destructive hover:bg-destructive/10`,title:"Failed — click to re-order",children:"retry"}):t.status==="rejected"?e.jsx("button",{type:"button",onClick:()=>h(t.id),className:`${r} border-dashed border-muted-foreground/40 text-muted-foreground hover:border-foreground
1/40`,title:"Rejected — click to re-order",children:"replace"}):e.jsx("button",{type:"button",onClick:()=>h(t.id),className:`${r} border-dashed text-muted-foreground hover:border-primary/60 hover:text-primary`,title:"Order this asset",children:"+ order"})}function At({slot:t,onReject:n,onOrder:h}){const r=t.variantIndex;if(t.status==="ready")return e.jsxs("div",{className:"relative flex h-12 w-16 items-center justify-center overflow-hidden rounded border border-emerald-500/40 bg-emerald-500/5",children:[t.thumbnailUrl||t.previewUrl?e.jsx("img",{src:t.thumbnailUrl??t.previewUrl??"",alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-[10px] text-emerald-500",children:t.kind==="copy"?`v${r}`:"ready"}),e.jsx("button",{type:"button",onClick:()=>n(t.id),className:"absolute right-0.5 top-0.5 rounded-full bg-background/80 p-0.5 text-foreground/70 hover:text-destructive",title:"Reject",children:e.jsx(Ce,{className:"size-3"})})]});const f="flex h-12 w-16 items-center justify-center rounded border text-[10px]";return t.status==="queued"||t.status==="running"?e.jsxs("div",{className:`${f} relative border-amber-500/40 bg-amber-500/5 text-amber-600`,children:[e.jsx(ae,{className:"size-3 animate-spin"}),e.jsx("button",{type:"button",onClick:()=>n(t.id),className:"absolute right-0.5 top-0.5 rounded-full bg-background/80 p-0.5 text-foreground/70 hover:text-destructive",title:"Cancel this asset (stops the Arcads job)",children:e.jsx(Ce,{className:"size-3"})})]}):t.status==="failed"?e.jsx("button",{type:"button",onClick:()=>h(t.id),className:`${f} border-destructive/40 text-destructive hover:bg-destructive/10`,children:"retry"}):e.jsxs("button",{type:"button",onClick:()=>t.kind==="copy"?N.message("Copy variants come from the copy-variation flow"):h(t.id),className:`${f} border-dashed text-muted-foreground hover:border-primary/60 hover:text-primary`,title:"Order",children:["+ v",r]})}const St=[{key:"copy",label:"Copy"},{key:"arcads",label:"Arcads",retryKind:"arcads"},{key:"funnel",label:"Funnel",retryKind:"funnel"},{key:"meta",label:"Meta push",retryKind:"meta"}];function pa(t){return t.status==="failed"||t.status==="queued"||t.status==="processing"}function ha({workspaceId:t,row:n}){const h=S(As),r=S(Ss),f=S(sa),o=he(),[p,x]=A.useState(null),[m,k]=A.useState(!1),[T,_]=A.useState(!1),[y,d]=A.useState(!1),u=`pipeline-bundles-open::${n.cellId}`,[g,b]=A.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(u)==="1"}catch{return!1}}),C=w=>{b(R=>{const J=typeof w=="function"?w(R):w;try{window.localStorage.setItem(u,J?"1":"0")}catch{}return J})},[O,D]=A.useState(["9:16","1:1","16:9"]),i=S(ta),M=B({mutationFn:()=>i({data:{workspaceId:t,sourceJobId:n.parts.arcads.id,aspects:O}}),onSuccess:w=>{N.success(`Queued ${w.queued} video variant${w.queued===1?"":"s"}`),_(!1),o.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:w=>N.error(w.message)}),I=B({mutationFn:w=>h({data:{workspaceId:t,partKind:w.partKind,partId:w.partId}}),onSuccess:w=>{w?.ok?N.success("Retry queued"):N.error(w?.error??"Retry failed"),o.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:w=>N.error(w.message)}),q=B({mutationFn:()=>r({data:{workspaceId:t,cellId:n.cellId}}),onSuccess:w=>{const R=w?.activated??0,J=w?.errors??[];J.length>0?N.error(`Activated ${R}, ${J.length} failed: ${J[0]}`):N.success(`Activated ${R} Meta ad${R===1?"":"s"}`),o.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:w=>N.error(w.message)}),$=B({mutationFn:()=>f({data:{workspaceId:t,cellId:n.cellId}}),onSuccess:w=>{const R=w;R.skipped?N.info(R.skipped):(R.errors?.length??0)>0?N.error(`Bundled ${R.actorsBundled??0} actor${R.actorsBundled===1?"":"s"}, ${R.errors.length} error(s): ${R.errors[0].error}`):N.success(`Bundled ${R.actorsBundled??0} actor${R.actorsBundled===1?"":"s"} into Advantage+; paused ${R.adSetsPaused??0} legacy ad set${R.adSetsPaused===1?"":"s"}.`),d(!1),o.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:w=>N.error(w.message)});async function c(w){try{await c(w),N.success("URL copied")}catch{N.error("Could not copy")}}const a=St.find(w=>w.retryKind&&pa(n.parts[w.key])),s=n.parts.funnel.status==="completed",j=n.parts.arcads.status==="completed",F=n.parts.meta.status,U=s&&j&&(F==="none"||F==="failed"),Q=j&&!!n.parts.arcads.id,ne=n.metaActive;return e.jsxs("div",{"data-app-row":"","data-no-hover":"",className:"rounded-md border bg-card/40 p-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.previewUrl?e.jsxs("button",{type:"button",onClick:()=>x({url:n.previewUrl,type:n.previewType??"image",title:`${n.awarenessLevel} · ${n.formatType}`}),className:"group relative h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted",title:"Click to preview",children:[n.previewThumbnailUrl||n.previewType==="image"?e.jsx("img",{src:n.previewThumbnailUrl??n.previewUrl,alt:"",className:"h-full w-full object-cover transition-transform group-hover:scale-105",loading:"lazy"}):e.jsx("video",{src:n.previewUrl,className:"h-full w-full object-cover",muted:!0,preload:"metadata"}),n.previewType==="video"&&e.jsx("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-black/30",children:e.jsx(Le,{className:"size-4 fill-white text-white"})})]}):e.jsx("div",{className:"h-14 w-14 shrink-0 rounded-md border border-dashed bg-muted/30"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 font-medium",children:[e.jsxs("span",{children:[n.awarenessLevel," · ",n.formatType]}
1),n.pendingVariationsCount>0&&e.jsxs("span",{className:"inline-flex items-center rounded border border-emerald-500/40 bg-emerald-500/15 px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide text-emerald-600 dark:text-emerald-400",children:["Parent · ",n.pendingVariationsCount," variant",n.pendingVariationsCount===1?"":"s"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.aspect," · ",n.headline?n.headline.slice(0,60):e.jsx("span",{className:"italic",children:"no headline"})]}),n.landingUrl&&e.jsxs("a",{href:n.landingUrl,target:"_blank",rel:"noreferrer",className:"mt-1 inline-flex items-center gap-1 break-all text-xs text-primary",children:[n.landingUrl,e.jsx(Ae,{className:"size-3 shrink-0"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:St.map(w=>e.jsx(na,{label:w.label,part:n.parts[w.key]},w.key))}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(E,{size:"sm",variant:g?"default":"outline",onClick:()=>C(w=>!w),title:"Show the Advantage+ bundle plan (one ad per actor, all aspects bundled) for this cell",children:[e.jsx(Ne,{className:"size-3.5"}),"Bundles",g?e.jsx(Pt,{className:"size-3.5"}):e.jsx(It,{className:"size-3.5"})]}),n.landingUrl&&e.jsx(E,{size:"sm",variant:"ghost",className:"h-7 px-2",title:n.landingUrl,onClick:()=>c(n.landingUrl),children:e.jsx(Ft,{className:"size-3.5"})}),a&&n.parts[a.key].id&&e.jsxs(E,{size:"sm",variant:"outline",disabled:I.isPending,onClick:()=>I.mutate({partKind:a.retryKind,partId:n.parts[a.key].id}),children:["Retry ",a.label]}),U&&e.jsxs(E,{size:"sm",variant:"default",title:"Configure & push this cell to Meta",onClick:()=>k(!0),children:[e.jsx(Ze,{className:"size-3.5"})," Push to Meta"]}),Q&&e.jsxs(E,{size:"sm",variant:"outline",title:"Spawn alternative video renders (re-runs Arcads with new aspect)",onClick:()=>_(!0),children:[e.jsx(Z,{className:"size-3.5"})," Video variants"]}),ne&&e.jsxs(E,{size:"sm",variant:"outline",title:"Bundle this cell's scattered ads into one Advantage+ Creative ad per actor; pauses the legacy ad sets so spend concentrates.",onClick:()=>d(!0),children:[e.jsx(Ne,{className:"size-3.5"})," Consolidate"]}),e.jsxs(E,{size:"sm",variant:n.allComplete?"default":"outline",disabled:!n.allComplete||q.isPending,title:n.allComplete?"Activate this ad in Meta":"All parts must be complete before activating",onClick:()=>q.mutate(),children:[e.jsx(Le,{className:"size-3.5"})," Activate"]})]})]}),g&&e.jsx(ca,{workspaceId:t,cellId:n.cellId}),e.jsx(ce,{open:!!p,onOpenChange:w=>!w&&x(null),children:e.jsxs(oe,{className:"max-w-3xl",children:[e.jsx(ue,{children:e.jsx(me,{children:p?.title??"Preview"})}),p?.type==="video"?e.jsx("video",{src:p.url,controls:!0,autoPlay:!0,className:"max-h-[70vh] w-full rounded-md bg-black"}):p?.type==="image"?e.jsx("img",{src:p.url,alt:p.title,className:"max-h-[70vh] w-full rounded-md object-contain"}):null,p&&e.jsxs("a",{href:p.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 self-start text-xs text-primary",children:["Open in new tab ",e.jsx(Ae,{className:"size-3"})]})]})}),e.jsx(ce,{open:y,onOpenChange:d,children:e.jsxs(oe,{className:"max-w-md",children:[e.jsxs(ue,{children:[e.jsx(me,{children:"Consolidate to Advantage+"}),e.jsxs(we,{children:["Bundles every aspect (9:16 / 1:1 / 16:9) of this cell into ONE Meta ad per actor, using ",e.jsx("code",{children:"asset_feed_spec"})," placement customization. Meta then auto-serves the right aspect per placement."]})]}),e.jsxs("div",{className:"space-y-2 py-2 text-xs text-muted-foreground",children:[e.jsx("p",{children:e.jsx("b",{children:"What happens:"})}),e.jsxs("ul",{className:"ml-4 list-disc space-y-1",children:[e.jsx("li",{children:"New ads are created (one per actor) with bundled aspects."}),e.jsxs("li",{children:["The legacy scattered ad sets are ",e.jsx("b",{children:"paused"}),", not deleted — you can resume them if anything looks off."]}),e.jsx("li",{children:"Learning resets on the new bundled ads. Give them 3–7 days before reading results."})]})]}),e.jsxs(Me,{children:[e.jsx(E,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(E,{disabled:$.isPending,onClick:()=>$.mutate(),children:[$.isPending?e.jsx(ae,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(Ne,{className:"mr-1 h-3 w-3"}),"Bundle & pause legacy ad sets"]})]})]})}),e.jsx(ce,{open:T,onOpenChange:_,children:e.jsxs(oe,{className:"max-w-md",children:[e.jsxs(ue,{children:[e.jsx(me,{children:"Spawn video variants"}),e.jsx(we,{children:"Re-renders this Arcads video in the selected aspect ratios. Each render becomes its own pipeline row, linked so Meta can bundle them into one placement-customized ad on push."})]}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("div",{className:"text-xs font-medium",children:"Aspect ratios"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["9:16","1:1","16:9"].map(w=>{const R=O.includes(w),J=w==="9:16"?"Tall — Reels / Stories":w==="1:1"?"Square — Feed":"Wide — In-Stream";return e.jsx("button",{type:"button",onClick:()=>D(ee=>{const xe=ee.includes(w)?ee.filter(v=>v!==w):[...ee,w];return xe.length===0?ee:xe}),className:`rounded-full border px-2 py-1 text-[10px] transition ${R?"border-primary bg-primary text-primary-foreground":"border-border text-muted-foreground hover:border-foreground
1/40"}`,children:J},w)})}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Heads-up: each render uses one Arcads credit."})]}),e.jsxs(Me,{children:[e.jsx(E,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsxs(E,{disabled:M.isPending,onClick:()=>M.mutate(),children:[M.isPending?e.jsx(ae,{className:"mr-1 h-3 w-3 animate-spin"}):e.jsx(Z,{className:"mr-1 h-3 w-3"}),"Queue ",O.length," render",O.length===1?"":"s"]})]})]})}),m&&e.jsx(tt,{open:m,onOpenChange:k,workspaceId:t,cellId:n.cellId,cellTitle:`${n.awarenessLevel} · ${n.formatType}`,defaultLandingUrl:n.landingUrl??null,pipelineCampaignName:n.metaCampaignName??null})]})}const Bt=H({method:"POST"}).middleware([W]).handler(Y("src_lib_matrix-bundle-preview_functions_ts--previewMatrixBundles_createServerFn_handler")),xa=Object.freeze(Object.defineProperty({__proto__:null,previewMatrixBundles:Bt},Symbol.toStringTag,{value:"Module"}));function Ye(t){if(!t)return null;const n=new Date(t);return isNaN(n.getTime())?null:n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function ga(t){if(!t)return null;const n=new Date(t);return isNaN(n.getTime())?null:n.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function fa({cells:t}){const n=t.find(p=>p.metaCampaignCreatedAt||p.metaCampaignStartAt),h=Ye(n?.metaCampaignCreatedAt),r=Ye(n?.metaCampaignStartAt),f=t.map(p=>p.createdAt).filter(p=>!!p).sort()[0],o=f?ga(f):null;return!h&&!r&&!o?null:e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground",children:[o&&e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground/80",children:"Pushed to Assembler:"})," ",o]}),h&&e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground/80",children:"Created:"})," ",h]}),r&&e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground/80",children:"Live from:"})," ",r]})]})}function va({cells:t}){const h=[{key:"copy",label:"Copy"},{key:"arcads",label:"Arcads"},{key:"funnel",label:"Funnel"},{key:"meta",label:"Meta push"}].map(r=>{let f=0,o=0,p=0,x=0,m=0;for(const k of t){const T=k.parts[r.key],_=T.status;if(_==="none")continue;const y=T.detail?/(\d+)\s*\/\s*(\d+)/.exec(T.detail):null,d=y?parseInt(y[1],10):null,u=y?parseInt(y[2],10):null,g=u&&u>0?u:1;m+=g,_==="completed"?x+=d??g:_==="processing"?(x+=d??0,f+=g-(d??0)):_==="queued"?(x+=d??0,o+=g-(d??0)):(_==="failed"||_==="blocked")&&(x+=d??0,p+=g-(d??0))}return{...r,running:f,queued:o,failed:p,done:x,total:m}});return t.length===0?null:e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",onClick:r=>r.stopPropagation(),children:[e.jsxs("span",{className:"whitespace-nowrap rounded-md border bg-muted/40 px-1.5 py-0.5 text-[11px] text-muted-foreground",children:[t.length," cell",t.length===1?"":"s"]}),h.map(r=>r.total===0?null:e.jsxs("span",{className:"inline-flex items-center gap-1 whitespace-nowrap rounded-md border bg-muted/40 px-1.5 py-0.5 text-[11px]",title:`${r.label}: ${r.done}/${r.total} done · ${r.running} running · ${r.queued} queued · ${r.failed} failed`,children:[e.jsx("span",{className:"font-medium text-foreground",children:r.label}),e.jsxs("span",{className:"text-foreground/80",children:[r.done,"/",r.total]}),r.running>0&&e.jsxs("span",{className:"text-blue-500",children:["· ",r.running," running"]}),r.queued>0&&e.jsxs("span",{className:"text-muted-foreground",children:["· ",r.queued," queued"]}),r.failed>0&&e.jsxs("span",{className:"text-destructive",children:["· ",r.failed," failed"]})]},r.key))]})}function st({message:t}){return e.jsxs("div",{className:"mt-1 flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-2 py-1.5",children:[e.jsx("div",{className:"flex-1 whitespace-pre-wrap break-words text-xs text-destructive",children:t}),e.jsxs(E,{size:"sm",variant:"ghost",className:"h-6 shrink-0 px-1.5 text-[10px] text-destructive hover:bg-destructive/10",onClick:async n=>{n.stopPropagation();try{await ds(t),N.success("Error copied")}catch{N.error("Could not copy")}},"aria-label":"Copy error message",children:[e.jsx(Ft,{className:"mr-1 h-3 w-3"})," Copy"]})]})}function ba(t=1e3){const[,n]=A.useState(0);A.useEffect(()=>{const h=setInterval(()=>n(r=>r+1),t);return()=>clearInterval(h)},[t])}function Je(t){return t==="queued"?12:t==="pushing"?55:t==="awaiting_media"?85:t==="pushed"||t==="failed"||t==="cancelled"||t==="attach_failed"||t==="active"||t==="paused"?100:t==="awaiting_video"?25:5}function ja(t){switch(t){case"draft":return{step:1,total:4,label:"Draft — waiting to be queued"};case"awaiting_video":return{step:1,total:4,label:"Awaiting video render from Arcads"};case"queued":return{step:2,total:4,label:"Queued for Meta"};case"pushing":return{step:3,total:4,label:"Creating ad in Meta Ads Manager"};case"awaiting_media":return{step:4,total:4,label:"Ad created — attaching final media"};case"pushed":return{step:4,total:4,label:"Live in Meta (paused — activate when ready)"};case"active":return{step:4,total:4,label:"Active in Meta Ads Manager"};case"paused":return{step:4,total:4,label:"Created in Meta Ads Manager — currently paused"};case"attach_failed":return{step:4,total:4,label:"Ad exists in Meta — media attach failed"};case"failed":return{step:0,total:4,label:"Failed — click Retry to try again"};case"cancelled":return{step:0,total:4,label:"Cancelled"};default:return{step:1,total:4,label:t}}}function De(t){const h={queued:{label:"Queued",variant:"secondary"},planned:{label:"Not ordered",variant:"outline"},processing:{label:"Processing",variant:"default"},completed:{label:"Completed",variant:"outline"},failed:{label:"Failed",variant:"destructive"},cancelled:{label:"Cancelled",variant:"outline"},draft:{label:"Draft",variant:"secondary"},live:{label:"Live",variant:"default"},idle:{label:"Idle",variant:"secondary"},missing:{label:"Missing",variant:"outline"},archived:{label:"Archived",variant:"outline"},awaiting_video:{label:"Awaiting Arcads video",variant:"secondary"},pushing:{label:"Pushing to Meta",variant:"default"},pushed:{label:"Pushed to Meta",variant:"default"},awaiting_media:{label:"Pushed · attaching media…",variant:"default"},attach_failed:{label:"Media attach failed",variant:"destructive"},active:{label:"Active",variant:"default"},paused:{label:"Paused in Meta",variant:"outline"}}[t]??{label:t,variant:"secondary"};return e.jsx(pe,{variant:h.variant,children:h.label})}function at({url:t,mediaType:n,outputUrl:h,title:r}){const f=n==="image"?Rt:Es,[o,p]=A.useState(!1),x=h??t??null,m=!!x;return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:!m,onClick:()=>m&&p(!0),className:`group relative h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted flex items-center justify-center ${m?"curs
1or-pointer":"cursor-default"}`,title:m?"Click to preview":void 0,children:[t?e.jsx("img",{src:t,alt:"",className:"h-full w-full object-cover",loading:"lazy"}):h&&n==="video"?e.jsx("video",{src:`${h}#t=0.1`,className:"h-full w-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}):h&&n==="image"?e.jsx("img",{src:h,alt:"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx(f,{className:"h-5 w-5 text-muted-foreground"}),m&&n==="video"&&e.jsx("span",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-black/30 opacity-90 group-hover:opacity-100",children:e.jsx(Le,{className:"h-4 w-4 fill-white text-white"})})]}),e.jsx(ce,{open:o,onOpenChange:p,children:e.jsxs(oe,{className:"max-w-3xl",children:[e.jsx(ue,{children:e.jsx(me,{children:r??"Preview"})}),x&&n==="video"?e.jsx("video",{src:x,controls:!0,autoPlay:!0,className:"max-h-[70vh] w-full rounded-md bg-black"}):x?e.jsx("img",{src:x,alt:r??"",className:"max-h-[70vh] w-full rounded-md object-contain"}):null]})})]})}function ya({workspaceId:t,offerId:n}){const h=S(Ks),r=S(Hs),f=S(Ws),o=S(Ys),p=S(ks),x=S(Js),m=he();ba(1e3);const k=G({queryKey:["pipeline-queues",t,n??null],queryFn:()=>h({data:{workspaceId:t,offerId:n??null}}),refetchInterval:s=>{const j=s.state.data,F=new Set(["pushing","queued","awaiting_media","awaiting_video","processing"]),U=ne=>(ne??[]).some(w=>F.has((w.status??"").toLowerCase()));return U(j?.metaAds)||U(j?.metaPushes)||U(j?.arcadsAds)||U(j?.images)?2e3:5e3}}),T=G({queryKey:["pipeline-rows",t],queryFn:()=>p({data:{workspaceId:t}}),refetchInterval:5e3}),_=()=>m.invalidateQueries({queryKey:["pipeline-queues",t]});B({mutationFn:s=>r({data:{workspaceId:t,...s}}),onSuccess:()=>{N.success("Stopped"),_()},onError:s=>N.error(s.message)});const y=B({mutationFn:s=>f({data:{workspaceId:t,...s}}),onSuccess:s=>{const j=s.error;j?N.error(j):N.success("Restarted"),_()},onError:s=>N.error(s.message)}),d=B({mutationFn:s=>o({data:{workspaceId:t,...s}}),onSuccess:s=>{const j=s.metaError;j?N.warning(`Deleted locally. Meta archive: ${j}`):N.success("Deleted"),_()},onError:s=>N.error(s.message)}),u=B({mutationFn:s=>x({data:{workspaceId:t,cellIds:s.cellIds}}),onSuccess:s=>{const j=s.archived??0;N.success(`Archived ${j} cell${j===1?"":"s"}`),_(),m.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:s=>N.error(s.message)}),[g,b]=A.useState(null),[C,O]=A.useState(null),[D,i]=A.useState({arcads_ad:new Set,arcads_vsl:new Set,arcads_image:new Set,funnel:new Set,meta:new Set}),[M,I]=A.useState(!1);function q(s){i(j=>({...j,[s]:new Set}))}async function $(s,j){I(!0);try{const U=(await Promise.allSettled(j.map(Q=>o({data:{workspaceId:t,kind:s,id:Q}})))).filter(Q=>Q.status==="rejected").length;U===0?N.success(`Deleted ${j.length} item${j.length===1?"":"s"}`):N.warning(`Deleted ${j.length-U} of ${j.length}, ${U} failed`),q(s),_()}finally{I(!1)}}async function c(s){if(s.length!==0){I(!0);try{const F=(await Promise.allSettled(s.map(U=>o({data:{workspaceId:t,kind:U.kind,id:U.id}})))).filter(U=>U.status==="rejected").length;F===0?N.success(`Deleted ${s.length} item${s.length===1?"":"s"}`):N.warning(`Deleted ${s.length-F} of ${s.length}, ${F} failed`),_(),m.invalidateQueries({queryKey:["pipeline-rows",t]})}finally{I(!1)}}}if(k.isLoading)return e.jsx(Xe,{className:"h-64 w-full"});const a=k.data;return a?e.jsxs("div",{className:"space-y-6",children:[e.jsx(wa,{arcadsAds:a.arcadsAds,arcadsVsl:a.arcadsVsl,images:a.images,funnels:a.funnels,metaAds:a.metaAds,metaPushes:a.metaPushes??[],onRetry:(s,j)=>y.mutate({kind:s,id:j}),retryPendingId:y.variables?.id,workspaceId:t,cells:T.data?.rows??[],bulkPending:M,onDeleteCampaigns:s=>{c(s)},onArchiveCells:s=>u.mutate({cellIds:s}),archivePending:u.isPending}),e.jsx(Pe,{open:!!g,onOpenChange:s=>!s&&b(null),children:e.jsxs(Ie,{children:[e.jsxs(Fe,{children:[e.jsx($e,{children:"Delete this item?"}),e.jsx(Te,{children:g?.kind==="meta"?`"${g?.label}" will be paused and archived on Meta, then removed from this workspace.`:g?.kind==="funnel"?`"${g?.label}" and its landing pages will be deleted. This cannot be undone.`:`"${g?.label}" will be deleted from the queue. This cannot be undone.`})]}),e.jsxs(qe,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Ee,{onClick:()=>{g&&d.mutate({kind:g.kind,id:g.id}),b(null)},children:"Delete"})]})]})}),e.jsx(Pe,{open:!!C,onOpenChange:s=>!s&&O(null),children:e.jsxs(Ie,{children:[e.jsxs(Fe,{children:[e.jsxs($e,{children:["Delete ",C?.ids.length??0," item",(C?.ids.length??0)===1?"":"s","?"]}),e.jsx(Te,{children:C?.kind==="meta"?"Selected Meta ads will be paused, ar
1chived on Meta, then removed from this workspace.":C?.kind==="funnel"?"Selected funnels and their landing pages will be deleted. This cannot be undone.":"Selected queue items will be deleted. This cannot be undone."})]}),e.jsxs(qe,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Ee,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{C&&$(C.kind,C.ids),O(null)},children:"Delete"})]})]})})]}):null}function Na({workspaceId:t,cells:n}){const h=S(Bt),r=n.map(u=>u.cellId),f=r.slice().sort().join("|"),o=G({queryKey:["matrix-bundle-preview",t,f],queryFn:()=>h({data:{workspaceId:t,cellIds:r}}),enabled:r.length>0,refetchInterval:15e3,staleTime:1e4}),p=o.data??{},x=u=>{const g=n.find(C=>C.cellId===u);return g&&[g.awarenessLevel,g.formatType].filter(Boolean).join(" · ")||u.slice(0,8)},m=r.map(u=>p[u]).filter(u=>!!u&&u.actors.length>0);if(o.isLoading)return e.jsx("div",{className:"rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground",children:"Computing Advantage+ bundle preview…"});if(m.length===0)return e.jsxs("div",{className:"rounded-md border border-dashed bg-muted/20 p-3 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-medium text-foreground",children:[e.jsx(Ne,{className:"h-3.5 w-3.5"}),"Advantage+ bundle preview"]}),e.jsx("div",{className:"mt-1",children:"No completed videos yet. Bundling needs ≥ 2 aspect ratios per actor."})]});const k=m.reduce((u,g)=>u+g.predictedAdCount,0),T=m.reduce((u,g)=>u+(g.videoAdCount??0),0),_=m.reduce((u,g)=>u+(g.imageAdCount??0),0),y=m.reduce((u,g)=>u+(g.variationAdCount??0),0),d=m.length;return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-foreground",children:[e.jsx(Ne,{className:"h-3.5 w-3.5"})," Meta push preview"]}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:"Every produced video and every image is pushed as its own Meta ad in the cell's ad set. Headline / primary-text variations push as additional ads in the same ad set."})]})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2",children:[e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Campaigns"}),e.jsx("div",{className:"text-sm font-semibold text-foreground",children:"1"})]}),e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Ad sets"}),e.jsxs("div",{className:"text-sm font-semibold text-foreground",children:[d,e.jsx("span",{className:"ml-1 text-[10px] font-normal text-muted-foreground",children:"× Saved Audiences"})]})]}),e.jsxs("div",{className:"rounded-md border bg-background px-2 py-1.5",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Ads"}),e.jsxs("div",{className:"text-sm font-semibold text-foreground",children:[k,e.jsxs("span",{className:"ml-1 text-[10px] font-normal text-muted-foreground",children:[T," video · ",_," image",y>0?` · ${y} copy-variant`:""]})]})]})]}),e.jsxs("div",{className:"mt-1.5 text-[10px] leading-snug text-muted-foreground",children:["1 ad set per cell by default. If you pick Saved Audiences in the push dialog, the count multiplies: ",e.jsx("b",{children:"cells × audiences in tier"})," ad sets, each receiving the same ",k," ad",k===1?"":"s"," below — every produced asset gets a Meta ad shell."]}),e.jsx("ul",{className:"mt-2 space-y-1.5",children:m.map(u=>e.jsxs("li",{className:"rounded border bg-background px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:x(u.cellId)}),e.jsxs("span",{className:"text-muted-foreground",children:[u.videoAdCount??0," video · ",u.imageAdCount??0," image",(u.variationAdCount??0)>0?` · ${u.variationAdCount} copy-variant`:""," ","→"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[u.predictedAdCount," ad",u.predictedAdCount===1?"":"s"]})]})]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:u.actors.map(g=>e.jsxs("li",{className:"flex items-center justify-between gap-2 text-xs",children:[e.jsxs("span",{className:"truncate",children:[e.jsx("span",{className:"text-foreground",children:g.actor==="_unknown"?"(no actor)":g.actorName??`Actor ${g.actor.slice(0,6)}`})," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",g.aspects.join(" + ")]})]}),g.alreadyBundled?e.jsx(pe,{variant:"secondary",className:"text-[10px]",children:"bundled"}):g.willBundle?e.jsx(pe,{className:"bg-emerald-600 text-[10px] text-white hover:bg-emerald-600",children:"will bundle → 1 ad"}):e.jsx(pe,{variant:"outline",className:"text-[10px]",children:"1 aspect only"})]},g.actor))})]},u.cellId))})]})}function Qt({workspaceId:t}){const n=S(Xs),h=S(Zs),r=he(),f=G({queryKey:["pipeline-archived",t],queryFn:()=>n({data:{workspaceId:t}}),refetchInterval:1e4}),o=B({mutationFn:x=>h({data:{workspaceId:t,cellIds:x.cellIds}}),onSuccess:x=>{const m=x.restored??0;N.success(`Restored ${m} cell${m===1?"":"s"}`),r.invalidateQueries({queryKey:["pipeline-archived",t]}
1),r.invalidateQueries({queryKey:["pipeline-queues",t]}),r.invalidateQueries({queryKey:["pipeline-rows",t]})},onError:x=>N.error(x.message)}),p=f.data?.groups??[];return f.isLoading||p.length===0?null:e.jsxs("details",{"data-no-hover":"",className:"mt-4 rounded-md border bg-muted/20 group",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-2 px-3 py-2 text-xs text-muted-foreground [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-3.5 w-3.5 transition-transform group-open:rotate-90"}),e.jsx(Vt,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium text-foreground",children:"Archived"}),e.jsxs("span",{children:["· ",p.length," campaign",p.length===1?"":"s"]})]}),e.jsx("span",{className:"text-[11px]",children:"Restore brings cells back · never touches Meta"})]}),e.jsx("ul",{className:"border-t [&>li+li]:border-t",children:p.map(x=>{const m=o.isPending&&o.variables?.cellIds.length===x.cellIds.length&&o.variables?.cellIds[0]===x.cellIds[0],k=x.campaignName||"(no campaign name)",T=Ye(x.archivedAt);return e.jsxs("li",{className:"flex items-center gap-3 px-3 py-1.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate text-xs font-medium",children:k}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[x.count," cell",x.count===1?"":"s",T?` · archived ${T}`:""]})]}),e.jsxs(E,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[11px]",disabled:m,onClick:()=>o.mutate({cellIds:x.cellIds}),children:[e.jsx(et,{className:"mr-1 h-3 w-3"}),m?"Restoring…":"Restore"]})]},x.key)})})]})}function wa({arcadsAds:t,arcadsVsl:n,images:h,funnels:r,metaAds:f,metaPushes:o,cells:p,onRetry:x,retryPendingId:m,workspaceId:k,bulkPending:T,onDeleteCampaigns:_,onArchiveCells:y,archivePending:d}){const u=new Map,g="__unpushed__",b=new Map;function C(c,a){const s=a?.trim();return s?`meta:${s}`:c&&c.trim()?`name:${c.trim()}`:g}function O(c,a,s,j){let F=u.get(c);return F?s>F.latestAt&&(F.latestAt=s):(F={key:c,campaignName:a,campaignStatus:j,arcadsAds:[],arcadsVsl:[],images:[],funnels:[],metaAds:[],metaPushes:[],cells:[],latestAt:s},u.set(c,F)),a&&!F.campaignName&&(F.campaignName=a),j&&!F.campaignStatus&&(F.campaignStatus=j),F}for(const c of p){const a=c.metaCampaignName?.trim()||null,s=C(a,c.metaCampaignId);b.set(c.cellId,s),O(s,a,c.updatedAt,null).cells.push(c)}const D=c=>!!(c&&c.trim());function i(c,a){return c&&b.get(c)||C(a)}for(const c of t)(D(c.campaignName)||c.synthetic||c.cellId&&b.has(c.cellId))&&O(i(c.cellId,c.campaignName),c.campaignName,c.updatedAt,c.campaignStatus).arcadsAds.push(c);for(const c of n)(D(c.campaignName)||c.synthetic||c.cellId&&b.has(c.cellId))&&O(i(c.cellId,c.campaignName),c.campaignName,c.updatedAt,c.campaignStatus).arcadsVsl.push(c);for(const c of h)(D(c.campaignName)||c.synthetic||c.cellId&&b.has(c.cellId))&&O(i(c.cellId,c.campaignName),c.campaignName,c.updatedAt,c.campaignStatus).images.push(c);for(const c of r)(D(c.campaignName)||c.cellId&&b.has(c.cellId))&&O(i(c.cellId,c.campaignName),c.campaignName,c.updatedAt,c.campaignStatus).funnels.push(c);for(const c of f){const a=c.parentCellId??c.id;(D(c.campaignName)||b.has(a))&&O(i(a,c.campaignName),c.campaignName,c.updatedAt,c.campaignStatus).metaAds.push(c)}for(const c of o)if(D(c.campaignName)||c.metaCampaignId||b.has(c.cellId)){const a=b.get(c.cellId)??C(c.campaignName,c.metaCampaignId);O(a,c.campaignName,c.updatedAt,c.campaignStatus).metaPushes.push(c)}const M=/\d{4}-\d{2}-\d{2}/g;function I(c){if(!c)return"";const a=c.match(M);return!a||a.length===0?"":a.sort().at(-1)??""}const q=c=>{let a="";for(const s of c.cells){const j=s.createdAt??"";j>a&&(a=j)}return a},$=Array.from(u.values()).sort((c,a)=>{if(c.key===g)return 1;if(a.key===g)return-1;const s=I(c.campaignName),j=I(a.campaignName);if(s!==j)return j.localeCompare(s);const F=q(c),U=q(a);return F!==U?U.localeCompare(F):c.key.localeCompare(a.key)});return $.length===0?e.jsx(Qt,{workspaceId:k}):e.jsx(Ca,{ordered:$,onRetry:x,retryPendingId:m,workspaceId:k,bulkPending:T,onDeleteCampaigns:_,onArchiveCells:y,archivePending:d})}function Ca({ordered:t,onRetry:n,retryPendingId:h,workspaceId:r,bulkPending:f,onDeleteCampaigns:o,onArchiveCells:p,archivePending:x}){const[m,k]=A.useState(new Set),[T,_]=A.useState(!1),[y,d]=A.useState(null);A.useEffect(()=>{k(i=>{const M=new Set(t.map(q=>q.key)),I=new Set;for(const q of i)M.has(q)&&I.add(q);return I})},[t.map(i=>i.key).join("|")]);const u=t.length>0&&m.size===t.length,g=m.size>0&&!u;function b(i){k(M=>{const I=new Set(M);return I.has(i)?I.delete(i):I.add(i),I})}function C(){k(i=>i.size===t.length?new Set:new Set(t.map(M=>
1M.key)))}function O(){const i=[],M=new Set,I=(q,$)=>{const c=`${q}:${$}`;M.has(c)||(M.add(c),i.push({kind:q,id:$}))};for(const q of t)if(m.has(q.key)){for(const $ of q.arcadsAds)$.synthetic||I("arcads_ad",$.id);for(const $ of q.arcadsVsl)$.synthetic||I("arcads_vsl",$.id);for(const $ of q.images)$.synthetic||I("arcads_image",$.id);for(const $ of q.funnels)I("funnel",$.id);for(const $ of q.metaAds)I("meta",$.id);for(const $ of q.cells)$.metaCampaignId&&I("meta",$.cellId)}return i}const D=m.size>0?O():[];return e.jsxs($t,{children:[e.jsxs(Tt,{children:[e.jsx(qt,{children:"Campaigns in flight"}),e.jsx(Ot,{children:"Every VSL, Arcads video, funnel and Meta ad currently in flight, grouped under the Meta campaign it's destined for. Use this view to track what a single campaign is waiting on in one place."})]}),e.jsxs(Et,{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[e.jsx(je,{checked:u?!0:g?"indeterminate":!1,onCheckedChange:()=>C(),"aria-label":"Select all campaigns"}),e.jsx("span",{className:"font-medium",children:m.size===0?`Select all (${t.length})`:`${m.size} selected`})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m.size>0&&e.jsx(E,{size:"sm",variant:"ghost",onClick:()=>k(new Set),disabled:f,children:"Clear"}),e.jsxs(E,{size:"sm",variant:"destructive",disabled:m.size===0||f,onClick:()=>_(!0),children:[e.jsx(Lt,{className:"h-4 w-4"})," Delete selected"]})]})]}),e.jsx(Aa,{keys:t.map(i=>i.key),forceOpenKeys:t.filter(i=>i.metaPushes.some(M=>M.status==="queued"||M.status==="pushing")).map(i=>i.key),children:t.map((i,M)=>{const I=i.arcadsAds.length+i.arcadsVsl.length+i.images.length+i.funnels.length+i.metaPushes.length+i.metaAds.length+i.cells.length;return(()=>{const q=i.cells.filter(a=>{if(a.parts.meta.status==="completed"&&(a.pendingVariationsCount??0)>0)return!0;const s=a.parts.arcads.status==="completed"||a.parts.images.status==="completed";return a.parts.funnel.status==="completed"&&s&&(a.parts.meta.status==="none"||a.parts.meta.status==="failed")}),$=i.cells.reduce((a,s)=>a+(s.pendingVariationsCount??0),0),c=q.length>0?null:i.cells.length===0?"No matrix cells in this campaign":$===0?"No ready cells: funnel must be complete and at least one asset (image or video) ready; Meta push must be empty or failed":"Variants waiting, but parent cells aren't pushable";return e.jsxs(ns,{value:i.key,"data-app-row":"","data-no-hover":"",className:"rounded-md border bg-card px-3 hover:bg-card even:bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center",children:e.jsx(je,{checked:m.has(i.key),onCheckedChange:()=>b(i.key),"aria-label":`Select campaign ${i.campaignName??"unpushed"}`})}),e.jsx(rs,{className:"min-w-0 flex-1 py-3 hover:no-underline",children:e.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-3 pr-2 text-left",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:i.campaignName??"Not yet pushed to Meta"}),e.jsx(Sa,{status:i.campaignStatus})]}),e.jsx(fa,{cells:i.cells}),e.jsx(va,{cells:i.cells})]})})}),e.jsxs(pe,{variant:"outline",className:"shrink-0",children:[I," asset",I===1?"":"s"]}),i.cells.length>0&&e.jsxs(E,{size:"sm",variant:"default",className:"h-7 shrink-0 px-2 text-xs",disabled:q.length===0,title:c??`Configure & push ${q.length} ready cell${q.length===1?"":"s"} to Meta`,onClick:a=>{a.stopPropagation(),a.preventDefault(),q.length>0&&d({...i,cells:q})},children:[e.jsx(Ze,{className:"mr-1 h-3.5 w-3.5"})," Push to Meta"]}),i.cells.length>0&&e.jsxs(E,{size:"sm",variant:"ghost",className:"h-7 shrink-0 px-2 text-xs",disabled:x,title:"Hide this campaign from the pipeline (does not touch Meta)",onClick:a=>{a.stopPropagation(),a.preventDefault();const s=i.campaignName||"Unpushed";window.confirm(`Archive "${s}" (${i.cells.length} cell${i.cells.length===1?"":"s"})?
2
3This hides them from the pipeline view. It does NOT touch Meta. You can restore them from the database if needed.`)&&p(i.cells.map(F=>F.cellId))},children:[e.jsx(Vt,{className:"mr-1 h-3.5 w-3.5"})," Archive"]})]}),e.jsx(ls,{children:e.jsxs("div",{className:"space-y-4 pt-2",children:[i.cells.length>0&&e.jsx(Na,{workspaceId:r,cells:i.cells}),i.cells.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Matrix cells"}),e.jsx("div",{className:"space-y-2",children:i.cells.map(a=>e.jsx(ha,{workspaceId:r,row:a},a.cellId))})]}),e.jsx(Ma,{items:i.metaPushes}),e.jsx(Ge,{title:"Meta ad videos (Arcads)",items:i.arcadsAds,kind:"arcads_ad",onRetry:n,retryPendingId:h,workspaceId:r,onDeleteItems:o,bulkPending:f}),e.jsx(Ge,{title:"Landing page VSL (Arcads)",items:i.arcadsVsl,kind:"arcads_vsl",onRetry:n,retryPendingId:h,workspaceId:r,onDeleteItems:o,bulkPending:f}),e.jsx(Ge,{title:"Static images",items:i.images,kind:"arcads_image",onRetry:n,retryPendingId:h,workspaceId:r,onDeleteItems:o,bulkPending:f}),e.jsx(_a,{items:i.funnels,onRetry:a=>n("funnel",a),retryPendingId:h}),e.jsx(Pa,{items:i.metaAds,cells:i.cells,onRetry:a=>n("meta",a),retryPendingId:h})]})})]},i.key)})()})}),e.jsx(Qt,{workspaceId:r}),y&&y.cells.length>0&&e.jsx(tt,{open:!!y,onOpenChange:i=>!i&&d(null),workspaceId:r,cellId:y.cells[0].cellId,cellIds:y.cells.map(i=>i.cellId),cellTitle:y.cells.length===1?`${y.cells[0].awarenessLevel} · ${y.cells[0].formatType}`:`${y.campaignName??"Campaign"} · ${y.cells.length} cells`,defaultLandingUrl:y.cells[0].landingUrl??null,pipelineCampaignName:y.campaignName??null,cells:y.cells.map(i=>({cellId:i.cellId,awarenessLevel:i.awarenessLevel,formatType:i.formatType}))})]}),e.jsx(Pe,{open:T,onOpenChange:_,children:e.jsxs(Ie,{children:[e.jsxs(Fe,{children:[e.jsxs($e,{children:["Delete ",m.size," campaign",m.size===1?"":"s","?"]}),e.jsxs(Te,{children:["All queued and planned assets (",D.length," item",D.length===1?"":"s",") for the selected campaign",m.size===1?"":"s"," will be deleted. Any Meta ads already pushed will be paused and archived on Meta. This cannot be undone."]})]}),e.jsxs(qe,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Ee,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o(D),k(new Set),_(!1)},children:"Delete"})]})]})})]})}function Aa({keys:t,forceOpenKeys:n,children:h}){const r="pipeline:campaign-accordion:open",[f,o]=A.useState(()=>{if(typeof window>"u")return[];try{const x=window.localStorage.getItem(r);if(!x)return[];const m=JSON.parse(x);if(Array.isArray(m))return m.filter(k=>typeof k=="string")}catch{}return[]});A.useEffect(()=>{o(x=>x.filter(m=>t.includes(m)))},[t.join("|")]);const p=A.useRef(!1);return A.useEffect(()=>{p.current||!n||n.length===0||(p.current=!0,o(x=>Array.from(new Set([...x,...n]))))},[n?.join("|")]),A.useEffect(()=>{try{window.localStorage.setItem(r,JSON.stringify(f))}catch{}},[f]),e.jsx(is,{type:"multiple",className:"w-full space-y-1.5",value:f,onValueChange:o,children:h})}function Sa({status:t}){if(!t)return null;const n=t.toLowerCase(),r={active:{label:"Active",variant:"default",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/15"},paused:{label:"Paused",variant:"secondary"},draft:{label:"Draft",variant:"outline"},archived:{label:"Archived",variant:"outline"},deleted:{label:"Deleted",variant:"destructive"}}[n]??{label:t,variant:"outline"};return e.jsx(pe,{variant:r.variant,className:`shrink-0 text-[10px] uppercase tracking-wide ${r.className??""}`,children:r.label})}function ka({purpose:t}){const n=t==="vsl"?{label:"VSL",className:"border-amber-500/40 bg-amber-500/10 text-amber-600 dar
3k:text-amber-400"}:t==="image"?{label:"Image",className:"border-muted-foreground/30 bg-muted text-muted-foreground"}:{label:"Meta ad",className:"border-blue-500/40 bg-blue-500/10 text-blue-600 dark:text-blue-400"};return e.jsx(pe,{variant:"outline",className:`shrink-0 text-[10px] uppercase tracking-wide ${n.className}`,children:n.label})}function Re({title:t,count:n,headerRight:h,defaultOpen:r=!0,children:f}){const o=typeof t=="string"?`pipeline:section-open:${t}`:null,[p,x]=A.useState(()=>{if(!o||typeof window>"u")return r;const m=window.localStorage.getItem(o);return m==null?r:m==="1"});return A.useEffect(()=>{!o||typeof window>"u"||window.localStorage.setItem(o,p?"1":"0")},[p,o]),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>x(m=>!m),className:"flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Pt,{className:`h-3 w-3 shrink-0 transition-transform ${p?"":"-rotate-90"}`}),t,typeof n=="number"&&e.jsx("span",{className:"ml-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium normal-case tracking-normal text-muted-foreground",children:n})]}),h]}),p&&f]})}function Ge({title:t,items:n,kind:h,onRetry:r,retryPendingId:f,workspaceId:o,onDeleteItems:p,bulkPending:x}){if(n.length===0)return null;const m=he(),k=S(ps),T=S(Ut),_=S(Gs),y=S(hs),d=S(Dt),u=B({mutationFn:async s=>{if(!o)throw new Error("Missing workspaceId");const j=await k({data:{workspaceId:o,jobId:s}});if(j.blocked){const F=(j.reasons??[]).filter(Q=>Q.delta<0).slice(0,2).map(Q=>Q.label).join(" · ");return window.confirm(`Brain predicts this creative will underperform (score ${j.score}/100).
4
5${F}
6
7Spend the video credits anyway?`)?k({data:{workspaceId:o,jobId:s,overrideGuard:!0}}):{ok:!1,blocked:!0}}return j},onSuccess:s=>{s&&"blocked"in s&&s.blocked?N.message("Video not ordered — credits saved."):N.success("Video ordered — Arcads is rendering it now."),m.invalidateQueries({queryKey:["pipeline-queues",o]})},onError:s=>N.error(s.message)});B({mutationFn:async s=>{if(!o)throw new Error("Missing workspaceId");return T({data:{workspaceId:o,jobId:s}})},onSuccess:()=>{N.success("Image ordered — rendering now."),m.invalidateQueries({queryKey:["pipeline-queues",o]})},onError:s=>N.error(s.message)});const g=B({mutationFn:async s=>{if(!o)throw new Error("Missing workspaceId");return _({data:{workspaceId:o,funnelId:s}})},onSuccess:()=>{N.success("VSL ordered — Arcads is rendering it now."),m.invalidateQueries({queryKey:["pipeline-queues",o]})},onError:s=>N.error(s.message)}),b=B({mutationFn:async({cellId:s,mediaType:j})=>{if(!o)throw new Error("Missing workspaceId");return j==="image"?d({data:{workspaceId:o,cellId:s}}):y({data:{workspaceId:o,cellIds:[s],includeVariations:!1}})},onSuccess:(s,j)=>{N.success(j.mediaType==="image"?"Image ordered — rendering now.":"Video job created."),m.invalidateQueries({queryKey:["pipeline-queues",o]})},onError:s=>N.error(s.message)}),[C,O]=A.useState(new Set),[D,i]=A.useState(!1),M=n.filter(s=>!s.synthetic);A.useEffect(()=>{O(s=>{const j=new Set(M.map(U=>U.id)),F=new Set;for(const U of s)j.has(U)&&F.add(U);return F})},[M.map(s=>s.id).join("|")]);const I=M.length>0&&C.size===M.length,q=C.size>0&&!I,$=s=>O(j=>{const F=new Set(j);return F.has(s)?F.delete(s):F.add(s),F}),c=()=>O(s=>s.size===M.length?new Set:new Set(M.map(j=>j.id))),a=p&&M.length>0?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer select-none",children:[e.jsx(je,{checked:I?!0:q?"indeterminate":!1,onCheckedChange:()=>c(),"aria-label":`Select all ${t}`}),C.size>0?`${C.size} selected`:"Select all"]}),C.size>0&&e.jsxs(E,{size:"sm",variant:"destructive",className:"h-7 px-2 text-xs",disabled:!!x,onClick:()=>i(!0),children:[e.jsx(Lt,{className:"mr-1 h-3 w-3"})," Delete"]})]}):void 0;return e.jsxs(Re,{title:t,count:n.length,headerRight:a,children:[e.jsx("ul",{className:"divide-y rounded-md border",children:n.map(s=>e.jsxs("li",{"data-app-row":"",className:"flex items-center gap-3 px-3 py-2",children:[p&&e.jsx("span",{className:"flex items-center",children:s.synthetic?e.jsx("span",{className:"inline-block h-4 w-4"}):e.jsx(je,{checked:C.has(s.id),onCheckedChange:()=>$(s.id),"aria-label":`Select ${s.title}`})}),e.jsx(at,{url:s.thumbnailUrl,mediaType:s.mediaType,outputUrl:s.outputUrl,title:s.title}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ka,{purpose:s.purpose}),e.jsx("div",{className:"line-clamp-1 text-sm font-medium",children:s.title}),s.bundleSlot?e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-px font-mono text-[10px] text-primary",title:`This row is the same asset as Advantage+ bundle slot ${s.bundleSlot.kind} v${s.bundleSlot.variantIndex}${s.bundleSlot.aspect?` · ${s.bundleSlot.aspect}`:""}${s.bundleSlot.actorName?` · ${s.bundleSlot.actorName}`:""}`,children:[e.jsx(Z,{className:"h-2.5 w-2.5"}),"Bundle · ",s.bundleSlot.kind," v",s.bundleSlot.variantIndex,s.bundleSlot.aspect?` · ${s.bundleSlot.aspect}`:"",s.bundleSlot.actorName?` · ${s.bundleSlot.actorName}`:""]}):null]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s.subtitle}),s.stagedAspects&&s.stagedAspects.length>0&&e.jsxs("div",{className:"mt-0.5 flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Z,{className:"h-3 w-3 text-primary"}),e.jsx("span",{children:"Staged Advantage+:"}),s.stagedAspects.map(j=>e.jsx("span",{className:"rounded border border-primary/30 bg-primary/10 px-1 py-px font-mono text-[10px] text-primary",children:j},j))]}),s.errorMessage&&(s.status==="failed"||s.status==="cancelled")&&e.jsx(st,{message:s.errorMessage})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[De(s.status),o&&s.mediaType==="image"&&s.status==="completed"&&e.jsx(ea,{workspaceId:o,sourceJobId:s.id,title:s.title,sourceAspect:s.aspect??null}),s.status==="planned"&&s.mediaType==="video"&&o&&!s.synthetic&&e.jsxs(E,{size:"sm",className:"h-7 px-2 text-xs",disabled:u.isPending&&u.variables===s.id,onClick:()=>u.mutate(s.id),title:"Send this video to Arcads for rendering",children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),u.isPending&&u.variables===s.id?"Ordering…":s.purpose==="vsl"?"Order VSL":"Order video"]}),s.mediaType==="image"&&o&&!s.synthetic&&(s.status==="planned"?e.jsx(bt,{workspaceId:o,jobId:s.id,title:s.title}):null),s.purpose==="vsl"&&s.status==="awaiting_video"&&s.funnelId&&o&&e.jsxs(E,{size:"sm",className:"h-7 px-2 text-xs",disabled:g.isPending&&g.variables===s.funnelId,onClick:()=>g.mutate(s.funnelId),title:"Send this VSL to Arcads for rendering",children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),g.isPending&&g.variables===s.funnelId?"Ordering…":"Order VSL"]}),(s.status==="failed"||s.status==="cancelled")&&!s.synthetic&&e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs",disabled:f===s.id,onClick:()=>r(h,s.id),children:[e.jsx(et,{className:"mr-1 h-3 w-3"}),"Retry"]}),s.synthetic&&s.status==="missing"&&s.cellId&&o&&(s.mediaType==="image"?e.jsx(bt,{workspaceId:o,cellId:s.cellId,title:s.title}):e.jsxs(E,{size:"sm",className:"h-7 px-2 text-xs",disabled:b.isPending&&b.variables?.rowId===s.id,onClick:()=>b.mutate({rowId:s.id,cellId:s.cellId,mediaType:s.mediaType}),title:"Create job for this cell",children:[e.jsx(Z,{className:"mr-1 h-3 w-3"}),b.isPending&&b.variables?.rowId===s.id?"Ordering…":"Create job"]})),s.outputUrl&&e.jsxs("a",{href:s.outputUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-primary inline-flex items-center gap-1",children:["Open ",e.jsx(Ae,{className:"h-3 w-3"})]})]})]},s.id))}),p&&e.jsx(Pe,{open:D,onOpenChange:i,children:e.jsxs(Ie,{children:[e.jsxs(Fe,{children:[e.jsxs($e,{children:["Delete ",C.size," ",t.toLowerCase(),"?"]}),e.jsx(Te,{children:"Selected rows will be removed from this campaign. Anything already staged into an Advantage+ ad will be unstaged. This cannot be undone."})]}),e.jsxs(qe,{children:[e.jsx(Oe,{children:"Cancel"}),e.jsx(Ee,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{const s=Array.from(C);p(s.map(j=>({kind:h,id:j}))),O(new Set),i(!1)},children:"Delete"})]})]})})]})}function _a({items:t,onRetry:n,retryPendingId:h}){return t.length===0?null:e.jsx(Re,{title:"Funnels",count:t.length,children:e.jsx("ul",{className:"divide-y rounded-md border",children:t.map(r=>e.jsxs("li",{"data-app-row":"",className:"flex items-center gap-3 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-1 text-sm font-medium",children:r.title}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["/",r.slug," · VSL ",r.vslReady?"ready":r.vslStatus??"pending"]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[De(r.state),r.publishedUrl&&e.jsxs("a",{href:r.publishedUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-primary inline-flex items-center gap-1",children:["Open ",e.jsx(Ae,{className:"h-3 w-3"})]})]})]},r.id))})})}function Ma({items:t}){if(t.length===0)return null;const n=t.reduce((r,f)=>(r.total+=1,f.status==="pushed"?r.pushed+=1:f.status==="failed"?r.failed+=1:f.status==="pushing"?r.pushing+=1:r.queued+=1,r),{total:0,queued:0,pushing:0,pushed:0,failed:0}),h=n.total>0?Math.round(n.pushed/n.total*100):0;return e.jsxs(Re,{title:"Meta push progress",headerRight:e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[n.pushed,"/",n.total," ad set queues pushed",n.pushing>0?` · ${n.pushing} pushing`:"",n.queued>0?` · ${n.queued} queued`:"",n.failed>0?` · ${n.failed} failed`:""]}),children:[e.jsxs("div",{className:"mb-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsx(We,{value:h}),e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:"Campaign creation + ad set/ad queue fan-out shown per row below."})]}),e.jsx("ul",{className:"divide-y rounded-md border",children:t.map(r=>{const f=Je(r.status),o=[r.awarenessLevel,r.formatType,r.aspect].filter(
7Boolean).join(" · ");return e.jsxs("li",{"data-app-row":"",className:"flex items-center gap-3 px-3 py-2",children:[e.jsx(at,{url:r.thumbnailUrl,mediaType:r.mediaType,title:r.title}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"line-clamp-1 text-sm font-medium",children:r.title}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[o||"Matrix cell"," · ",r.audienceName||r.audienceId||"Broad / Advantage+"]}),e.jsxs("div",{className:"mt-1 grid gap-1",children:[e.jsx(We,{value:f}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["Ad set: ",r.metaAdSetId?r.metaAdSetId:r.status==="queued"?"queued":"creating"]}),e.jsxs("span",{children:["Ad: ",r.metaAdId?r.metaAdId:r.status==="queued"?"queued":"creating"]})]})]}),r.errorMessage&&(r.status==="failed"||r.status==="cancelled")&&e.jsx(st,{message:r.errorMessage})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:De(r.status)})]},r.id)})})]})}function Pa({items:t,cells:n,onRetry:h,retryPendingId:r}){if(t.length===0)return null;const f=t.filter(d=>!d.parentCellId),o=new Set(f.map(d=>d.id)),p=new Map(n.map(d=>[d.cellId,d])),m=Array.from(new Set(t.map(d=>d.parentCellId??null).filter(d=>!!d&&!o.has(d)))).map(d=>{const u=p.get(d),g=t.find(b=>b.parentCellId===d);return{id:d,title:u?.headline??`Parent cell ${d.slice(0,8)}`,metaAdId:null,status:u?.parts.meta.status==="failed"?"failed":u?.parts.meta.status==="processing"?"pushing":u?.parts.meta.status==="completed"?"pushed":"draft",errorMessage:u?.parts.meta.message??null,productionStatus:null,awarenessLevel:u?.awarenessLevel??g?.awarenessLevel??null,formatType:u?.formatType??g?.formatType??null,aspect:u?.aspect??g?.aspect??null,pushedAt:null,updatedAt:u?.updatedAt??g?.updatedAt??new Date().toISOString(),etaSec:Qs.meta,landingUrl:u?.landingUrl??null,mediaType:u?.previewType??g?.mediaType??null,thumbnailUrl:u?.previewThumbnailUrl??null,campaignName:u?.metaCampaignName??g?.campaignName??null,campaignStatus:g?.campaignStatus??null,actionable:!1}}),k=[...f,...m],T=new Map,_=[];for(const d of t)if(d.parentCellId)if(k.some(u=>u.id===d.parentCellId)){const u=T.get(d.parentCellId)??[];u.push(d),T.set(d.parentCellId,u)}else _.push(d);const y=[];for(const d of k){y.push(d);const u=T.get(d.id);u&&y.push(...u)}return y.push(..._),e.jsx(Re,{title:"Meta ads",count:y.length,children:e.jsx("ul",{className:"divide-y rounded-md border",children:y.map(d=>{const u=!!d.parentCellId,g=u?[]:T.get(d.id)??[],b=!u&&g.length>0?{total:g.length,pushed:g.filter(C=>C.status==="pushed").length,pushing:g.filter(C=>C.status==="pushing"||C.status==="queued").length,failed:g.filter(C=>C.status==="failed").length,draft:g.filter(C=>C.status==="draft"||C.status==="awaiting_video").length}:null;return e.jsxs("li",{"data-app-row":"",className:`flex items-center gap-3 px-3 py-2 ${u?"border-l-2 border-l-primary/40 bg-muted/20 pl-6":""}`,children:[e.jsx(at,{url:d.thumbnailUrl,mediaType:d.mediaType,title:d.title}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"line-clamp-1 text-sm font-medium flex items-center gap-2",children:[d.title,!u&&g.length>0&&e.jsxs("span",{className:"inline-flex items-center rounded border border-emerald-500/40 bg-emerald-500/15 px-1.5 py-px text-[10px] font-semibold uppercase tracking-wide text-emerald-600 dark:text-emerald-400",children:["Parent · ",g.length," variant",g.length===1?"":"s"]}),u&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded border border-primary/30 bg-primary/10 px-1.5 py-px text-[10px] font-medium uppercase tracking-wide text-primary",children:[e.jsx(Z,{className:"h-2.5 w-2.5"}),d.variantKind==="image_variant_bundle"?"Advantage+ bundle":d.variantKind==="image_variant_single"?"Image variant":d.variantKind==="meta_creative_ad"?"Meta pushed ad":d.variantKind==="meta_synced_ad"?"Synced from Meta":"Variant",d.bundleAspects&&d.bundleAspects.length>
70&&e.jsx("span",{className:"ml-1 font-mono normal-case opacity-80",children:d.bundleAspects.join(" · ")})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[d.awarenessLevel,d.formatType,d.aspect].filter(Boolean).join(" · "),d.metaAdId?` · Meta ID ${d.metaAdId}`:""]}),d.campaignName&&e.jsxs("div",{className:"line-clamp-1 text-xs text-muted-foreground",children:["Campaign: ",e.jsx("span",{className:"font-medium text-foreground",children:d.campaignName})]}),b&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"font-medium text-foreground",children:["Variants ",b.pushed,"/",b.total," pushed"]}),b.pushing>0&&e.jsxs("span",{className:"text-primary",children:["· ",b.pushing," in flight"]}),b.failed>0&&e.jsxs("span",{className:"text-destructive",children:["· ",b.failed," failed"]}),b.draft>0&&e.jsxs("span",{children:["· ",b.draft," draft"]})]}),d.errorMessage&&(d.status==="failed"||d.status==="cancelled")&&e.jsx(st,{message:d.errorMessage}),(()=>{const C=ja(d.status),O=d.status==="failed"||d.status==="cancelled";return e.jsxs("div",{className:"mt-1.5 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{value:Je(d.status),className:`h-1 flex-1 ${O?"[&>div]:bg-destructive":""}`}),e.jsxs("span",{className:"shrink-0 text-[10px] tabular-nums text-muted-foreground",children:[Je(d.status),"%"]})]}),e.jsxs("div",{className:`text-[10px] ${O?"text-destructive":"text-muted-foreground"}`,children:[C.step>0&&e.jsxs("span",{className:"font-medium",children:["Stage ",C.step,"/",C.total,": "]}),C.label]})]})})()]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[De(d.status),d.actionable!==!1&&(d.status==="failed"||d.status==="cancelled"||d.status==="pushed"||d.status==="draft")&&e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 px-2 text-xs",disabled:r===d.id,onClick:()=>h(d.id),title:d.status==="pushed"?"Re-push to Meta with all available assets":d.status==="draft"?"Push this ad to Meta now":"Retry push",children:[e.jsx(et,{className:"mr-1 h-3 w-3"}),d.status==="pushed"?"Re-push":d.status==="draft"?"Push":"Retry"]}),d.landingUrl&&e.jsxs("a",{href:d.landingUrl,target:"_blank",rel:"noreferrer",className:"text-xs text-primary inline-flex items-center gap-1",children:["Open ",e.jsx(Ae,{className:"h-3 w-3"})]})]})]},d.id)})})})}const Ia="active_offer_id::",He="__all__";function Ha(){const t=S(cs),n=S(ms),{data:h}=G({queryKey:["workspaces"],queryFn:()=>t({})}),r=(()=>{if(!h?.length)return null;if(typeof window>"u")return h[0];try{const y=window.localStorage.getItem("active_workspace_id");return y?h.find(d=>d.id===y)??h[0]:h[0]}catch{return h[0]}})(),{data:f}=G({queryKey:["assembler-offers",r?.id],queryFn:()=>n({data:{workspaceId:r.id}}),enabled:!!r?.id}),o=r?`${Ia}${r.id}`:null,[p,x]=A.useState(null);A.useEffect(()=>{if(!f||f.length===0||!o){x(null);return}let y=null;try{y=window.localStorage.getItem(o)}catch{y=null}if(y&&f.some(d=>d.id===y))x(y);else{const d=f.find(u=>u.status==="active")??f[0];x(d?.id??null)}},[f,o]);const m=y=>{if(y===He){x(null);return}if(x(y),o)try{window.localStorage.setItem(o,y)}catch{}},k=S(os),{data:T}=G({queryKey:["action-center-state",r?.id],queryFn:()=>k({data:{workspaceId:r.id}}),enabled:!!r?.id,staleTime:3e4}),_=!!T&&!T.flags.hasMatrix;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-end md:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Assembler"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Every matrix cell currently building or recently failed, broken into the parts that ship it: copy, Arcads, funnel, and Meta push. Click ",e.jsx("strong",{children:"Bundles"})," on any row to see its Advantage+ plan (one ad per actor, all aspects bundled). Retry on any failed part — completed parts stay as they are, no credits wasted."]}),r&&e.jsx("div",{className:"mt-2",children:e.jsx(_s,{workspaceId:r.id,variant:"badge"})})]}),f&&f.length>1?e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Offer"}),e.jsxs(re,{value:p??He,onValueChange:m,children:[e.jsx(le,{className:"w-[260px]",children:e.jsx(ie,{placeholder:"All offers"})}),e.jsxs(de,{children:[e.jsx(X,{value:He,children:"All offers"}),f.map(y=>e.jsx(X,{value:y.id,children:y.name},y.id))]})]})]}):null]}),r?_?e.jsxs($t,{children:[e.jsxs(Tt,{children:[e.jsx(qt,{className:"text-base",children:"Nothing to assemble yet"}),e.jsx(Ot,{children:"The Assembler shows live build status for every matrix cell — copy, video render, funnel, and Meta push. Generate your first matrix to start filling this view."})]}),e.jsx(Et,{children:e.jsx(us,{to:"/start",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:"Go to Today →"})})]}):e.jsx(ya,{workspaceId:r.id,offerId:p}):e.jsx(Xe,{className:"h-64 w-full"})]})}
7export{Ha 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.