PageSourceSearch

https://apps.fufa.ai/assets/route-BClvbLvv.js

js fufa.ai collected 2026-10-05 14:27:31 UTC 57,943 bytes, 6 lines download raw bytes

1import{c as ws,a9 as Is,gV as qe,bx as ks,gW as _e,ad as ie,gX as Fs,eZ as je,gN as Ue,b as d,d as Ds,q as ve,t as p,j as e,h as ne,ac as ns,P as is,f as rs,B as z,k as ls,dt as Ps,a as F,eC as ge,g1 as ye,eH as cs,aG as fe,bp as Es,bq as Os,br as zs,bs as Vs,bt as Ms,bw as Rs,o as Fe,gY as Bs,bv as Ls,b0 as De,b1 as Pe,b2 as Ee,b3 as Oe,b4 as ze,fY as ds,b6 as qs,gZ as _s,ba as Us,bb as Ws,bc as Ks,C as $s,bM as Gs,bR as We,V as Hs,g_ as Qs,bN as Ys,bO as Zs,bS as Xs,bP as Js,bz as et,F as st,ay as tt,aJ as at,bf as nt,ds as it,av as Te,aO as os,cg as Ke,p as $e,w as Ge,a7 as rt,ca as lt,l as ms,aF as ct,g$ as dt,J as us,h0 as ot,m as V,K as k,dm as mt,h1 as He,h2 as Ce,h3 as Qe,h4 as ut,h5 as pt,L as ps,W as ae,h6 as ht,eR as xt,bB as gt,bC as ft,O as jt}from"./index-BNSlZW3b.js";import"./branding-provider-DePoo6JG.js";import"./domain-branding-provider-MkpWjPqk.js";import{u as Ve}from"./useLocation-CEZ9XHWf.js";import{D as yt,a as bt,b as vt,h as re,d as Ct}from"./dropdown-menu-CNNIjbdt.js";import{M as St}from"./secondary-nav-store-BF5t__Jl.js";import{I as we}from"./inset-panel-DxGATAgW.js";import{P as Nt,a as Ye,b as At}from"./page-header-DYIHlZ-n.js";import{a as Tt,b as wt,c as It,S as kt}from"./nav-CXBSQmpg.js";import{R as le,a as ce,b as de,c as oe,d as me,e as ue,f as pe,g as he}from"./responsive-alert-dialog-DSvjRwol.js";import{B as Ft}from"./badge-B8Onwl7T.js";import{I as Dt}from"./inline-edit-BEj0SHaC.js";import{C as M,a as R,b as B,d as L,c as hs}from"./card-DgpTAWyl.js";import{C as Pt,T as Et,h as Ot,g as zt,a as Vt}from"./template-send-options-BGiLPpVt.js";import{L as te}from"./loading-button-CdiLx1vU.js";import{u as Mt,b as q,c as Rt,f as Bt,a as Lt,F as qt}from"./form-submit-button-QNy0gx7W.js";import{C as Me}from"./calendar-BtSmVlTW.js";import{F as _,a as U,c as G}from"./field-ChXsvxn4.js";import{g as _t,T as Ut}from"./time-picker-D3PbUl_h.js";import{T as Ze}from"./status-badge-DdOQptHY.js";import{T as Ie,R as Wt,a as Xe}from"./radio-group-Iz43N8wY.js";import{L as Kt}from"./list-checks-BlFVt88L.js";import{A as ke}from"./arrow-left-C9Dss__s.js";import{A as Je}from"./arrow-right-DQq6mJ8R.js";import{S as $t}from"./send-PtzObGCc.js";import{M as xs}from"./message-circle-B0sYmJax.js";import{u as Gt}from"./useInfiniteQuery-DH_qj7DW.js";import{g as Ht,C as Qt}from"./contacts-table-columns-C2d4bfjw.js";import{A as Yt,b as Zt,a as Xt}from"./alert-BcARrQDq.js";import{C as Jt}from"./contact-search-input-CwR1505a.js";import{P as gs}from"./pencil-DRP5YLn6.js";import{S as ea}from"./switch-DmqKj_0n.js";import{W as ee,a as se}from"./wizard-shell-CC65Kr4L.js";import{F as sa}from"./funnel-xk73OM7Q.js";import{W as ta}from"./whatsapp-box-mockup-eX6yhWBk.js";import{W as aa}from"./whatsapp-template-preview-BAWZYU_8.js";import{g as Re,a as fs,b as js,c as ys,C as es,d as na,e as ia}from"./-utils-BnsvEGUy.js";import{P as ra}from"./pause-DG9ZGgPn.js";import{C as la}from"./copy-CR57eaZd.js";import{T as ca}from"./trash-2-CrC1FKyw.js";import"./index-B-Lc1CYs.js";import"./phone-input-49Fw2LII.js";import"./index-Cc2jQODR.js";import"./index-DI_3W3id.js";import"./upload-CVQ8Wr6H.js";import"./image-DxZ4wWTW.js";import"./use-attributes-3d4-2Fv5.js";import"./video-3LztsDoo.js";import"./link-DjnnMG_E.js";import"./useForm-DCj-pjeq.js";import"./filter-builder-DDPhEXFc.js";import"./tooltip-EDcrlS5q.js";import"./combobox-U-gzcTlp.js";import"./shopping-cart-BwzeOTB4.js";import"./undo-2-B7A5ObAJ.js";import"./receipt-BPAuWPe8.js";import"./ban-DXzsT8BK.js";import"./globe-DJI1Lwd1.js";import"./languages-D6NQ5hq0.js";import"./phone-Cu9ZXddO.js";import"./mail-BPywnOCY.js";import"./user-DvWx5BcZ.js";import"./hash-C09A28eM.js";import"./package-Dvbh92da.js";import"./type-whCpKUhL.js";import"./toggle-left-DP11z3FD.js";import"./multi-select-CPc8JNct.js";import"./circle-alert-oneqiEhF.js";import"./layers-BlJH4RsJ.js";import"./data-table-bulk-actions-BVTBtwDx.js";import"./data-table-D_gl7U4M.js";import"./table-D0Em9Wo6.js";import"./arrow-up-B2CzVuwC.js";import"./arrow-down-BRwtLfAR.js";import"./arrow-up-down-Jzb1ohsK.js";import"./formatDistanceToNow-CdHcsOSP.js";import"./use-infinite-scroll-DIMZJis1.js";import"./tag-list-BR2b9SpK.js";import"./currency-C7k9IhzA.js";import"./create-contact-dialog-DLPj_STL.js";import"./form-CxHDHTlK.js";import"./whatsapp-carousel-card-preview-CCzUZmEg.js";import"./eye-CT68w0hZ.js";import"./circle-check-big-BP3k1F9I.js";/**
2 * @license lucide-react v0.544.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const da=[["path",{d:"M4.2 4.2A2 2 0 0 0 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 1.82-1.18",key:"16swn3"}],["path",{d:"M21 15.5V6a2 2 0 0 0-2-2H9.5",key:"yhw86o"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h7",key:"1wap6i"}],["path",{d:"M21 10h-5.5",key:"quycpq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],oa=ws("calendar-off",da),ma=["immediate","scheduled"],ua=["static","dynamic"],pa=["draft","scheduled","running","paused","tier_limit_reached","completed","failed"],ha=["pending","processing","processed"],xa=je(ma),ga=je(ua);je(pa);je(ha);const fa=Is({name:ie().min(1,"Name is required").max(255),description:ie().max(1e3).default(""),type:ga.default("dynamic"),scheduleType:xa.default("immediate"),channelAccountId:qe(Ue.channelAccount,"channel account ID").optional().nullable(),whatsappTemplateId:ie().optional(),templateVariables:Fs.default([]),scheduledAt:_e().nullable(),scheduledTimezone:ie().default("UTC"),endsAt:_e().nullable(),optInStatementAccepted:ks(),segmentId:qe(Ue.segment,"segment ID").optional().nullable()}).superRefine((s,t)=>{s.scheduleType==="scheduled"&&s.scheduledAt&&s.scheduledAt.getTime()<=Date.now()&&t.addIssue({code:"custom",message:"Scheduled date must be in the future",path:["scheduledAt"]}),s.type==="dynamic"&&!s.segmentId&&t.addIssue({code:"custom",message:"Select a segment",path:["segmentId"]}),s.endsAt&&s.endsAt.getTime()<=Date.now()&&t.addIssue({code:"custom",message:"End date must be in the future",path:["endsAt"]}),s.endsAt&&s.scheduleType==="scheduled"&&s.scheduledAt&&s.endsAt.getTime()<=s.scheduledAt.getTime()&&t.addIssue({code:"custom",message:"End date must be after the scheduled start",path:["endsAt"]})});
6function ja(s){const t=s.messageContent,a=s.type==="static"||s.type==="dynamic"?s.type:"dynamic",i=s.scheduleType==="immediate"||s.scheduleType==="scheduled"?s.scheduleType:s.scheduledAt?"scheduled":"immediate";return{name:s.name??"",description:s.description??"",type:a,scheduleType:i,channelAccountId:s.channelAccountId??null,whatsappTemplateId:t?.templateId??void 0,templateVariables:t?.variables??[],scheduledAt:s.scheduledAt?new Date(s.scheduledAt):null,scheduledTimezone:s.scheduledTimezone??"UTC",endsAt:s.endsAt?new Date(s.endsAt):null,optInStatementAccepted:!1,segmentId:s.segmentId??null}}function ya(s,t){return{id:t,name:s.name,description:s.description?.trim()||null,type:s.type,channelAccountId:s.channelAccountId??void 0,messageContent:{templateId:s.whatsappTemplateId,variables:s.templateVariables.length>0?s.templateVariables:void 0},scheduledAt:s.scheduleType==="scheduled"?s.scheduledAt:null,scheduledTimezone:s.scheduleType==="scheduled"||s.endsAt?s.scheduledTimezone:void 0,endsAt:s.endsAt,segmentId:s.type==="dynamic"?s.segmentId??null:null}}function ba(s,t=!0){d.useEffect(()=>{if(!t)return;const a=Ds.campaign.onStatsUpdate.subscribe({id:s},{onData:i=>{i.type==="state"&&ve.invalidateQueries({queryKey:p.campaign.getById.queryKey({id:s})}),ve.invalidateQueries({queryKey:p.campaign.getAnalytics.queryKey({id:s})}),ve.invalidateQueries({queryKey:p.campaign.listBroadcasts.queryKey()})},onError:i=>{console.error("[CampaignStatsSubscription] Error:",i)}});return()=>a.unsubscribe()},[s,t])}function va({incomingTemplateId:s,adoptTemplate:t,saveDraft:a,clearTemplateId:i}){const n=d.useRef(null);d.useEffect(()=>{if(!s||n.current===s)return;n.current=s,t(s);let l=!1;return(async()=>{try{await a()}catch{return}l||i()})(),()=>{l=!0}},[s])}function O(){return Mt()}function Se(s){return s?s.toLocaleDateString("en-US",{day:"2-digit",month:"short",year:"numeric"}):""}function Ne(s){return s?!isNaN(s.getTime()):!1}function Ca({value:s,onChange:t,onOpenChange:a,open:i,placeholder:n="Select date...",className:l,disabled:r=!1,fromDate:o}){const[m,g]=d.useState(!1),b=i!==void 0,v=b?i:m,h=y=>{r||(b||g(y),a?.(y))},j=s?new Date(s):void 0,A=Ne(j),[x,f]=d.useState(A?j:new Date),[u,N]=d.useState(A?Se(j):"");d.useEffect(()=>{if(s){const y=new Date(s);Ne(y)&&(N(Se(y)),f(y))}else N("")},[s]);const S=y=>{y?(t(y.toISOString()),N(Se(y)),f(y)):(t(null),N("")),h(!1)},I=y=>{const P=y.target.value;if(N(P),!P.trim()){t(null);return}const D=new Date(P);if(Ne(D)){if(o&&D<o)return;t(D.toISOString()),f(D)}},T=()=>{t(null),N(""),h(!1)},W=y=>{y.key==="ArrowDown"?(y.preventDefault(),h(!0)):y.key==="Escape"?h(!1):y.key==="Backspace"&&!u&&T()};return e.jsxs("div",{className:ne("relative w-[180px]",l),children:[e.jsx(ns,{value:u,placeholder:n,className:"pr-9",onChange:I,onKeyDown:W,disabled:r}),e.jsxs(is,{open:v,onOpenChange:h,children:[e.jsx(rs,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"ghost",size:"icon",className:"absolute top-1/2 right-1 size-7 -translate-y-1/2",disabled:r,children:[e.jsx(Me,{className:"size-4"}),e.jsx("span",{className:"sr-only",children:"Select date"})]})}),e.jsxs(ls,{className:"w-auto p-0",align:"end",sideOffset:8,children:[e.jsx(Ps,{mode:"single",selected:A?j:void 0,month:x,onMonthChange:f,onSelect:S,captionLayout:"dropdown",disabled:o?{before:o}:void 0}),A&&e.jsx("div",{className:"border-t p-2",children:e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:T,children:"Clear"})})]})]})]})}function Sa(s){const t=d.useMemo(()=>{const m=new Date;return m.setHours(0,0,0,0),m},[]),a=s.state.value?.toISOString(),i=s.state.value?`${String(s.state.value.getHours()).padStart(2,"0")}:${String(s.state.value.getMinutes()).padStart(2,"0")}`:null,l=(s.state.value?s.state.value.toDateString()===new Date().toDateString():!1)?_t():void 0;return{today:t,dateValue:a,timeValue:i,minTime:l,handleDateChange:m=>{if(!m){s.handleChange(null);return}const g=new Date(m);if(Number.isNaN(g.getTime()))return;const b=s.state.value,v=b?.getHours()??0,h=b?.getMinutes()??0;g.setHours(v,h,0,0),s.handleChange(g)},handleTimeChange:m=>{if(!m||!s.state.value)return;const[g,b]=m.split(":"),v=Number(g),h=Number(b);if(!Number.isFinite(v)||!Number.isFinite(h))return;const j=new Date(s.state.value);j.setHours(v,h,0,0),s.handleChange(j)}}}function Na({current:s,userEditableVarDefs:t,templateMediaDefs:a,templateJustChanged:i}){const n=cs(s),l=new Set(t.map(u=>u.key)),r=n.textVariables.filter(u=>l.has(u.key)),o=new Set(r.map(u=>u.key)),m=s.filter(u=>u.type==="header_media"||u.type==="card_media"),g=a.length>0&&m.length===0,b=n.textVariables.some(u=>!l.has(u.key));if(!(i||g||b||t.length>0&&r.length===0||r.some(u=>ge(u.key))||t.some(u=>!o.has(u.key))))return null;const h=r.filter(u=>!ge(u.key)).reduce((u,N)=>(u[N.key]=N.value,u),{}),j=t.map(u=>({type:u.type,key:u.key,value:h[u.key]??""})),A=s.filter(u=>u.type==="button"&&ye(u)),f=i||g?a:m;return[...j,...A,...f]}function Aa({current:s,textVariables:t,key:a,value:i,defType:n}){const l=t.some(o=>o.key===a)?t.map(o=>o.key===a?{...o,value:i}:o):[...t,{type:n,key:a,value:i}],r=s.filter(ye);return[...l,...r]}function Ta({field:s,whatsappTemplateId:t}){const a=t??"",{data:i}=F({...p.whatsappTemplate.getById.queryOptions({id:a}),enabled:!!t}),n=i?i.variables??[]:[],l=n.filter(x=>
6(x.type==="body"||x.type==="header"||x.type==="button")&&!ge(x.key)&&!ye(x)),r=n.filter(x=>x.type==="header_media"||x.type==="card_media"),o=l.map(x=>`${x.type}:${x.key}`).join("\0"),m=r.map(x=>x.type==="header_media"?"header_media":`card_media:${x.cardIndex}`).join("\0"),g=d.useRef(void 0),b=d.useRef(!1);d.useEffect(()=>{if(t&&!i)return;const x=!b.current,f=g.current,u=!x&&f!==t;g.current=typeof t=="string"?t:void 0,b.current=!0;const N=s.state.value??[],S=Na({current:N,userEditableVarDefs:l,templateMediaDefs:r,templateJustChanged:u});S&&s.handleChange(S)},[t,i?.id,o,m]);const v=s.state.value??[],h=cs(v);return{userEditableVarDefs:l,getValue:x=>h.textRecord[x]??"",setValue:(x,f)=>{const u=l.find(S=>S.key===x),N=Aa({current:v,textVariables:h.textVariables,key:x,value:f,defType:u?.type??"body"});s.handleChange(N)}}}const bs=d.createContext(null);function Be(){return d.useContext(bs)}function ss({children:s,...t}){return e.jsx(bs.Provider,{value:t,children:s})}function wa({campaign:s,children:t}){const[a,i]=d.useState(!1),n=Be(),l=(n?.currentStep??1)===(n?.totalSteps??5),r=n?.currentStep??1,o=n?.totalSteps??5,m=()=>{l?i(!0):n?.onNext()};return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[e.jsxs("div",{className:"shrink-0",children:[e.jsxs("div",{className:"hidden lg:grid lg:grid-cols-2 h-14",children:[e.jsxs("div",{className:"bg-card flex items-center gap-2 min-w-0 px-6",children:[e.jsx("div",{className:"flex size-8 items-center justify-center rounded-md border bg-card text-muted-foreground",children:e.jsx(Kt,{className:"size-4"})}),e.jsxs("span",{className:"text-sm font-medium",children:["Step ",r," ",e.jsxs("span",{className:"text-muted-foreground",children:["/ ",o]})]})]}),e.jsxs("div",{className:"bg-surface-1/60 flex items-center justify-between gap-2 px-6",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>n?.onBack(),disabled:!n,className:"text-muted-foreground hover:text-foreground",children:[e.jsx(ke,{className:"size-4"}),"Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{resource:"campaign",permission:"update",children:e.jsx(te,{className:"rounded-full min-w-32 h-10",variant:"outline",onClick:()=>n?.onSaveAndExit(),disabled:!n||n.isSaving,loading:n?.isSaving,children:"Save and exit"})}),e.jsx(te,{className:"rounded-full min-w-32 h-10",onClick:m,disabled:!n||!l&&!n.canAdvance||n.isAdvancing||n.isActivating,loading:l?n?.isActivating:n?.isAdvancing,children:l?e.jsxs(e.Fragment,{children:["Activate",e.jsx(Je,{className:"size-4"})]}):e.jsxs(e.Fragment,{children:["Next",e.jsx(Je,{className:"size-4"})]})})]})]})]}),e.jsxs("div",{className:"lg:hidden px-4 py-3 border-b",children:[e.jsx("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-2",children:e.jsxs("span",{children:["Step ",r," of ",o]})}),e.jsx("div",{className:"h-1 bg-border rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full",style:{width:`${r/o*100}%`}})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto lg:overflow-hidden",children:t}),e.jsxs("div",{className:"lg:hidden shrink-0 border-t bg-background flex items-center gap-2 p-3",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>n?.onBack(),disabled:!n,className:"text-muted-foreground hover:text-foreground shrink-0",children:[e.jsx(ke,{className:"size-4"}),"Back"]}),e.jsx(fe,{resource:"campaign",permission:"update",children:e.jsx(te,{className:"rounded-full flex-1",variant:"outline",onClick:()=>n?.onSaveAndExit(),disabled:!n||n.isSaving,loading:n?.isSaving,children:"Save"})}),e.jsx(te,{className:"rounded-full flex-1",onClick:m,disabled:!n||!l&&!n.canAdvance||n.isAdvancing||n.isActivating,loading:l?n?.isActivating:n?.isAdvancing,children:l?"Activate":"Next"})]}),e.jsx(Es,{open:a,onOpenChange:i,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(zs,{children:[e.jsx(Vs,{children:"Activate campaign?"}),e.jsx(Ms,{children:n?.isTemplatePending?e.jsxs(e.Fragment,{children:['"',s.name,'" will start sending automatically as soon as WhatsApp approves your template. You can cancel it before then.']}):e.jsxs(e.Fragment,{children:['This will send "',s.name,'" to all selected recipients. This action cannot be undone.']})})]}),e.jsxs(Rs,{children:[e.jsx(z,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>{n?.onActivate(),i(!1)},disabled:!n||n.isActivating,children:[e.jsx($t,{className:"size-4"}),n?.isActivating?"Sending...":n?.isTemplatePending?"Schedule":"Send now"]})]})]})})]})}const Ae=["approved","pending"];function Ia({field:s,channelAccountId:t}
6){const a=O(),[i,n]=d.useState(!1),[l,r]=d.useState(!1),o=Fe(),m=Be(),{campaignId:g}=Bs({from:"/_app/campaigns/$campaignId"}),{data:b=[]}=F(p.channel.listAccounts.queryOptions({channelType:"whatsapp"})),h=b.find(S=>S.id===t)?.businessAccountId,{data:j=[]}=F({...p.whatsappTemplate.list.queryOptions({businessAccountId:h??""}),enabled:!!h}),A=S=>{const I=Ae.indexOf(S);return I===-1?Ae.length:I},x=d.useMemo(()=>[...j.filter(I=>I.category==="marketing"&&(Ae.includes(I.status)||I.id===s.state.value))].sort((I,T)=>A(I.status)-A(T.status)),[j,s.state.value]),f=x.find(S=>S.id===s.state.value);return{open:i,setOpen:n,isLeavingToCreate:l,templates:x,selected:f,handleSelect:S=>{a.setFieldValue("whatsappTemplateId",S),a.setFieldValue("templateVariables",[]),n(!1)},handleStartCreation:async()=>{if(!l){if(n(!1),m){r(!0);try{await m.onSaveDraft()}catch{return}finally{r(!1)}}o({to:"/settings/templates/whatsapp/new",search:{accountId:h??void 0,campaignId:g}})}}}}const ka="__create__";function Fa(){const s=q();return e.jsxs(_,{children:[e.jsx(U,{htmlFor:s.name,children:"Campaign name"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"The name is only used internally."}),e.jsx(ns,{id:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:t=>s.handleChange(t.target.value),placeholder:"e.g. Summer newsletter"}),e.jsx(G,{errors:s.state.meta.errors})]})}function Da(){const s=q();return e.jsxs(_,{children:[e.jsx(U,{htmlFor:s.name,children:"Description"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Optional notes about the goal or context of this campaign."}),e.jsx(qs,{id:s.name,value:s.state.value??"",onBlur:s.handleBlur,onChange:t=>s.handleChange(t.target.value),placeholder:"e.g. Drive sign-ups for the August launch event",rows:4}),e.jsx(G,{errors:s.state.meta.errors})]})}function Pa(){const s=q(),t=O(),{data:a=[]}=F(p.channel.listAccounts.queryOptions({channelType:"whatsapp"}));d.useEffect(()=>{a.length>0&&!s.state.value&&t.setFieldValue("channelAccountId",a[0].id)},[a,s.state.value,t]);const i=n=>{t.setFieldValue("channelAccountId",n),t.setFieldValue("whatsappTemplateId",void 0),t.setFieldValue("templateVariables",[])};return e.jsxs(_,{children:[e.jsx(U,{children:"WhatsApp number"}),e.jsxs(De,{value:s.state.value??"",onValueChange:i,children:[e.jsx(Pe,{className:"w-full",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"size-4 text-green-600"}),e.jsx(Ee,{placeholder:"Select WhatsApp number"})]})}),e.jsx(Oe,{children:a.map(n=>e.jsx(ze,{value:n.id,children:ds(n)},n.id))})]}),e.jsx(G,{errors:s.state.meta.errors})]})}function Ea(){const s=q(),t=O();return e.jsx(t.Subscribe,{selector:a=>
6a.values.channelAccountId,children:a=>e.jsx(Oa,{field:s,channelAccountId:a})})}function Oa({field:s,channelAccountId:t}){const{open:a,setOpen:i,isLeavingToCreate:n,templates:l,selected:r,handleSelect:o,handleStartCreation:m}=Ia({field:s,channelAccountId:t});return e.jsxs(_,{children:[e.jsx(U,{children:"WhatsApp template"}),e.jsxs(is,{open:a,onOpenChange:i,children:[e.jsx(rs,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"outline",role:"combobox","aria-expanded":a,disabled:!t,className:"w-full justify-between font-normal",children:[r?e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate",children:r.name}),e.jsx(Ze,{status:r.status})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select template"}),e.jsx($s,{className:"size-4 shrink-0 opacity-50"})]})}),e.jsx(ls,{className:"w-(--radix-popover-trigger-width) p-0",align:"start",children:e.jsxs(Gs,{children:[e.jsxs(We,{value:ka,onSelect:()=>void m(),disabled:n,className:"cursor-pointer",children:[e.jsx(Hs,{className:"size-4"}),"Create a new template"]}),e.jsx(Qs,{}),e.jsx(Ys,{placeholder:"Search templates..."}),e.jsxs(Zs,{children:[e.jsx(Xs,{children:"No templates found."}),e.jsx(Js,{children:l.map(g=>e.jsx(We,{value:g.name,onSelect:()=>o(g.id),className:"cursor-pointer",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:g.name}),e.jsx(Ze,{status:g.status})]})},g.id))})]})]})})]}),e.jsx(G,{errors:s.state.meta.errors})]})}function za(){const s=q(),t=O();return e.jsx(t.Subscribe,{selector:a=>
6a.values.whatsappTemplateId,children:a=>e.jsx(Va,{field:s,whatsappTemplateId:a})})}function Va({field:s,whatsappTemplateId:t}){const{userEditableVarDefs:a,getValue:i,setValue:n}=Ta({field:s,whatsappTemplateId:t});return a.length===0?null:e.jsx("div",{className:"space-y-4",children:a.map(l=>e.jsxs(_,{children:[e.jsx(U,{children:_s(l.key)}),e.jsxs(Us,{children:[e.jsx(Ws,{value:i(l.key),onChange:r=>n(l.key,r.target.value),placeholder:"Enter text or insert variable"}),e.jsx(Ks,{align:"inline-end",children:e.jsx(Pt,{onSelect:r=>n(l.key,r)})})]})]},l.key))})}function Ma(){const s=O();return e.jsx(s.Subscribe,{selector:t=>{const a=t.values;return{whatsappTemplateId:a.whatsappTemplateId,templateVariables:a.templateVariables}},children:t=>e.jsx(Ra,{form:s,whatsappTemplateId:t.whatsappTemplateId,templateVariables:t.templateVariables??[]})})}function Ra({form:s,whatsappTemplateId:t,templateVariables:a}){const{data:i}=F({...p.whatsappTemplate.getById.queryOptions({id:t??""}),enabled:!!t});return i?e.jsx(Et,{template:i,variables:a,onVariablesChange:n=>s.setFieldValue("templateVariables",n)}):null}function Ba(){const s=q(),t=O(),a=i=>{s.handleChange(i),i==="immediate"&&t.setFieldValue("scheduledAt",null)};return e.jsxs(_,{children:[e.jsx(U,{children:"When would you like to send this campaign?"}),e.jsxs("div",{className:"flex flex-col gap-3 mt-2",children:[e.jsxs("label",{className:"flex items-start gap-3 rounded-lg border p-4 cursor-pointer hover:bg-muted/50 has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5",children:[e.jsx("input",{type:"radio",name:"scheduleType",checked:s.state.value==="immediate",onChange:()=>a("immediate"),className:"mt-1 size-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Send immediately"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"If you want to send your campaign immediately."})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg border p-4 cursor-pointer hover:bg-muted/50 has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5",children:[e.jsx("input",{type:"radio",name:"scheduleType",checked:s.state.value==="scheduled",onChange:()=>a("scheduled"),className:"mt-1 size-4"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Select time"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Plan your campaign for a later date."})]})]})]}),e.jsx(G,{errors:s.state.meta.errors})]})}function La(){return e.jsx(vs,{label:"Date and time"})}function qa(){return e.jsx(vs,{label:"End date (optional)",description:"Stop sending remaining messages after this time."})}function vs({label:s,description:t}){const a=q(),{today:i,dateValue:n,timeValue:l,minTime:r,handleDateChange:o,handleTimeChange:m}=Sa(a);return e.jsxs(_,{children:[e.jsx(U,{children:s}),t?e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:t}):null,e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(Ca,{value:n,onChange:o,placeholder:"Select date",className:"w-full",fromDate:i}),e.jsx(Ut,{value:l,onChange:m,placeholder:"Select time",className:"w-full",disabled:!a.state.value,minTime:r})]}),e.jsx(G,{errors:a.state.meta.errors})]})}function _a(){const s=q();return d.useEffect(()=>{if(s.state.value)return;const t=Intl.DateTimeFormat().resolvedOptions().timeZone,a=Ie.some(i=>i.value===t);s.handleChange(a?t:"UTC")},[s]),e.jsxs(_,{children:[e.jsx(U,{children:"Timezone"}),e.jsxs(De,{value:s.state.value??"UTC",onValueChange:s.handleChange,children:[e.jsx(Pe,{className:"w-full",children:e.jsx(Ee,{placeholder:"Select timezone"})}),e.jsx(Oe,{children:Ie.map(t=>e.jsx(ze,{value:t.value,children:t.label},t.value))})]}),e.jsx(G,{errors:s.state.meta.errors})]})}const Ua="https://developers.facebook.com/docs/whatsapp/guides/opt-in";function Wa(){const s=q();return e.jsxs(_,{children:[e.jsx(U,{children:"Opt-in statement"}),e.jsxs("label",{className:"mt-2 flex items-start gap-3 rounded-lg border p-4",children:[e.jsx(Ls,{checked:s.state.value,onCheckedChange:t=>s.handleChange(t===!0),className:"mt-0.5"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["I hereby declare that I have the consent of the selected contacts to contact them with the selected content."," ",e.jsx("a",{href:Ua,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"See Meta Guidelines."})]})]}),e.jsx(G,{errors:s.state.meta.errors})]})}const Ka={CampaignNameField:Fa,CampaignDescriptionField:Da,CampaignChannelAccountIdField:Pa,CampaignWhatsappTemplateIdField:Ea,CampaignTemplateAttributeValuesField:za,CampaignScheduleTypeField:Ba,CampaignScheduledAtField:La,CampaignEndsAtField:qa,CampaignScheduledTimezoneField:_a,CampaignOptInStatementAcceptedField:Wa},$a={FormSubmitButton:qt},{useAppForm:Ga}=Rt({fieldContext:Bt,formContext:Lt,fieldComponents:Ka,formComponents:$a});function Ha(s){return Ga(s)}function Qa(){const s=O();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Template settings"})}),e.jsxs(L,{className:"space-y-6",children:[e.jsx(s.AppField,{name:"channelAccountId",children:t=>e.jsx(t.CampaignChannelAccountIdField,{})}),e.jsx(s.AppField,{name:"whatsappTemplateId",children:t=>e.jsx(t.CampaignWhatsappTemplateIdField,{})})]})]}),e.jsx(s.Subscribe,{selector:t=>t.values.whatsappTemplateId,children:t=>e.jsx(Ya,{whatsappTemplateId:t})})]})}function Ya({whatsappTemplateId:s}
6){const t=O(),{data:a}=F({...p.whatsappTemplate.getById.queryOptions({id:s??""}),enabled:!!s});if(!s||a?.status!=="approved"&&a?.status!=="pending")return null;const n=(a.variables??[]).some(r=>(r.type==="body"||r.type==="header"||r.type==="button")&&!ge(r.key)&&!ye(r)),l=Ot(a)||!!zt(a)||Vt(a).length>0||a.templateType==="carousel"||a.templateType==="limited_time_offer"&&!!a.ltoHasExpiration;return!n&&!l?null:e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Customize message"})}),e.jsxs(L,{className:"space-y-6",children:[e.jsx(t.AppField,{name:"templateVariables",children:r=>e.jsx(r.CampaignTemplateAttributeValuesField,{})}),e.jsx(Ma,{})]})]})}const ts={logic:"and",conditions:[{field:"optIn",operator:"eq",value:!0}]};function Za(s){return s?{logic:"and",conditions:[ts,s]}:ts}function Xa({recipientCount:s=0,onBack:t,onSelect:a,isSaving:i=!1}){const[n,l]=d.useState(""),[r,o]=d.useState(""),[m,g]=d.useState(null),[b,v]=d.useState(!1),h=d.useRef(null),j=et(w=>{o(w)},300),A=d.useMemo(()=>Za(m),[m]),x=d.useCallback(()=>{v(!1),h.current?.()},[]),f=d.useCallback(w=>{l(w),j(w),x()},[j,x]),u=d.useCallback(w=>{x(),g(w)},[x]),{data:N=[]}=F(p.contact.filterMetadata.queryOptions()),{data:S,isLoading:I,isFetchingNextPage:T,hasNextPage:W,fetchNextPage:y}=Gt(p.contact.list.infiniteQueryOptions({limit:25,filter:A,search:r||void 0},{getNextPageParam:w=>w.nextCursor??void 0})),P=d.useMemo(()=>S?.pages.flatMap(w=>w.items)??[],[S]),{data:D}=F({...p.contact.count.queryOptions({filter:A,search:r||void 0}),enabled:b}),{vertical:E}=st(),K=E==="ecommerce",{data:H}=F({...p.ecommerce.listStores.queryOptions(),enabled:K}),Q=H?.[0]?.currency,X=d.useMemo(()=>Ht({vertical:E,currency:Q}),[E,Q]),C=d.useCallback(w=>w.mode==="ids"?{mode:"ids",contactIds:w.contactIds}:{mode:"all",filter:A,search:r||void 0,excludeIds:w.excludeIds.length?w.excludeIds:void 0},[A,r]),Y=d.useMemo(()=>[{label:i?"Saving...":"Add to audience",icon:e.jsx(tt,{className:"size-4"}),disabled:i,onAction:w=>a(C(w))}],[C,i,a]);return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"shrink-0 border-b bg-background px-6 py-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"mt-0.5 size-8 shrink-0",onClick:t,disabled:i,"aria-label":"Back",children:e.jsx(ke,{className:"size-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-xl font-semibold truncate",children:"Select recipients"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s>0?`This replaces your current audience of ${s.toLocaleString()} contact${s!==1?"s":""}.`:"Only opted-in contacts you select will be included."})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 px-6 py-4",children:e.jsx(Qt,{data:P,columns:X,isLoading:I,isFetchingNextPage:T,hasNextPage:W,onLoadMore:()=>y(),bulkActions:Y,clearSelectionRef:h,search:n,onSearchChange:f,filter:m,onFilterApply:u,filterFields:N,totalCount:D,isSelectAllAcrossPages:b,onSelectAllAcrossPages:()=>v(!0),onClearSelectAllAcrossPages:()=>v(!1),showColumnToggle:!1,searchPlaceholder:"Search for contact...",emptyTitle:"No contacts found",emptyDescription:"Try adjusting your search or filters."})})]})}function Ja(){const s=O();return e.jsxs(M,{children:[e.jsxs(R,{children:[e.jsx(B,{className:"text-lg font-semibold",children:"Campaign details"}),e.jsx(hs,{children:"Give your campaign a name and an optional description."})]}),e.jsxs(L,{className:"space-y-6",children:[e.jsx(s.AppField,{name:"name",children:t=>e.jsx(t.CampaignNameField,{})}),e.jsx(en,{}),e.jsx(s.AppField,{name:"description",children:t=>e.jsx(t.CampaignDescriptionField,{})})]})]})}function en(){return e.jsx("div",{className:"rounded-lg border bg-surface-1/90 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary",children:e.jsx(at,{className:"size-4"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Good naming makes life easier"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use a name that describes the purpose, offer, or audience of this campaign."})]})]})})}function sn({recipientCount:s,onJumpToStep:t}){const a=O();return e.jsxs("div",{className:"space-y-6",children:[e.jsx(tn,{}),e.jsx(a.Subscribe,{selector:i=>{const n=i.values;return{name:n.name,channelAccountId:n.channelAccountId,whatsappTemplateId:n.whatsappTemplateId,templateVariables:n.templateVariables??[],type:n.type??"dynamic",segmentId:n.segmentId,scheduleType:n.scheduleType??"immediate",scheduledAt:n.scheduledAt,scheduledTimezone:n.scheduledTimezone,endsAt:n.endsAt}},children:i=>e.jsx(nn,{values:i,recipientCount:s,onJumpToStep:t})}),e.jsx(an,{})]})}function tn(){const s=Be(),[t,a]=d.useState(null),i=()=>{t&&s?.onSendTest(t.id)};return e.jsxs(M,{children:[e.jsxs(R,{children:[e.jsx(B,{children:"Test campaign"}),e.jsx(hs,{children:"Send a test message to a contact to preview how the campaign will look."})]}),e.jsxs(L,{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Jt,{selectedContact:t,onSelectContact:a,onClearContact:()=>a(null),className:"flex-1 border rounded-md",placeholder:"Search a contact to test",phoneOnly:!0}),e.jsx(te,{variant:"outline",onClick:i,disabled:!s||!t||s.isSendingTest,loading:s?.isSendingTest,children:"Test"})]})]})}function an(){const s=O();return e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Compliance & consent"})}),e.jsx(L,{children:e.jsx(s.AppField,{name:"optInStatementAccepted",children:t=>e.jsx(t.CampaignOptInStatementAcceptedField,{})})})]})}function nn({values:s,recipientCount:t,onJumpToStep:a}){const{data:i}
6=F(p.channel.listAccounts.queryOptions({channelType:"whatsapp"})),{data:n}=F({...p.whatsappTemplate.getById.queryOptions({id:s.whatsappTemplateId??""}),enabled:!!s.whatsappTemplateId}),{data:l}=F({...p.segment.getById.queryOptions({id:s.segmentId??""}),enabled:s.type==="dynamic"&&!!s.segmentId}),r=Array.isArray(i)?i.find(v=>v.id===s.channelAccountId):void 0,o=r?ds(r):"—",m=s.type==="static"?`${t.toLocaleString()} contact${t===1?"":"s"} selected`:l?`Segment: ${l.name}`:"Segment not selected",g=rn(s),b=n?.status==="pending";return e.jsxs(e.Fragment,{children:[b&&e.jsxs(Yt,{className:"mb-6",children:[e.jsx(nt,{}),e.jsx(Zt,{children:"Waiting on template approval"}),e.jsxs(Xt,{children:["This campaign will go live once WhatsApp approves your template. Approval is usually quick but can take up to 24–48 hours.",e.jsx("br",{}),"If Meta rejects the template, this campaign returns to draft so you can fix it and resubmit."]})]}),e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Campaign summary"})}),e.jsx(L,{className:"p-0",children:e.jsxs("div",{className:"divide-y",children:[e.jsx(J,{icon:e.jsx(it,{className:"size-4"}),label:"Campaign name",value:s.name?.trim()||"Untitled campaign",onEdit:()=>a(1)}),e.jsx(J,{icon:e.jsx(xs,{className:"size-4"}),label:"Channel & template",value:n?`${o} · ${n.name}`:`${o} · No template selected`,onEdit:()=>a(2)}),e.jsx(J,{icon:e.jsx(Te,{className:"size-4"}),label:"Audience",value:m,onEdit:()=>a(3)}),e.jsx(J,{icon:e.jsx(Me,{className:"size-4"}),label:"Scheduled time",value:g,onEdit:()=>a(4)}),s.endsAt&&e.jsx(J,{icon:e.jsx(oa,{className:"size-4"}),label:"Ends at",value:Cs(s.endsAt,s.scheduledTimezone),onEdit:()=>a(4)}),e.jsx(J,{icon:e.jsx(os,{className:"size-4"}),label:"Smart Retry",value:"On"})]})})]})]})}function J({icon:s,label:t,value:a,onEdit:i}){return e.jsxs("div",{className:"flex items-start justify-between gap-4 px-6 py-4",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-muted",children:s}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-0.5",children:t}),e.jsx("p",{className:"text-sm font-medium text-foreground wrap-break-word",children:a})]})]}),i&&e.jsx(z,{variant:"ghost",size:"icon",className:"size-8 shrink-0",onClick:i,"aria-label":`Edit ${t}`,children:e.jsx(gs,{className:"size-3.5"})})]})}function Cs(s,t){const a=s.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),i=Ie.find(n=>n.value===t)?.label??t??"UTC";return`${a} (${i})`}function rn(s){return s.scheduleType==="immediate"||!s.scheduledAt?"Send immediately":Cs(s.scheduledAt,s.scheduledTimezone)}function ln(){const s=O();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Schedule"})}),e.jsxs(L,{className:"space-y-6",children:[e.jsx(s.AppField,{name:"scheduleType",children:t=>e.jsx(t.CampaignScheduleTypeField,{})}),e.jsx(s.Subscribe,{selector:t=>t.values.scheduleType,children:t=>t==="scheduled"?e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsx(s.AppField,{name:"scheduledAt",children:a=>e.jsx(a.CampaignScheduledAtField,{})}),e.jsx(s.AppField,{name:"scheduledTimezone",children:a=>e.jsx(a.CampaignScheduledTimezoneField,{})})]}):null}),e.jsx(s.AppField,{name:"endsAt",children:t=>e.jsx(t.CampaignEndsAtField,{})}),e.jsx(s.Subscribe,{selector:t=>({scheduleType:t.values.scheduleType,endsAt:t.values.endsAt}),children:({scheduleType:t,endsAt:a})=>t!=="scheduled"&&a?e.jsx(s.AppField,{name:"scheduledTimezone",children:i=>e.jsx(i.CampaignScheduledTimezoneField,{})}):null})]})]}),e.jsx(cn,{})]})}function cn(){return e.jsx("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary",children:e.jsx(os,{className:"size-4"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Smart Retry on WhatsApp"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Improve delivery rates with Smart Retry, which re-sends undelivered WhatsApp messages every 24 hours due to Meta's frequency capping."})]})]}),e.jsx(ea,{checked:!0,disabled:!0,"aria-label":"Smart Retry on WhatsApp"})]})})}const xe=["bg-blue-100 text-blue-700","bg-emerald-100 text-emerald-700","bg-amber-100 text-amber-700","bg-purple-100 text-purple-700","bg-rose-100 text-rose-700"];function dn({recipientCount:s,onSelectRecipients:t}){const a=O();return e.jsx(a.Subscribe,{selector:i=>({type:i.values.type??"dynamic",segmentId:i.values.segmentId,channelAccountId:i.values.channelAccountId}),children:({type:i,segmentId:n,channelAccountId:l})=>e.jsx(on,{form:a,type:i,segmentId:n,channelAccountId:l,recipientCount:s,onSelectRecipients:t})})}function on({form:s,type:t,segmentId:a,channelAccountId:i,recipientCount:n,onSelectRecipients:l}){const{data:r=[],isLoading:o}=F(p.segment.list.queryOptions({entityType:"contacts"})),{data:m,isLoading:g}=F({...p.campaign.estimateRecipients.queryOptions({segmentId:t==="dynamic"?a??null:null,channelAccountId:i??null}),enabled:t==="dynamic"&&!!a}),b=h=>{const j=h;s.setFieldValue("type",j),j==="static"&&s.setFieldValue("segmentId",null)},v=h=>{s.setFieldValue("segmentId",h)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Audience source"})}),e.jsx(L,{children:e.jsxs(Wt,{value:t,onValueChange:b,className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5",children:[e.jsx(Xe,{value:"static",id:"campaign-type-static",className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(Ke,{htmlFor:"campaign-type-static",className:"text-sm font-medium cursor-pointer",children:"Static"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose specific contacts now"})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/5",children:[e.jsx(Xe,{value:"dynamic",id:"campaign-type-dynamic",className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(Ke,{htmlFor:"campaign-type-dynamic",className:"text-sm font-medium cursor-pointer",children:"Dynamic"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use a saved segment at send time"})]})]})]})})]}),t==="static"&&e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Contact selection"})}),e.jsx(L,{children:e.jsx(mn,{count:n,onSelectRecipients:l})})]}),t==="dynamic"&&e.jsxs(M,{children:[e.jsx(R,{children:e.jsx(B,{children:"Saved segment"})}),e.jsx(L,{children:e.jsx(un,{segments:r,segmentsLoading:o,selectedSegmentId:a??"",onSegmentChange:v,estimate:m,estimateLoading:g})})]})]})}function mn({count:s,onSelectRecipients:t}){return s>0?e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex -sp
6ace-x-2",children:[Array.from({length:Math.min(s,5)}).map((a,i)=>e.jsx($e,{className:ne("size-8 border-2 border-background",xe[i%xe.length]),children:e.jsx(Ge,{className:ne("text-xs font-medium",xe[i%xe.length]),children:e.jsx(Te,{className:"size-3.5"})})},i)),s>5&&e.jsx($e,{className:"size-8 border-2 border-background bg-muted",children:e.jsxs(Ge,{className:"text-[10px] font-semibold text-muted-foreground bg-muted",children:["+",s-5]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:[s.toLocaleString()," contact",s!==1?"s":""," selected"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients of your campaign"})]}),e.jsx(z,{variant:"outline",size:"sm",type:"button",onClick:t,children:"Change"})]})}):e.jsxs("div",{className:"flex flex-col items-center gap-3 py-4 rounded-lg border bg-muted/30",children:[e.jsx("div",{className:"flex size-12 items-center justify-center rounded-full bg-muted",children:e.jsx(Te,{className:"size-5 text-muted-foreground"})}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"No recipients selected"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Choose who will receive this campaign"})]}),e.jsx(z,{variant:"outline",type:"button",onClick:t,children:"Select recipients"})]})}function un({segments:s,segmentsLoading:t,selectedSegmentId:a,onSegmentChange:i,estimate:n,estimateLoading:l}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(De,{value:a,onValueChange:i,children:[e.jsx(Pe,{className:"h-10 w-full max-w-[380px]",children:e.jsx(Ee,{placeholder:t?"Loading segments...":"Select a segment"})}),e.jsxs(Oe,{children:[s.map(r=>e.jsx(ze,{value:r.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"size-3.5 text-muted-foreground"}),r.name]})},r.id)),s.length===0&&!t&&e.jsx("div",{className:"px-2 py-4 text-xs text-muted-foreground text-center",children:"No segments found. Create one in Contacts."})]})]}),a&&e.jsx(pn,{estimate:n,loading:l})]})}function pn({estimate:s,loading:t}){return t?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-2",children:[e.jsx(rt,{className:"size-3 animate-spin"}),"Estimating recipients..."]}):s?e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total matching"}),e.jsx("span",{className:"font-semibold",children:s.total.toLocaleString()})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Opted in"}),e.jsx("span",{className:"font-semibold",children:s.optedIn.toLocaleString()})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground pt-1 border-t",children:["~",s.optedIn.toLocaleString()," opted-in contacts will receive this campaign"]})]}):null}function as(){const s=O();return e.jsx(s.Subscribe,{selector:t=>({whatsappTemplateId:t.values.whatsappTemplateId,templateVariables:t.values.templateVariables}),children:({whatsappTemplateId:t,templateVariables:a})=>e.jsx(hn,{whatsappTemplateId:t,templateVariables:a??[]})})}function hn({whatsappTemplateId:s,templateVariables:t}){const a=s??"",{data:i}=F({...p.whatsappTemplate.getById.queryOptions({id:a}),enabled:!!s});return i?e.jsx(aa,{template:i,templateVariables:t,className:"h-full min-h-0"}):e.jsx(ta,{className:"h-full min-h-[200px]",children:e.jsx(lt,{headerType:"none",body:"",emptyPlaceholder:"Select a template to see the preview"})})}function xn({campaign:s}){const t=ms(),a=Fe(),[i,n]=d.useState(!1),[l,r]=d.useState(s.targetCount??0),[o,m]=d.useState(!1),[g,b]=d.useState(!1),v=ct({from:"/_app/campaigns/$campaignId"}),h=dt(v.step)??1,j=d.useCallback(c=>{a({to:"/campaigns/$campaignId",params:{campaignId:s.id},search:$=>({...$,step:c})})},[a,s.id]),A=us(),x=ot(c=>c.setHidden);d.useEffect(()=>{if(A)return x(!0),()=>x(!1)},[A,x]);const f=Ha({defaultValues:ja(s),validators:{onChange:fa}}),u=V(p.campaign.update.mutationOptions({onSuccess:(c,$)=>{t.invalidateQueries({queryKey:[["campaign","list"]]}),t.setQueryData(p.campaign.getById.queryKey({id:s.id}),Z=>Z&&{...Z,...$})},onError:c=>{k.error(c.message??"Failed to save draft")}})),N=V(p.campaign.replaceRecipients.mutationOptions({onSuccess:async c=>{r(c.targetCount),f.setFieldValue("type","static"),f.setFieldValue("segmentId",null),await t.invalidateQueries({queryKey:p.campaign.getById.queryKey({id:s.id})})},onError:c=>{k.error(c.message??"Failed to update recipients")}})),S=V(p.campaign.send.mutationOptions({onSuccess:()=>{t.invalidateQueries({queryKey:[["campaign","list"]]}),t.invalidateQueries({queryKey:p.campaign.getById.queryKey({id:s.id})}),k.success("Campaign is being sent!")},onError:c=>{k.error(c.message??"Failed to send campaign")}})),I=V(p.campaign.sendTest.mutationOptions({onSuccess:()=>{k.success("Test message sent!")},onError:c=>{k.error(c.message??"Failed to send test message")}})),T=d.useCallback(async()=>{const c=f.state.values,$=ya(c,s.id),Z=await u.mutateAsync($);r(Z.targetCount??0),f.reset(c)},[u,s.id,f]),W=async c=>{try{await N.mutateAsync({campaignId:s.id,selection:c}),n(!1),k.success("Recipients updated")}catch{}},y=()=>{const c=f.state.values;return{name:c.name,channelAccountId:c.channelAccountId,whatsappTemplateId:c.whatsappTemplateId,type:c.type,segmentId:c.segmentId,scheduleType:c.scheduleType,scheduledAt:c.scheduledAt,endsAt:c.endsAt,optInStatementAccepted:c.optInStatementAccepted}},P=mt(f.store,c=>c.values.whatsappTemplateId),{data:D}=F({...p.whatsappTemplate.getById.queryOptions({id:P??""}),enabled:!!P}),E=D?.status,K=E==="pending",H=d.useCallback(c=>{const $=f.state.values.whatsappTemplateId;f.setFieldValue("whatsappTemplateId",c),$!==c&&f.setFieldValue("templateVariables",[])},[]),Q=d.useCallback(()=>{a({to:"/campaigns/$campaignId",params:{campaignId:s.id},search:c=>({...c,templateId:void 0}),replace:!0})},[a,s.id]);va({incomingTemplateId:v.templateId,adoptTemplate:H,saveDraft:T,clearTemplateId:Q});const X=d.useCallback(async()=>{const c=He(h,{values:y(),recipientCount:l});if(Ce(c)){try{f.state.isDirty&&await T()}catch{return}if(h===2&&E==="draft"&&P){a({to:"/settings/templates/whatsapp/$templateId",params:{templateId:P},search:{campaignId:s.id}});return}j(Math.min(Qe,h+1))}},[h,j,l,T,E,P,a,s.id]),C=d.useCallback(async()=>
6{if(!o){m(!0);try{await X()}finally{m(!1)}}},[X,o]),Y=d.useCallback(()=>{if(h===1){a({to:"/campaigns"});return}j(h-1)},[h,j,a]),w=d.useCallback(async()=>{const c=ut({values:y()});if(Ce(c)){b(!0);try{f.state.isDirty&&await T(),a({to:"/campaigns"})}catch{}finally{b(!1)}}},[T,a,l]),As=d.useCallback(async()=>{const c=pt({values:y(),recipientCount:l,templateStatus:E});if(Ce(c))try{f.state.isDirty&&await T(),S.mutate({id:s.id})}catch{}},[l,T,S,s.id,E]),Ts=d.useCallback(c=>j(c),[j]);return e.jsx(we,{className:"flex-1 flex flex-col min-w-0 rounded-none border-0 shadow-none bg-background",children:e.jsx(f.Subscribe,{selector:c=>({isDirty:c.isDirty,name:c.values.name,channelAccountId:c.values.channelAccountId,whatsappTemplateId:c.values.whatsappTemplateId,type:c.values.type,segmentId:c.values.segmentId,scheduleType:c.values.scheduleType,scheduledAt:c.values.scheduledAt,endsAt:c.values.endsAt,optInStatementAccepted:c.values.optInStatementAccepted}),children:c=>{const Z=h===2&&(!!P&&!D)?!1:He(h,{values:c,recipientCount:l}).valid,Le={onSave:w,onSaveDraft:T,isSaving:g,onSendTest:async be=>{try{c.isDirty&&await T(),I.mutate({id:s.id,contactId:be})}catch{}},isSendingTest:I.isPending,onActivate:As,isActivating:S.isPending,recipientCount:l,isDirty:c.isDirty,currentStep:h,totalSteps:Qe,onBack:Y,onNext:C,canAdvance:Z,isAdvancing:o,onSaveAndExit:w,isTemplatePending:K};return i?e.jsx(ss,{...Le,children:e.jsx(Xa,{recipientCount:l,onBack:()=>n(!1),onSelect:W,isSaving:N.isPending})}):e.jsx(ss,{...Le,children:e.jsx(wa,{campaign:s,children:e.jsx(f.AppForm,{children:e.jsx("form",{onSubmit:be=>be.preventDefault(),className:"min-h-full flex flex-col lg:h-full lg:min-h-0",children:e.jsx(gn,{step:h,recipientCount:l,onSelectRecipients:()=>n(!0),onJumpToStep:Ts})})})})})}})})}function gn({step:s,recipientCount:t,onSelectRecipients:a,onJumpToStep:i}){switch(s){case 1:return e.jsx(ee,{left:e.jsx(se,{title:"What is your campaign about?",description:"Give your campaign a name for internal reference.",children:e.jsx("img",{src:"/illustrations/campaign-main.png",alt:"campaign-main","aria-hidden":"true",className:"w-96 h-auto"})}),right:e.jsx(Ja,{})});case 2:return e.jsx(ee,{left:e.jsx(se,{title:"Build your message",description:"Personalize your WhatsApp message using approved templates. Preview how it will look to your customers.",children:e.jsx("div",{className:"w-full max-w-sm h-full min-h-0",children:e.jsx(as,{})})}),right:e.jsx(Qa,{})});case 3:return e.jsx(ee,{left:e.jsx(se,{title:"Choose who should receive this campaign",description:"Select the right audience to make your message more relevant and effective. Use a static list or a saved dynamic segment.",children:e.jsx("img",{src:"/illustrations/campaign-audience.png",alt:"campaign-audience","aria-hidden":"true",className:"w-96 h-auto"})}),right:e.jsx(dn,{recipientCount:t,onSelectRecipients:a})});case 4:return e.jsx(ee,{left:e.jsx(se,{title:"When do you want to send?",description:"Choose whether to send your campaign right away or schedule it for a specific date and time.",children:e.jsx("img",{src:"/illustrations/campaign-schedule.png",alt:"campaign-schedule","aria-hidden":"true",className:"w-96 h-auto"})}),right:e.jsx(ln,{})});case 5:return e.jsx(ee,{left:e.jsx(se,{title:"Review your campaign before sending",description:"You're almost ready. Review the details below before activating your WhatsApp campaign.",children:e.jsx("div",{className:"w-full max-w-sm min-h-0",children:e.jsx(as,{})})}),right:e.jsx(sn,{recipientCount:t,onJumpToStep:i})})}}function Ss(s,t){const a=t.funnelPercentages,i=t.errorStats,n=i.excludedContacts.percentage+i.recipientExperiment.percentage;switch(s){case"details":return null;case"sent":return a.sent;case"delivered":return a.delivered;case"read":return a.read;case"undelivered":return a.undelivered;case"unreachable":return n}}function Ns(s){return`${Math.round(s)}%`}function fn({campaignId:s,analytics:t}){const{pathname:a}=Ve(),i=Re(a),n=l=>{const r=i===l,o=ys[l],m=o.icon,g=t?Ss(l,t):null;return e.jsx(wt,{children:e.jsx(It,{asChild:!0,isActive:r,className:"justify-between",children:e.jsxs(ps,{to:js[l],params:{campaignId:s},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[m&&e.jsx(m,{className:"size-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"truncate",children:o.label})]}),l!=="details"&&(g!==null?e.jsx("span",{className:"text-xs font-bold ml-auto pl-2 tabular-nums",children:Ns(g)}):e.jsx(ae,{className:"ml-auto h-3.5 w-9 shrink-0"}))]})})},l)};return e.jsx("div",{className:"space-y-5 p-2",children:e.jsx(Tt,{children:fs.map(l
6=>n(l))})})}function jn({campaignId:s,analytics:t}){const{pathname:a}=Ve(),i=Re(a);return e.jsx("div",{className:"flex min-w-0 gap-1 overflow-x-auto overscroll-x-contain border-b px-2 py-2 shrink-0",children:fs.map(n=>{const l=i===n,r=ys[n],o=t?Ss(n,t):null;return e.jsxs(ps,{to:js[n],params:{campaignId:s},className:ne("flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs whitespace-nowrap shrink-0",l?"bg-sidebar-accent text-sidebar-foreground":"text-muted-foreground"),children:[e.jsx("span",{children:r.label}),n!=="details"&&(o!==null?e.jsx("span",{className:"font-bold tabular-nums",children:Ns(o)}):e.jsx(ae,{className:"h-3.5 w-9 shrink-0"}))]},n)})})}function Qi(){const{campaignId:s}=ht.useParams(),{pathname:t}=Ve(),a=Fe(),i=ms(),n=Re(t),l=xt("campaign","update"),{data:r,isLoading:o,error:m}=F(p.campaign.getById.queryOptions({id:s})),g=!!r&&r.status!=="draft",{data:b}=F({...p.campaign.getAnalytics.queryOptions({id:s}),enabled:g});ba(s,g);const v=us(),h=v&&r?.status&&r.status!=="draft"?"/campaigns":null,[j,A]=d.useState(!1),[x,f]=d.useState(!1),[u,N]=d.useState(!1),[S,I]=d.useState(!1),T=async C=>{await Promise.all([i.invalidateQueries({queryKey:p.campaign.getById.queryKey({id:C})}),i.invalidateQueries({queryKey:p.campaign.getAnalytics.queryKey({id:C})}),i.invalidateQueries({queryKey:p.campaign.listBroadcasts.queryKey()}),i.invalidateQueries({queryKey:p.campaign.list.queryKey()})])},W=V(p.campaign.duplicate.mutationOptions({onSuccess:async C=>{await i.invalidateQueries({queryKey:p.campaign.list.queryKey()}),k.success("Campaign duplicated"),a({to:"/campaigns/$campaignId",params:{campaignId:C.id}})},onError:C=>{k.error(C.message||"Failed to duplicate campaign")}})),y=V(p.campaign.delete.mutationOptions({onSuccess:async()=>{await i.invalidateQueries({queryKey:p.campaign.list.queryKey()}),A(!1),k.success("Campaign deleted"),a({to:"/campaigns"})},onError:C=>{k.error(C.message||"Failed to delete campaign")}})),P=V(p.campaign.update.mutationOptions({onSuccess:async()=>{await T(s)},onError:C=>{k.error(C.message??"Failed to rename campaign")}})),D=V(p.campaign.cancel.mutationOptions({onSuccess:async()=>{await T(s),k.success("Scheduled send cancelled")},onError:C=>{k.error(C.message??"Failed to cancel scheduled send")}})),E=V(p.campaign.pause.mutationOptions({onSuccess:async()=>{await T(s),N(!1),k.success("Campaign paused")},onError:C=>{k.error(C.message??"Failed to pause campaign")}})),K=V(p.campaign.resume.mutationOptions({onSuccess:async C=>{await T(s),I(!1),k.success(C.status==="completed"?"Campaign ended":"Campaign resumed")},onError:C=>{k.error(C.message??"Failed to resume campaign")}}));if(o)return e.jsxs("div",{className:"flex flex-1 h-full flex-col min-w-0",children:[e.jsxs("div",{className:"border-b px-6 py-4",children:[e.jsx(ae,{className:"h-8 w-48"}),e.jsx(ae,{className:"mt-2 h-5 w-32"})]}),e.jsx("div",{className:"flex-1 p-6",children:e.jsx(ae,{className:"h-64 w-full"})})]});if(m||!r)return e.jsxs("div",{className:"flex flex-1 h-full flex-col items-center justify-center p-6 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign not found or you don't have access."}),e.jsx("button",{type:"button",onClick:()=>a({to:"/campaigns"}),className:"mt-4 text-sm text-primary hover:underline",children:"Back to campaigns"})]});if(r.status==="draft")return e.jsx(xn,{campaign:r});const H=r.status==="scheduled",Q=es[r.status??"draft"]??es.draft,X=na(n,r.name);return e.jsx(St,{value:h,children:e.jsxs(e.Fragment,{children:[!v&&e.jsx(we,{className:"bg-sidebar/80 flex-col",children:e.jsx(kt,{title:"Campaign",onBack:()=>a({to:"/campaigns"}),children:e.jsx(fn,{campaignId:s,analytics:b})})}),e.jsxs(we,{className:"flex-1 flex-col min-w-0 overflow-hidden",children:[e.jsxs(Nt,{title:n==="details"&&l?e.jsx(Dt,{value:r.name??"",onSave:C=>{const Y=C.trim();!Y||Y===r.name||P.mutate({id:r.id,name:Y})},placeholder:"Untitled campaign",showControls:!1,showEditIcon:!1,className:"text-base md:text-lg font-semibold min-w-0 flex-1",triggerClassName:"min-w-0 max-w-full"}):X,children:[e.jsxs(Ft,{variant:Q.variant,className:ne("shrink-0 capitalize text-xs",Q.className),children:[H&&e.jsx(Me,{className:"mr-1 size-3"}),r.status]}),H&&r.scheduledAt&&e.jsx("span",{className:"hidden md:inline text-xs text-muted-foreground shrink-0",children:new Date(r.scheduledAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}),r.endsAt&&r.status!=="completed"&&r.status!=="failed"&&e.jsxs("span",{className:"hidden md:inline text-xs text-muted-foreground shrink-0",children:["Ends"," ",new Date(r.endsAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})]}),e.jsxs(fe,{resource:"campaign",permission:"update",children:[r.status==="running"&&e.jsx(Ye,{variant:"outline",icon:e.jsx(ra,{className:"size-4"}),label:"Pause",onClick:()=>N(!0),disabled:E.isPending}),r.status==="paused"&&e.jsx(Ye,{icon:e.jsx(gt,{className:"size-4"}),label:"Resume",onClick:()=>I(!0),disabled:K.isPending})]}),e.jsxs(yt,{children:[e.jsx(bt,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"size-8","aria-label":"More actions",children:e.jsx(ft,{className:"size-4"})})}),e.jsxs(vt,{align:"end",children:[H&&e.jsxs(e.Fragment,{children:[e.jsxs(re,{onClick:()=>f(!0),children:[e.jsx(gs,{className:"size-4"}),"Edit"]}),e.jsxs(re,{onClick:()=>D.mutate({id:r.id}),disabled:D.isPending,children:[e.jsx(ia,{className:"size-4"}),"Cancel campaign"]}),e.jsx(Ct,{})]}),e.jsx(fe,{resource:"campaign",permission:"create",children:e.jsxs(re,{onClick:()=>W.mutate({id:r.id}
6),disabled:W.isPending,children:[e.jsx(la,{className:"size-4"}),"Duplicate"]})}),e.jsxs(re,{variant:"destructive",onClick:()=>A(!0),children:[e.jsx(ca,{className:"size-4"}),"Delete"]})]})]})]}),v&&e.jsx(jn,{campaignId:s,analytics:b}),e.jsx(At,{className:"relative",children:e.jsx(jt,{})})]}),e.jsx(le,{open:x,onOpenChange:f,children:e.jsxs(ce,{children:[e.jsxs(de,{children:[e.jsx(oe,{children:"Reset scheduled campaign to draft"}),e.jsx(me,{children:"You are about to edit a scheduled campaign. If you proceed, the campaign will be reset to draft and the scheduled send will be cancelled so you can make your changes."})]}),e.jsxs(ue,{children:[e.jsx(pe,{children:"Cancel"}),e.jsx(he,{onClick:()=>D.mutate({id:r.id}),disabled:D.isPending,children:D.isPending?"Resetting...":"Continue"})]})]})}),e.jsx(le,{open:u,onOpenChange:N,children:e.jsxs(ce,{children:[e.jsxs(de,{children:[e.jsx(oe,{children:"Pause campaign?"}),e.jsx(me,{children:"Sending will stop immediately. Contacts who haven't been messaged yet will be held until you resume."})]}),e.jsxs(ue,{children:[e.jsx(pe,{children:"Cancel"}),e.jsx(he,{onClick:()=>E.mutate({id:r.id}),disabled:E.isPending,children:E.isPending?"Pausing...":"Pause"})]})]})}),e.jsx(le,{open:S,onOpenChange:I,children:e.jsxs(ce,{children:[e.jsxs(de,{children:[e.jsx(oe,{children:"Resume campaign?"}),e.jsx(me,{children:"Sending will continue to the remaining contacts in this campaign."})]}),e.jsxs(ue,{children:[e.jsx(pe,{children:"Cancel"}),e.jsx(he,{onClick:()=>K.mutate({id:r.id}),disabled:K.isPending,children:K.isPending?"Resuming...":"Resume"})]})]})}),e.jsx(le,{open:j,onOpenChange:A,children:e.jsxs(ce,{children:[e.jsxs(de,{children:[e.jsx(oe,{children:"Delete campaign?"}),e.jsxs(me,{children:['This will permanently delete "',r.name?.trim()||"Untitled campaign",'". This action cannot be undone.']})]}),e.jsxs(ue,{children:[e.jsx(pe,{children:"Cancel"}),e.jsx(he,{onClick:()=>y.mutate({id:r.id}),disabled:y.isPending,variant:"destructive",children:y.isPending?"Deleting...":"Delete"})]})]})})]})})}export{Qi 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.