1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/facebook-ad-mockup-BkALhgJj.js","assets/index-CuSEeJFb.js","assets/index-DK0yIo6F.css","assets/file-management-panel-CMp7oECT.js","assets/image-fQC3p4ps.js","assets/video-AMZtj4XD.js","assets/upload-rep3KVPL.js","assets/ellipsis-DL2QQYI6.js","assets/share-B5BYf7qZ.js","assets/grid-3x3-CB6J-yDX.js","assets/play-oR40AlEL.js","assets/google-search-mockup-hmE1fEdb.js","assets/instagram-post-mockup-CF3rT3Dh.js","assets/email-mockup-BSO_UPGU.js","assets/mail-Dl1RGATy.js","assets/twitter-post-mockup-D12O4fKe.js","assets/linkedin-ads-mockup-Ha6n9rSC.js","assets/sms-mockup-CQXgyJDf.js","assets/check-check-BVDNI4mA.js","assets/youtube-ads-mockup-C0bs0ojk.js","assets/volume-2-bzvEFd58.js","assets/maximize-B0AUw_l6.js","assets/ellipsis-vertical-04pZ3iRl.js","assets/accordion-BQLGpMyk.js","assets/sheet-veaLBARn.js","assets/skeleton-BRByoc1c.js","assets/inline-connection-components-CHMT89t0.js","assets/progress-B2eMqtVV.js","assets/link-2-B6OMy1mi.js","assets/tabs-CcPOXtvT.js","assets/en-US-BOoww7nS.js","assets/format-hhvI2L0z.js","assets/isSameDay-asvKFMkz.js","assets/endOfWeek-COLolEil.js","assets/isBefore-dQ65yIyQ.js","assets/calendar-days-B9ClAFA5.js","assets/filter-DIYm3mPi.js","assets/circle-check-DSSdNCFx.js","assets/rectangle-ellipsis-DOuE5nFj.js","assets/wand-sparkles-Cnc6tXs_.js","assets/radio-group-Cg3Pu9OU.js","assets/thermometer-Dh14qWj1.js","assets/generateCategoricalChart-lXkql-gd.js","assets/throttle-Bgu_Mp4s.js","assets/debounce-BH2
1V1_7f.js","assets/tiny-invariant-BaFNuDhB.js","assets/string-CFFdVFMV.js","assets/PieChart-BXVWJE0w.js","assets/save-DMqvNvzo.js","assets/snowflake-k2KdrOCY.js","assets/pen-line-Ys7SVokk.js","assets/list-CcOCoqUW.js","assets/tiktok-ads-mockup-fKF5oGJ5.js","assets/pinterest-mockup-Dd1KKEiy.js","assets/snapchat-ads-mockup-D9LAur0e.js","assets/reddit-mockup-CZy9nM3R.js","assets/arrow-up-Uui5xrmv.js","assets/arrow-down-CLUMqGAm.js","assets/whatsapp-business-mockup-Bh0DAhVC.js","assets/map-pin-DOxfmRxb.js","assets/shopping-bag-C66pVB-F.js","assets/mic-BSL7EuWM.js","assets/push-notifications-mockup-DW3DPxCU.js","assets/slider-1BwPyzha.js","assets/signal-CxJxYvBo.js","assets/wifi-BO0SxV3H.js","assets/webinars-mockup-azpRsk5P.js","assets/hand-MSlyF4UN.js","assets/phone-calls-mockup-Cvjtc9zF.js","assets/phone-call-C1bp6wH-.js","assets/voicemail-mockup-CQr_yUQx.js","assets/voicemail-2V6a7KU0.js","assets/pause-DRo4KdS6.js","assets/timer-ZazLa3Az.js","assets/postcards-mockup-CR5fL-xo.js","assets/ruler-CW1eoJlB.js","assets/type-u6mf0Lzd.js","assets/letters-mockup-D5t4vLdw.js","assets/align-right-8o2vFXTu.js","assets/print-ads-mockup-czZ_h_57.js","assets/newspaper-B16eXHZa.js","assets/square-CbouAjGs.js","assets/billboards-mockup-N86ZTu8h.js","assets/radio-ads-mockup-Dc4OXNQm.js","assets/radio-CZxjpB95.js","assets/tv-commercials-mockup-BwhprIt8.js","assets/tv-fmJKIX6v.js","assets/minus-LVFLuFlS.js","assets/articles-mockup-ynvpJikh.js","assets/calendar-B35CJklo.js","assets/subDays-Cl8kgx1y.js","assets/differenceInCalendarMonths-CdYt3YUn.js","assets/isSameMonth-GNceXh6W.js","assets/endOfMonth-DMtDxPW7.js","assets/square-pen-Wwme7SiP.js","assets/hash-jasa6rMo.js","assets/copy-Ctw93tQ7.js","assets/trade-shows-mockup-Dmgq-t6P.js","assets/network-XajVsS1y.js","assets/affiliate-marketing-mockup-BxSJAVAz.js","assets/user-plus-Bycr7F9K.js","assets/arrow-up-right-CBrP1-KZ.js","assets/flyers-mockup-CZSVCdir.js","assets/blog-mockup-DqSxzh4B.js"])))=>i.map(i=>d[i]); 2import{K as Xt,_ as Et,r as o,a6 as dt,c0 as Tt,c1 as At,j as e,ak as vt,al as bt,am as yt,an as jt,Z as ea,bJ as ws,T as Dt,J as qe,C as ae,b as ye,d as Ne,ab as ge,aF as Pe,bd as va,B as V,e as me,$ as Ce,a0 as Se,a1 as Ie,a2 as Te,a3 as K,h as mt,s as z,aH as Ft,a4 as De,S as Je,V as _s,n as ba,a7 as Ae,E as Gt,bU as Cs,X as za,v as ta,a5 as Ss,a as Ve,o as et,bt as an,au as sn,aD as nn,ap as Na,N as aa,ar as rn,ao as wa,be as Qe,aE as Is,ac as Va,aq as Ts,c2 as oa,bG as ln,c as ot,c3 as on,c4 as cn,ba as Kt,bb as Qt,aK as Pt,bc as Jt,c5 as Lt,F as dn,aM as Oa,I as mn,w as un,L as Yt,k as pn,m as gn,c6 as le,c7 as hn,c8 as xn,c9 as fn,ca as vn,R as Mt,cb as bn,Q as yn,D as It,aP as jn,bo as kn,aX as qa,H as Nn,br as wn,z as _n,a_ as ca,a$ as We,b0 as He,b1 as Xe,b2 as Ge,b3 as Ke,b4 as Cn,bz as $a,cc as Sn,bC as In,b9 as Ua,f as Tn,b8 as be,bf as Wa}from"./index-CuSEeJFb.js";import{A as An,a as Pn,b as Ln,c as Mn}from"./accordion-BQLGpMyk.js";import{S as Dn,a as En,b as Fn,c as Bn,d as Rn}from"./sheet-veaLBARn.js";import{S as xt}from"./skeleton-BRByoc1c.js";import{u as zn,P as Vn}from"./inline-connection-components-CHMT89t0.js";import{T as Bt,a as Rt,b as Re,c as Ye}from"./tabs-CcPOXtvT.js";import{P as On}from"./play-oR40AlEL.js";import{t as ft,c as qn,m as _a,a as As}from"./en-US-BOoww7nS.js";import{d as $n,f as Le,s as Ps}from"./format-hhvI2L0z.js";import{a as Zt,i as Un}from"./isSameDay-asvKFMkz.js";import{a as Wn,e as Hn}from"./endOfWeek-COLolEil.js";import{i as da,a as Ha}from"./isBefore-dQ65yIyQ.js";import{C as Ga}from"./calendar-days-B9ClAFA5.js";import{F as Gn}from"./filter-DIYm3mPi.js";import{C as Ls}from"./circle-check-DSSdNCFx.js";import{I as Ka}from"./image-fQC3p4ps.js";import{U as ya}from"./upload-rep3KVPL.js";import{L as Wt}from"./link-2-B6OMy1mi.js";import{R as Qa}from"./rectangle-ellipsis-DOuE5nFj.js";import{W as Kn}from"./wand-sparkles-Cnc6tXs_.js";import{R as Qn,a as ma}from"./radio-group-Cg3Pu9OU.js";import{P as Jn}from"./progress-B2eMqtVV.js";import{T as Yn}from"./thermometer-Dh14qWj1.js";import{R as Zn,C as Xn,T as ei}from"./generateCategoricalChart-lXkql-gd.js";import{P as ti,a as ai}from"./PieChart-BXVWJE0w.js";import{S as Ht}from"./save-DMqvNvzo.js";import{F as Ms,S as si}from"./snowflake-k2KdrOCY.js";import{P as ni}from"./pen-line-Ys7SVokk.js";import{L as ii}from"./list-CcOCoqUW.js";/** 3 * @license lucide-react v0.453.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const ua=Xt("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** 8 * @license lucide-react v0.453.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Ja=Xt("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",ke
vendor: 4,622 bytes, lines 12-22
12y:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/** 13 * @license lucide-react v0.453.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const Ya=Xt("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/** 18 * @license lucide-react v0.453.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const ri=Xt("ThermometerSun",[["path",{d:"M12 9a4 4 0 0 0-2 7.5",key:"1jvsq6"}],["path",{d:"M12 3v2",key:"1w22ol"}],["path",{d:"m6.6 18.4-1.4 1.4",key:"w2yidj"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}],["path",{d:"M4 13H2",key:"118le4"}],["path",{d:"M6.34 7.34 4.93 5.93",key:"1brd51"}]]);function li(t,n){const c=+ft(t);return qn(t,c+n)}function oi(t,n){return li(t,n*_a)}function ci(t,n){const c=ft(t),l=ft(n),u=Za(c,l),x=Math.abs($n(c,l));c.setDate(c.getDate()-u*x);const b=+(Za(c,l)===-u),S=u*(x-b);return S===0?0:S}function Za(t,n){const c=t.getFullYear()-n.getFullYear()||t.getMonth()-n.getMonth()||t.getDate()-n.getDate()||t.getHours()-n.getHours()||t.getMinutes()-n.getMinutes()||t.getSeconds()-n.getSeconds()||t.getMilliseconds()-n.getMilliseconds();return c<0?-1:c>0?1:c}function di(t,n){const c=ft(t.start),l=ft(t.end);let u=+c>+l;const x=u?+c:+l,b=u?l:c;b.setHours(0,0,0,0);let S=1;const d=[];for(;+b<=x;)d.push(ft(b)),b.setDate(b.getDate()+S),b.setHours(0,0,0,0);return u?d.reverse():d}function Xa(t,n){const l=gi(t);let u;if(l.date){const d=hi(l.date,2);u=xi(d.restDateString,d.year)}if(!u||isNaN(u.getTime()))return new Date(NaN);const x=u.getTime();let b=0,S;if(l.time&&(b=fi(l.time),isNaN(b)))return new Date(NaN);if(l.timezone){if(S=vi(l.timezone),isNaN(S))return new Date(NaN)}else{const d=new Date(x+b),R=new Date(0);return R.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),R.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),R}return new Date(x+b+S)}const qt={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},mi=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,ui=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,pi=/^([+-])(\d{2})(?::?(\d{2}))?$/;function gi(t){const n={},c=t.split(qt.dateTimeDelimiter);let l;if(c.length>2)return n;if(/:/.test(c[0])?l=c[0]:(n.date=c[0],l=c[1],qt.timeZoneDelimiter.test(n.date)&&(n.date=t.split(qt.timeZoneDelimiter)[0],l=t.substr(n.date.length,t.length))),l){const u=qt.timezone.exec(l);u?(n.time=l.replace(u[1],""),n.timezone=u[1]):n.time=l}return n}function hi(t,n){const c=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+n)+"})|(\\d{2}|[+-]\\d{"+(2+n)+"})$)"),l=t.match(c);if(!l)return{year:NaN,restDateString:""};const u=l[1]?parseInt(l[1]):null,x=l[2]?parseInt(l[2]):null;return{year:x===null?u:x*100,restDateString:t.slice((l[1]||l[2]).length)}}function xi(t,n){if(n===null)return new Date(NaN);const c=t.match(mi);if(!c)return new Date(NaN);const l=!!c[4],u=Ct(c[1]),x=Ct(c[2])-1,b=Ct(c[3]),S=Ct(c[4]),d=Ct(c[5])-1;if(l)return Ni(n,S,d)?bi(n,S,d):new Date(NaN);{const R=new Date(0);return!ji(n,x,b)||!ki(n,u)?new Date(NaN):(R.setUTCFullYear(n,x,Math.max(u,b)),R)}}function Ct(t){return t?parseInt(t):1}function fi(t){const n=t.match(ui);if(!n)return NaN;const c=pa(n[1]),l=pa(n[2]),u=pa(n[3]);return wi(c,l,u)?c*_a+l*As+u*1e3:NaN}function pa(t){return t&&parseFloat(t.replace(",","."))||0}function vi(t){if(t==="Z")return 0;const n=t.match(pi);if(!n)return 0;const c=n[1]==="+"?-1:1,l=parseInt(n[2]),u=n[3]&&parseInt(n[3])||0;return _i(l,u)?c*(l*_a+u*As):NaN}function bi(t,n,c){const l=new Date(0);l.setUTCFullYear(t,0,4);const u=l.getUTCDay()||7,x=(n-1)*7+c+1-u;return l.setUTCDate(l.getUTCDate()+x),l}const yi=[31,null,31,30,31,30,31,31,30,31,30,31];function Ds(t){return t%400===0||t%4===0&&t%100!==0}function ji(t,n,c){return n>=0&&n<=11&&c>=1&&c<=(yi[n]||(Ds(t)?29:28))}function ki(t,n){return n>=1&&n<=(Ds(t)?366:365)}function Ni(t,n,c){return n>=1&&n<=53&&c>=0&&c<=6}function wi(t,n,c){return t===24?n===0&&c===0:c>=0&&c<60&&n>=0&&n<60&&t>=0&&t<25}function _i(t,n){return n>=0&&n<=59}const es={immediate:{name:"Start Immediately",description:"Begin posting as soon as possible",icon:On,generateSchedule:(t,n)=>t.map((c,l)=>({stepId:c.id,publishDate:oi(n,l*2),strategy:"immediate"}))},daily:{name:"Daily Sequence",description:"One post per day at optimal times",icon:qe,generateSchedule:(t,n)=>t.map((c,l)=>
22({stepId:c.id,publishDate:Zt(n,l),strategy:"daily"}))},weekly:{name:"Weekly Campaign",description:"Spread across optimal days of the week",icon:_s,generateSchedule:(t,n)=>{const c=[1,3,5];return t.map((l,u)=>{const x=Math.floor(u/c.length),b=c[u%c.length],S=Wn(Ps(n),x);return S.setDate(S.getDate()+b),{stepId:l.id,publishDate:S,strategy:"weekly"}})}},temperature_based:{name:"Temperature Sequence",description:"Cold â Warm â Hot progression",icon:ba,generateSchedule:(t,n)=>{const c=t.filter(d=>d.temperature==="cold"),l=t.filter(d=>d.temperature==="warm"),u=t.filter(d=>d.temperature==="hot"),x=t.filter(d=>!d.temperature||!["cold","warm","hot"].includes(d.temperature)),b=[...c,...x,...l,...u],S=b.length;return S===0?[]:b.map((d,R)=>{let G=0;const O=R%Math.max(S,1);return d.temperature==="warm"?G=(c.length+x.length)*1:d.temperature==="hot"?G=(c.length+x.length+l.length)*1:G=0,{stepId:d.id,publishDate:Zt(n,G+Math.floor(O/3)),strategy:"temperature_based"}})}}},$t={facebook:["09:00","13:00","15:00"],instagram:["11:00","13:00","17:00"],twitter:["08:00","12:00","17:00"],linkedin:["08:00","11:00","16:00"],email:["10:00","14:00"],youtube:["14:00","20:00"],pinterest:["20:00","22:00"]};function Ci({isOpen:t,onClose:n,campaign:c,steps:l=[],platforms:u=[],onScheduleComplete:x}){const{toast:b}
22=Et(),[S,d]=o.useState(0),[R,G]=o.useState("daily"),[O,D]=o.useState(Le(Zt(new Date,1),"yyyy-MM-dd")),[I,Q]=o.useState([]),[T,F]=o.useState({}),[q,$]=o.useState([]),[ie,A]=o.useState(!1),[J,m]=o.useState(!0),[_,p]=o.useState(0),[f,r]=o.useState(""),[y,C]=o.useState(null),[k,M]=o.useState(!1);o.useEffect(()=>{l.length>0&&I.length>0&&O&&we()},[R,O,I,l]);const we=()=>{const U=es[R].generateSchedule(l,new Date(O)),oe=[];for(const se of I)for(const E of U){const P=l.find(X=>X.id===E.stepId),Y=$t[se]||["09:00"],s=T[se]||Y[0],h=new Date(E.publishDate),[te,v]=s.split(":").map(Number);h.setHours(te,v,0,0),oe.push({stepId:P.id,stepName:P.name,stepSequence:P.sequence,platform:se,publishDate:h,strategy:E.strategy,isOptimalTime:Y.includes(s),hasConflict:!1})}if(oe.sort((se,E)=>se.publishDate.getTime()-E.publishDate.getTime()),J)for(let se=0;se<oe.length;se++)for(let E=se+1;E<oe.length;E++){const P=oe[se],Y=oe[E];P.platform===Y.platform&&Math.abs(Y.publishDate.getTime()-P.publishDate.getTime())/(1e3*60*60)<2&&(P.hasConflict=!0,Y.hasConflict=!0)}$(oe)},ze=async(N,U=3)=>{var P;const oe=[],se=[];let E=0;p(0),r(`Starting bulk schedule of ${N.length} items...`);for(let Y=0;Y<N.length;Y+=U){const s=N.slice(Y,Y+U);r(`Processing batch ${Math.floor(Y/U)+1}...`);const h=s.map(async v=>{try{return{success:!0,result:await Ae("/api/content-schedule",{method:"POST",body:JSON.stringify({campaignId:c.id,stepId:v.stepId,variantId:1,publishDate:v.publishDate.toISOString(),platform:v.platform,title:`${c.name} - ${v.stepName}`,notes:`Bulk scheduled via ${R} strategy`,isActive:!0})}),item:v}}catch(X){const H=`${v.stepName} on ${v.platform}: ${X.message}`;if(X instanceof Tt||X instanceof At)throw X;return{success:!1,error:H,item:v}}}),te=await Promise.allSettled(h);for(const v of te){E++;const X=Math.round(E/N.length*100);if(p(X),v.status==="fulfilled"){const H=v.value;H.success?oe.push(H.result):se.push(H.error)}else{if(v.reason instanceof Tt||v.reason instanceof At)throw v.reason;se.push(`Batch processing failed: ${((P=v.reason)==null?void 0:P.message)||"Unknown error"}`)}}Y+U<N.length&&await new Promise(v=>setTimeout(v,200))}return r(`Completed! ${oe.length} scheduled, ${se.length} failed.`),{results:oe,errors:se}},nt=dt({mutationFn:async N=>(A(!0),p(0),C(null),M(!1),await ze(N,3)),onSuccess:({results:N,errors:U})=>{A(!1),p(100),queryClient.invalidateQueries({queryKey:["/api/content-schedule"]}),queryClient.invalidateQueries({queryKey:["/api/campaigns"]}),queryClient.invalidateQueries({queryKey:["/api/marketing-calendar"]}),N.length>0?(x(N),U.length===0?b({title:"Bulk Scheduling Complete",description:`Successfully scheduled ${N.length} items.`}):(b({title:"Bulk Scheduling Completed with Issues",description:`${N.length} items scheduled, ${U.length} failed. Check console for details.`,variant:"destructive"}),console.warn("Scheduling errors:",U)),setTimeout(()=>n(),1500)):b({title:"Bulk Scheduling Failed",description:`All ${U.length} items failed to schedule.`,variant:"destructive"})},onError:N=>{A(!1),p(0),N instanceof Tt||N instanceof At?(C(N.message),M(!0),b({title:"Authentication Required",description:"Please sign in to continue bulk scheduling.",variant:"destructive"})):b({title:"Bulk Scheduling Failed",description:N.message||"Failed to schedule content.",variant:"destructive"})}}),tt=N=>{Q(U=>U.includes(N)?U.filter(oe=>oe!==N):[...U,N])},ut=()=>{if(q.filter(U=>!U.hasConflict).length===0){b({title:"No Valid Schedule",description:"Please resolve conflicts or select different settings.",variant:"destructive"});return}const N=q.filter(U=>!U.hasConflict);nt.mutate(N)},ce=N=>({facebook:"ð",instagram:"ð·",twitter:"ð¦",linkedin:"ð¼",youtube:"ðº",email:"âï¸",sms:"ð¬"})[N]||"ð",Oe=N=>{switch(N){case"cold":return"âï¸";case"warm":return"ð¥";case"hot":return"â¡";default:return"ð"}},Ee=u.filter(N=>{var U;return N.isConnected&&((U=N.connectionHealth)==null?void 0:U.isConnected)!==!1});return e.jsx(vt,{open:t,onOpenChange:n,children:e.jsxs(bt,{className:"max-w-4xl max-h-[90vh]",children:[e.jsxs(yt,{children:[e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"w-5 h-5 text-orange-500"}),"Bulk Schedule Campaign"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Schedule ",l.length," content pieces across multiple platforms with intelligent timing"]})]}),e.jsxs(Bt,{value:S.toString(),className:"w-full",children:[e.jsxs(Rt,{className:"grid w-full grid-cols-3",children:[e.jsxs(Re,{value:"0",className:"flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Strategy"]}
22),e.jsxs(Re,{value:"1",className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4"}),"Platforms"]}),e.jsxs(Re,{value:"2",className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),"Preview"]})]}),e.jsxs(Ye,{value:"0",className:"space-y-6 mt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-3",children:"Choose Scheduling Strategy"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Object.entries(es).map(([N,U])=>{const oe=U.icon;return e.jsx(ae,{className:`cursor-pointer transition-all ${R===N?"ring-2 ring-orange-500 bg-orange-50 dark:bg-orange-900/20":"hover:border-orange-200"}`,onClick:()=>G(N),children:e.jsx(ye,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center",children:e.jsx(oe,{className:"w-4 h-4 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Ne,{className:"text-base",children:U.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:U.description})]})]})})},N)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Start Date"}),e.jsx(Pe,{type:"date",value:O,onChange:N=>D(N.target.value),min:Le(new Date,"yyyy-MM-dd"),"data-testid":"bulk-start-date"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{id:"conflict-check",checked:J,onCheckedChange:m}),e.jsx(ge,{htmlFor:"conflict-check",children:"Check for conflicts"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Warn about posts scheduled too close together on the same platform"})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(V,{onClick:()=>d(1),"data-testid":"strategy-next",children:["Next: Select Platforms",e.jsx(Ya,{className:"w-4 h-4 ml-2"})]})})]}),e.jsxs(Ye,{value:"1",className:"space-y-6 mt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-3",children:"Select Platforms"}),e.jsx("div",{className:"grid grid-cols-1 gap-3",children:Ee.map(N=>{var U,oe,se;return e.jsx(ae,{className:`cursor-pointer transition-all ${I.includes(N.platform)?"ring-2 ring-orange-500 bg-orange-50 dark:bg-orange-900/20":""}`,onClick:()=>tt(N.platform),children:e.jsx(me,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:ce(N.platform)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:N.platform}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Optimal times: ",(U=$t[N.platform])==null?void 0:U.join(", ")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[I.includes(N.platform)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ge,{className:"text-sm",children:"Time:"}),e.jsxs(Ce,{value:T[N.platform]||((oe=$t[N.platform])==null?void 0:oe[0]),onValueChange:E=>F(P=>({...P,[N.platform]:E})),children:[e.jsx(Se,{className:"w-20",children:e.jsx(Ie,{})}),e.jsx(Te,{children:(se=$t[N.platform])==null?void 0:se.map(E=>e.jsx(K,{value:E,children:Le(new Date(`2024-01-01T${E}`),"h:mm a")},E))})]})]}),e.jsx(va,{checked:I.includes(N.platform),onCheckedChange:()=>tt(N.platform)})]})]})})},N.platform)})}),Ee.length===0&&e.jsx(ae,{children:e.jsxs(me,{className:"py-12 text-center",children:[e.jsx(mt,{className:"h-8 w-8 mx-auto mb-3 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No Connected Platforms"}),e.jsx("p",{className:"text-muted-foreground",children:"Please connect at least one platform to schedule content."})]})})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx(V,{variant:"outline",onClick:()=>d(0),children:"Back"}),e.jsxs(V,{onClick:()=>d(2),disabled:I.length===0,"data-testid":"platforms-next",children:["Next: Preview Schedule",e.jsx(Ya,{className:"w-4 h-4 ml-2"})]})]})]}),e.jsxs(Ye,{value:"2",className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Schedule Preview"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"secondary",children:[q.length," posts scheduled"]}),q.some(N=>N.hasConflict)&&e.jsxs(z,{variant:"destructive",children:[e.jsx(mt,{className:"w-3 h-3 mr-1"}),"Conflicts detected"]})]})]}),e.jsx(Ft,{className:"max-h-96 border rounded-lg",children:e.jsxs("div",{className:"p-4 space-y-3",children:[q.map((N,U)=>{var oe;return e.jsx(ae,{className:N.hasConflict?"border-red-200 bg-red-50/50 dark:bg-red-900/10":"",children:e.jsxs(me,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{children:Oe((oe=l.find(se=>
22se.id===N.stepId))==null?void 0:oe.temperature)}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:N.stepName}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Step ",N.stepSequence," ⢠",R," strategy"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-medium",children:Le(N.publishDate,"MMM d, yyyy")}),e.jsxs("div",{className:"text-sm flex items-center gap-1",children:[Le(N.publishDate,"h:mm a"),N.isOptimalTime&&e.jsx("span",{children:"â"})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{children:ce(N.platform)}),e.jsx(z,{variant:"outline",children:N.platform})]})]})]}),N.hasConflict&&e.jsxs("div",{className:"mt-2 text-sm text-red-600 bg-red-100 dark:bg-red-900/20 p-2 rounded",children:["â ï¸ Conflict: Another post scheduled within 2 hours on ",N.platform]})]})},`${N.stepId}-${N.platform}-${U}`)}),q.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(qe,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No schedule preview available"}),e.jsx("p",{className:"text-xs",children:"Please select platforms and configure settings"})]})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx(V,{variant:"outline",onClick:()=>d(1),children:"Back"}),e.jsx(V,{onClick:ut,disabled:q.length===0||ie||q.every(N=>N.hasConflict),"data-testid":"bulk-schedule-confirm",children:ie?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 animate-spin mr-2"}),"Scheduling..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Schedule ",q.filter(N=>!N.hasConflict).length," Posts"]})})]})]})]})]})})}const ga={facebook:"bg-blue-500",instagram:"bg-pink-500",twitter:"bg-blue-400",linkedin:"bg-blue-700",youtube:"bg-red-500",email:"bg-green-500",sms:"bg-orange-500",pinterest:"bg-red-600",tiktok:"bg-black"};function Si({isOpen:t,onClose:n,campaign:c,scheduledContent:l=[],workflowSteps:u=[]}
22){const[x,b]=o.useState("timeline"),[S,d]=o.useState("all"),[R,G]=o.useState("all"),O=o.useMemo(()=>l.map(m=>{const _=u.find(p=>p.id===m.stepId);return{id:m.id,stepId:m.stepId,stepName:(_==null?void 0:_.name)||`Step ${m.stepId}`,stepSequence:(_==null?void 0:_.sequence)||0,stepTemperature:(_==null?void 0:_.temperature)||"warm",platform:m.platform,publishDate:Xa(m.publishDate),title:m.title,notes:m.notes,isActive:m.isActive,publishedAt:m.publishedAt?Xa(m.publishedAt):void 0}}).sort((m,_)=>m.publishDate.getTime()-_.publishDate.getTime()),[l,u]),D=o.useMemo(()=>O.filter(m=>!(S!=="all"&&m.platform!==S||R!=="all"&&m.stepTemperature!==R)),[O,S,R]),I=[...new Set(O.map(m=>m.platform))],Q=[...new Set(O.map(m=>m.stepTemperature))],T=o.useMemo(()=>{if(D.length===0)return null;const m=D[0].publishDate,_=D[D.length-1].publishDate,p=ci(_,m)+1,f=D.reduce((M,we)=>(M[we.platform]=(M[we.platform]||0)+1,M),{}),r=D.reduce((M,we)=>(M[we.stepTemperature]=(M[we.stepTemperature]||0)+1,M),{}),y=D.filter(M=>M.publishedAt).length,C=D.filter(M=>da(M.publishDate,new Date)).length,k=D.filter(M=>Ha(M.publishDate,new Date)&&!M.publishedAt).length;return{totalPosts:D.length,duration:p,startDate:m,endDate:_,platformCounts:f,temperatureCounts:r,published:y,upcoming:C,overdue:k}},[D]),F=m=>({facebook:"ð",instagram:"ð·",twitter:"ð¦",linkedin:"ð¼",youtube:"ðº",email:"âï¸",sms:"ð¬",pinterest:"ð",tiktok:"ðµ"})[m]||"ð",q=m=>{switch(m){case"cold":return"âï¸";case"warm":return"ð¥";case"hot":return"â¡";default:return"ð"}},$=m=>m.publishedAt?e.jsx(z,{className:"bg-green-100 text-green-800",children:"Published"}):da(m.publishDate,new Date)?e.jsx(z,{className:"bg-blue-100 text-blue-800",children:"Scheduled"}):e.jsx(z,{className:"bg-red-100 text-red-800",children:"Overdue"}),ie=()=>e.jsxs("div",{className:"space-y-6",children:[T&&e.jsxs(ae,{children:[e.jsx(ye,{children:e.jsx(Ne,{className:"text-base",children:"Campaign Overview"})}),e.jsx(me,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:T.totalPosts}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Posts"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:T.duration}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Days"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-green-600",children:T.published}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Published"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:T.upcoming}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]})]})})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-8 top-0 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700"}),e.jsxs("div",{className:"space-y-6",children:[D.map((m,_)=>e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:`relative z-10 w-4 h-4 rounded-full border-2 border-white dark:border-gray-900 ${ga[m.platform]||"bg-gray-400"}`}),e.jsx(ae,{className:"flex-1",children:e.jsxs(me,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:F(m.platform)}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:m.title}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[q(m.stepTemperature)," ",m.stepName]}),e.jsx("span",{children:"â¢"}),e.jsx("span",{children:m.platform})]})]})]}),$(m)]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(qe,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:Le(m.publishDate,"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:Le(m.publishDate,"h:mm a")})]})]}),m.notes&&e.jsx("div",{className:"text-xs text-muted-foreground max-w-xs",children:m.notes})]})]})})]},m.id)),D.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ga,{className:"h-8 w-8 mx-auto mb-4 text-muted-foreground opacity-50"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No Scheduled Content"}),e.jsx("p",{className:"text-muted-foreground",children:O.length===0?"This campaign doesn't have any scheduled content yet.":"No content matches the selected filters."})]})]})]})]}),A=()=>{if(!T)return e.jsx("div",{children:"No data available"});const m=Ps(T.startDate),_=Hn(T.endDate),p=di({start:m,end:_});return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-7 gap-2",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(f=>e.jsx("div",{className:"p-2 text-center text-sm font-medium text-muted-foreground",children:f},f))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:p.map(f=>{const r=D.filter(C=>Un(C.publishDate,f)),y=!Ha(f,T.startDate)&&!da(f,T.endDate);return e.jsx(ae,{className:`min-h-24 ${y?"":"opacity-30"}`,children:e.jsxs(me,{className:"p-2",children:[e.jsx("div",{className:"text-sm font-medium mb-2",children:Le(f,"d")}),e.jsxs("div",{className:"space-y-1",children:[r.slice(0,3).map(C=>e.jsxs("div",{className:`text-xs p-1 rounded flex items-center gap-1 ${ga[C.platform]||"bg-gray-100"} text-white`,children:[e.jsx("span",{className:"text-xs",children:F(C.platform)}),e.jsx("span",{className:"truncate",children:C.stepName})]},C.id)),r.length>3&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["+",r.length-3," more"]})]})]})},f.toISOString())})})]})},J=()=>T?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ae,{children:[e.jsx(ye,{children:e.jsxs(Ne,{className:"flex items-center gap-2",children:[e.jsx(za,{className:"w-5 h-5"}),"Platform Distribution"]})}),e.jsx(me,{children:e.jsx("div",{className:"space-y-3",children:Object.entries(T.platformCounts).map(([m,_])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:F(m)}),e.jsx("span",{className:"capitalize",children:m})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-20 bg-gray-200 rounded-full h-2",children:e.jsx("div",{className:`h-2 rounded-full ${ga[m]||"bg-gray-400"}`,style:{width:`${_/T.totalPosts*100}%`}})}),e.jsx(z,{variant:"secondary",children:_})]})]},m))})})]}),e.jsxs(ae,{children:[e.jsx(ye,{children:e.jsxs(Ne,{className:"flex items-center gap-2",children:[e.jsx(_s,{className:"w-5 h-5"}),"Audience Temperature"]})}),e.jsx(me,{children:e.jsx("div",{className:"space-y-3",children:Object.entries(T.temperatureCounts).map(([m,_])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:q(m)}),e.jsxs("span",{className:"capitalize",children:[m," Audience"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-20 bg-gray-200 rounded-full h-2",children:e.jsx("div",{className:`h-2 rounded-full ${m==="cold"?"bg-blue-500":m==="warm"?"bg-orange-500":"bg-red-500"}`,style:{width:`${_/T.totalPosts*100}%`}})}),e.jsx(z,{variant:"secondary",children:_})]})]},m))})})]}),e.jsxs(ae,{children:[e.jsx(ye,{children:e.jsx(Ne,{children:"Publishing Timeline"})}),e.jsx(me,{children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("div",{className:"text-3xl font-bold text-orange-600",children:[Le(T.startDate,"MMM d")," - ",Le(T.endDate,"MMM d, yyyy")]}),e.jsxs("div",{className:"text-muted-foreground",children:[T.duration," day campaign with ",T.totalPosts," posts"]}),T.overdue>0&&e.jsxs(z,{variant:"destructive",children:[T.overdue," overdue posts need attention"]})]})})]})]}):e.jsx("div",{children:"No data available"});return e.jsx(vt,{open:t,onOpenChange:n,children:e.jsxs(bt,{className:"max-w-6xl max-h-[90vh]",children:[e.jsxs(yt,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-5 h-5 text-blue-500"}),"Campaign Timeline Preview"]}),e.jsx(V,{variant:"outline",size:"sm",asChild:!0,"data-testid":"view-in-calendar",children:e.jsxs("a",{href:"/marketing-calendar",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"View in Calendar"]})})]}),e.jsxs("p",{className:"text-muted-foreground",children:[c==null?void 0:c.name," ⢠",O.length," scheduled posts"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Bt,{value:x,onValueChange:m=>b(m),children:e.jsxs(Rt,{children:[e.jsxs(Re,{value:"timeline",className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"w-4 h-4"}),"Timeline"]}),e.jsxs(Re,{value:"calendar",className:"flex items-center gap-2",children:[e.jsx(qe,{className:"w-4 h-4"}),"Calendar"]}),e.jsxs(Re,{value:"analytics",className:"flex items-center gap-2",children:[e.jsx(za,{className:"w-4 h-4"}),"Analytics"]})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gn,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs(Ce,{value:S,onValueChange:d,children:[e.jsx(Se,{className:"w-32",children:e.jsx(Ie,{placeholder:"Platform"})}),e.jsxs(Te,{children:[e.jsx(K,{value:"all",children:"All Platforms"}),I.map(m=>e.jsxs(K,{value:m,children:[F(m)," ",m]},m))]})]})]}),e.jsxs(Ce,{value:R,onValueChange:G,children:[e.jsx(Se,{className:"w-32",children:e.jsx(Ie,{placeholder:"Temperature"})}),e.jsxs(Te,{children:[e.jsx(K,{value:"all",children:"All Temps"}),Q.map(m=>e.jsxs(K,{value:m,children:[q(m)," ",m]},m))]})]})]})]}),e.jsx(Ft,{className:"max-h-[60vh]",children:e.jsxs("div",{className:"pr-4",children:[x==="timeline"&&e.jsx(ie,{}),x==="calendar"&&e.jsx(A,{}),x==="analytics"&&e.jsx(J,{})]})})]})]})})}const ha={facebook:{weekdays:["9:00","13:00","15:00"],weekends:["10:00","14:00","19:00"],description:"Best times: 9AM, 1PM, 3PM on weekdays"},instagram:{weekdays:["11:00","13:00","17:00"],weekends:["10:00","14:00","18:00"],description:"Best times: 11AM, 1PM, 5PM on weekdays"},twitter:{weekdays:["8:00","12:00","17:00"],weekends:["9:00","13:00","16:00"],description:"Best times: 8AM, 12PM, 5PM on weekdays"},linkedin:{weekdays:["8:00","11:00","16:00"],weekends:["10:00","15:00"],description:"Best times: 8AM, 11AM, 4PM on weekdays"},email:{weekdays:["10:00","14:00"],weekends:["11:00","16:00"],description:"Best times: 10AM, 2PM on weekdays"}};function Ii({step:t,campaign:n,platforms:c,scheduledItems:l,onSchedule:u,onUnschedule:x}
22){const[b,S]=o.useState(""),[d,R]=o.useState(Le(Zt(new Date,1),"yyyy-MM-dd")),[G,O]=o.useState("09:00"),[D,I]=o.useState(""),[Q,T]=o.useState(""),[F,q]=o.useState(!1),$=l.find(_=>_.stepId===t.id&&_.campaignId===n.id),ie=t.content||t.copyContent||t.headline,A=_=>{const p=ha[_];return(p==null?void 0:p.weekdays)||["09:00","13:00","17:00"]},J=()=>{if(!b||!d)return;const _=new Date(`${d}T${G}:00`),p={platform:b,publishDate:_.toISOString(),title:D||`${n.name} - Step ${t.sequence}`,notes:Q};u(t.id,p),S(""),I(""),T(""),q(!1)},m=_=>({facebook:"ð",instagram:"ð·",twitter:"ð¦",linkedin:"ð¼",youtube:"ðº",email:"âï¸",sms:"ð¬"})[_]||"ð";return e.jsxs(ae,{className:`transition-all ${$?"border-green-200 bg-green-50/50 dark:bg-green-900/10":""}`,children:[e.jsxs(ye,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(z,{variant:"outline",children:["Step ",t.sequence]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${ie?"bg-green-500":"bg-gray-300"}`}),e.jsx("span",{className:"font-medium",children:t.name})]}),t.platform&&e.jsxs(z,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx("span",{children:m(t.platform)}),t.platform]})]}),e.jsx("div",{className:"flex items-center gap-2",children:$?e.jsxs(e.Fragment,{children:[e.jsxs(z,{className:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100",children:[e.jsx(qe,{className:"w-3 h-3 mr-1"}),"Scheduled"]}),e.jsx(V,{size:"sm",variant:"outline",onClick:()=>x($.id),"data-testid":`unschedule-step-${t.id}`,children:e.jsx(sn,{className:"w-4 h-4"})})]}):ie?e.jsxs(V,{size:"sm",onClick:()=>q(!F),"data-testid":`schedule-step-${t.id}`,children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Schedule"]}):e.jsxs(z,{variant:"outline",className:"text-orange-600",children:[e.jsx(mt,{className:"w-3 h-3 mr-1"}),"No Content"]})})]}),$&&e.jsxs("div",{className:"text-sm text-green-700 dark:text-green-300 bg-green-100 dark:bg-green-900/20 p-2 rounded-md mt-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{children:["ð
",Le(new Date($.publishDate),"MMM d, yyyy 'at' h:mm a")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[m($.platform),$.platform]})]}),$.title&&e.jsx("div",{className:"mt-1 font-medium",children:$.title})]})]}),F&&ie&&!$&&e.jsx(me,{className:"pt-0 border-t",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Platform *"}),e.jsx(Vn,{platforms:c,selectedPlatform:b,onPlatformSelect:S,onConnectionRequest:()=>{},"data-testid":`platform-selector-step-${t.id}`}),b&&ha[b]&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["ð¡ ",ha[b].description]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Date *"}),e.jsx(Pe,{type:"date",value:d,onChange:_=>R(_.target.value),min:Le(new Date,"yyyy-MM-dd"),"data-testid":`date-input-step-${t.id}`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Time *"}),e.jsxs(Ce,{value:G,onValueChange:O,children:[e.jsx(Se,{"data-testid":`time-select-step-${t.id}`,children:e.jsx(Ie,{})}),e.jsxs(Te,{children:[b&&A(b).map(_=>e.jsxs(K,{value:_,children:[Le(new Date(`2024-01-01T${_}`),"h:mm a")," â"]},_)),["08:00","10:00","12:00","14:00","16:00","18:00","20:00"].map(_=>e.jsx(K,{value:_,children:Le(new Date(`2024-01-01T${_}`),"h:mm a")},_))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Title (Optional)"}),e.jsx(Pe,{value:D,onChange:_=>I(_.target.value),placeholder:`${n.name} - Step ${t.sequence}`,"data-testid":`title-input-step-${t.id}`})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Notes (Optional)"}),e.jsx(Na,{value:Q,onChange:_=>T(_.target.value),placeholder:"Add any notes or reminders...",rows:2,"data-testid":`notes-input-step-${t.id}`})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx(V,{variant:"outline",onClick:()=>q(!1),"data-testid":`cancel-schedule-step-${t.id}`,children:"Cancel"}),e.jsxs(V,{onClick:J,disabled:!b||!d,"data-testid":`confirm-schedule-step-${t.id}`,children:[e.jsx(qe,{className:"w-4 h-4 mr-2"}),"Schedule Step"]})]})]})})]})}function Ti({campaign:t,workflowSteps:n=[],onScheduleComplete:c}){const{toast:l}
22=Et(),u=Ss(),[x,b]=o.useState(!1),[S,d]=o.useState(!1),[R,G]=o.useState(null),[O,D]=o.useState(!1),{data:I,isLoading:Q}=zn(),T=(I==null?void 0:I.platforms)||[],{data:F=[],isLoading:q}=Ve({queryKey:["/api/content-schedule",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),select:k=>k.filter(M=>M.campaignId===t.id)}),$=n.filter(k=>k.content||k.copyContent||k.headline),ie=n.length,A=ie>0?$.length/ie*100:0,J=A>=50,m=dt({mutationFn:async({stepId:k,scheduleData:M})=>Ae("/api/content-schedule",{method:"POST",body:JSON.stringify({campaignId:t.id,stepId:k,variantId:1,publishDate:M.publishDate,platform:M.platform,title:M.title,notes:M.notes,isActive:!0})}),onSuccess:()=>{u.invalidateQueries({queryKey:["/api/content-schedule"]}),u.invalidateQueries({queryKey:["/api/campaigns"]}),u.invalidateQueries({queryKey:["/api/marketing-calendar"]}),G(null),D(!1),l({title:"Content Scheduled",description:"Your content has been scheduled successfully."})},onError:k=>{k instanceof Tt||k instanceof At?(G(k.message),D(!0),l({title:"Authentication Required",description:"Please sign in to schedule content.",variant:"destructive"})):l({title:"Scheduling Failed",description:k.message||"Failed to schedule content.",variant:"destructive"})}}),_=dt({mutationFn:async k=>Ae(`/api/content-schedule/${k}`,{method:"DELETE"}),onSuccess:()=>{u.invalidateQueries({queryKey:["/api/content-schedule"]}
22),u.invalidateQueries({queryKey:["/api/campaigns"]}),u.invalidateQueries({queryKey:["/api/marketing-calendar"]}),G(null),D(!1),l({title:"Content Unscheduled",description:"The scheduled content has been removed."})},onError:k=>{k instanceof Tt||k instanceof At?(G(k.message),D(!0),l({title:"Authentication Required",description:"Please sign in to manage scheduled content.",variant:"destructive"})):l({title:"Unschedule Failed",description:k.message||"Failed to unschedule content.",variant:"destructive"})}}),p=(k,M)=>{m.mutate({stepId:k,scheduleData:M})},f=k=>{_.mutate(k)},y=A===100?{color:"text-green-600",icon:Ls,text:"Ready to Schedule"}:A>=50?{color:"text-blue-600",icon:ta,text:"Partially Ready"}:{color:"text-orange-600",icon:mt,text:"Content Needed"},C=y.icon;return Q||q?e.jsx(ae,{children:e.jsxs(me,{className:"py-12 text-center",children:[e.jsx(De,{className:"h-8 w-8 animate-spin mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading scheduling options..."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ae,{children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ne,{className:"flex items-center gap-3",children:[e.jsx(qe,{className:"h-5 w-5 text-orange-500"}),"Schedule Campaign"]}),e.jsx(et,{children:"Schedule your campaign content across social platforms"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:`flex items-center gap-2 font-medium ${y.color}`,children:[e.jsx(C,{className:"h-4 w-4"}),y.text]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[$.length," of ",ie," steps ready"]})]}),e.jsxs("div",{className:"relative w-16 h-16",children:[e.jsxs("svg",{className:"transform -rotate-90 w-16 h-16",children:[e.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"4",fill:"transparent",className:"text-gray-200 dark:text-gray-700"}),e.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"4",fill:"transparent",strokeDasharray:`${2*Math.PI*28}`,strokeDashoffset:`${2*Math.PI*28*(1-A/100)}`,className:y.color,strokeLinecap:"round"})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:"text-sm font-medium",children:[Math.round(A),"%"]})})]})]})]})}),J&&e.jsx(me,{className:"pt-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(V,{onClick:()=>b(!0),disabled:$.length===0,"data-testid":"bulk-schedule-button",children:[e.jsx(ea,{className:"w-4 h-4 mr-2"}),"Bulk Schedule (",$.length," steps)"]}),e.jsxs(V,{variant:"outline",onClick:()=>d(!0),disabled:F.length===0,"data-testid":"preview-timeline-button",children:[e.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Preview Timeline"]}),F.length>0&&e.jsx(V,{variant:"outline",asChild:!0,"data-testid":"view-calendar-button",children:e.jsxs("a",{href:"/marketing-calendar",target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Cs,{className:"w-4 h-4 mr-2"}),"View in Calendar"]})})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Individual Step Scheduling"}),F.length>0&&e.jsxs(z,{variant:"secondary",children:[F.length," scheduled"]})]}),n.length===0?e.jsx(ae,{children:e.jsxs(me,{className:"py-12 text-center",children:[e.jsx(Dt,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Workflow Steps"}),e.jsx("p",{className:"text-muted-foreground",children:"Add workflow steps to your campaign to start scheduling content."})]})}):e.jsx("div",{className:"space-y-3",children:n.map(k=>e.jsx(Ii,{step:k,campaign:t,platforms:T,scheduledItems:F,onSchedule:p,onUnschedule:f},k.id))})]}),e.jsx(Ci,{isOpen:x,onClose:()=>b(!1),campaign:t,steps:$,platforms:T,onScheduleComplete:k=>{b(!1),u.invalidateQueries({queryKey:["/api/content-schedule"]}),c==null||c(k),l({title:"Bulk Scheduling Complete",description:`Scheduled ${k.length} pieces of content.`})}}),e.jsx(Si,{isOpen:S,onClose:()=>d(!1),campaign:t,scheduledContent:F,workflowSteps:n}),e.jsx(vt,{open:O,onOpenChange:D,children:e.jsxs(bt,{className:"sm:max-w-md","data-testid":"auth-prompt-dialog",children:[e.jsx(yt,{children:e.jsxs(jt,{className:"flex items-center gap-2",children:[e.jsx(an,{className:"w-5 h-5 text-orange-500"}),"Authentication Required"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-orange-50 dark:bg-orange-900/20 rounded-lg",children:[e.jsx(mt,{className:"w-5 h-5 text-orange-600 mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-orange-900 dark:text-orange-100",children:"Sign in required"}),e.jsx("p",{className:"text-xs text-orange-800 dark:text-orange-200",children:R||"You need to be signed in to schedule campaign content."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please sign in to continue scheduling your campaign content. Your scheduling data will be preserved."}),e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg",children:[e.jsx(Ja,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-blue-900 dark:text-blue-100",children:'Click "Sign In" to authenticate and resume scheduling'})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(V,{variant:"outline",onClick:()=>{D(!1),G(null)},"data-testid":"auth-prompt-dismiss",children:"Dismiss"}),e.jsxs(V,{onClick:()=>{window.location.reload()},"data-testid":"auth-prompt-signin",children:[e.jsx(Ja,{className:"w-4 h-4 mr-2"}),"Sign In"]})]})]})]})})]})}const lt=[{key:"copyTone",label:"Copy Tone",type:"select",required:!0,helpText:"How should the AI write the content?",options:[{value:"professional",label:"Professional - Business-focused and credible"},{value:"friendly",label:"Friendly - Warm and approachable"},{value:"urgent",label:"Urgent - Time-sensitive and compelling"},{value:"casual",label:"Casual - Relaxed and conversational"},{value:"curious",label:"Curious - Question-driven and engaging"},{value:"confident",label:"Confident - Authoritative and direct"}],defaultValue:"professional"},{key:"contentLength",label:"Content Length",type:"select",required:!0,helpText:"How much detail should the AI include?",options:[{value:"ultra_concise",label:"Ultra Concise - 1-2 sentences, direct impact"},{value:"concise_action_focused",label:"Concise & Action-Focused - 2-3 sentences with clear CTA"},{value:"medium_context",label:"Medium Context - 3-5 sentences with key benefits"},{value:"detailed_explanation",label:"Detailed Explanation - 5-8 sentences with full story"},{value:"long_form_story",label:"Long-form Story - 8+ sentences, narrative-driven"}],defaultValue:"medium_context"},{key:"callToActionType",label:"Call-to-Action Type",type:"select",required:!0,helpText:"What action should the audience take?",options:[{value:"learn_more",label:"Learn More - Soft engagement"},{value:"book_now",label:"Book Now - Schedule appointment"},{value:"get_quote",label:"Get Quote - Request pricing"},{value:"call_now",label:"Call Now - Phone contact"},{value:"visit_website",label:"Visit Website - Web traffic"},{value:"download",label:"Download - Get resource"},{value:"sign_up",label:"Sign Up - Registration"},{value:"contact_us",label:"Contact Us - General inquiry"}],defaultValue:"learn_more"},{key:"urgencyLevel",label:"Urgency Level",type:"select",required:!0,helpText:"How urgent should the messaging feel? (Temperature-dependent)",options:[{value:"no_urgency",label:"No Urgency - Informational, evergreen (Cold)"},{value:"gentle_nudge",label:"Gentle Nudge - Soft encouragement (Cold to Warm)"},{value:"moderate_urgency",label:"Moderate Urgency - Clear benef
22its (Warm)"},{value:"high_urgency",label:"High Urgency - Time-sensitive (Hot)"},{value:"immediate_action",label:"Immediate Action - Act now (Hot)"},{value:"loyalty_appreciation",label:"Loyalty Appreciation - Exclusive feel (Existing)"}],defaultValue:"moderate_urgency"},{key:"contentStrategy",label:"Content Strategy",type:"select",required:!0,helpText:"What approach should guide the content? (Awareness-dependent)",options:[{value:"problem_awareness",label:"Problem Awareness - Introduce issues (Cold)"},{value:"solution_education",label:"Solution Education - Explain options (Cold to Warm)"},{value:"benefit_focused",label:"Benefit Focused - Highlight value (Warm)"},{value:"credibility_building",label:"Credibility Building - Establish trust (Warm to Hot)"},{value:"conversion_optimized",label:"Conversion Optimized - Drive action (Hot)"},{value:"retention_focused",label:"Retention Focused - Maintain relationship (Existing)"}],defaultValue:"benefit_focused"},{key:"keywords",label:"Focus Keywords",type:"text",maxLength:200,helpText:"Key terms to emphasize (comma-separated)",defaultValue:""},{key:"customInstructions",label:"Custom AI Instructions",type:"textarea",maxLength:300,helpText:"Specific instructions for AI content generation",defaultValue:""}],Ai=[{id:"facebook_ads",name:"Facebook Ads",fields:[...lt,{key:"headline",label:"Headline",type:"text",maxLength:40},{key:"primaryText",label:"Primary Text",type:"textarea",maxLength:2200},{key:"description",label:"Description",type:"text",maxLength:30},{key:"linkDescription",label:"Link Description",type:"text",maxLength:20},{key:"callToAction",label:"Call to Action Button",type:"text",maxLength:20},{key:"adObjective",label:"Ad Objective",type:"select",required:!0,helpText:"What's the primary goal of this Facebook ad?",options:[{value:"awareness",label:"Awareness - Increase brand recognition"},{value:"traffic",label:"Traffic - Drive website visits"},{value:"engagement",label:"Engagement - Likes, comments, shares"},{value:"leads",label:"Leads - Generate lead forms"},{value:"conversions",label:"Conversions - Drive purchases/actions"},{value:"video_views",label:"Video Views - Maximize video engagement"}],defaultValue:"traffic"},{key:"audienceTargeting",label:"Audience Targeting",type:"select",required:!0,helpText:"Who should see this ad? Based on temperature and awareness level",options:[{value:"broad_interests",label:"Broad Interests - Cast wide net for cold audience"},{value:"detailed_targeting",label:"Detailed Targeting - Specific interests/behaviors"},{value:"lookalike",label:"Lookalike Audience - Similar to existing customers"},{value:"custom_audience",label:"Custom Audience - Retarget website visitors"},{value:"engaged_audience",label:"Engaged Audience - Interacted with brand"}],defaultValue:"detailed_targeting"},{key:"placementStrategy",label:"Placement Strategy",type:"select",required:!0,helpText:"Where should your ad appear for maximum impact?",options:[{value:"automatic",label:"Automatic Placements - Let Facebook optimize"},{value:"feed_only",label:"Feed Only - Facebook & Instagram feeds"},{value:"stories_focus",label:"Stories Focus - Mobile-first vertical content"},{value:"reels_priority",label:"Reels Priority - Short-form video emphasis"},{value:"messenger_ads",label:"Messenger Ads - Direct conversation starters"}],defaultValue:"automatic"}],characterLimits:{headline:40,primaryText:2200,description:30,linkDescription:20,callToAction:20}},{id:"google_search",name:"Google Search Ads",fields:[...lt,{key:"headline1",label:"Headline 1",type:"text",maxLength:30},{key:"headline2",label:"Headline 2",type:"text",maxLength:30},{key:"headline3",label:"Headline 3",type:"text",maxLength:30},{key:"description1",label:"Description 1",type:"text",maxLength:90},{key:"description2",label:"Description 2",type:"text",maxLength:90},{key:"path1",label:"Path 1",type:"text",maxLength:15},{key:"path2",label:"Path 2",type:"text",maxLength:15},{key:"matchType",label:"Keyword Match Type",type:"select",required:!0,helpText:"How closely should search terms match your keywords?",options:[{value:"broad",label:"Broad Match - Maximum reach, related searches"},{value:"phrase",label:"Phrase Match - Includes meaning of keyword"},{value:"exact",label:"Exact Match - Precise keyword targeting"},{value:"broad_modifier",label:"Broad Match Modifier - Required terms plus variations"}],defaultValue:"phrase"},{key:"bidStrategy",label:"Bidding Strategy",type:"select",required:!0,helpText:"How should Google optimize your ad spend?",options:[{value:"maximize_clicks",label:"Maximize Clicks - Drive traffic (Cold/Warm)"},{value:"target_cpa",label:"Target CPA - Focus on conversions (Hot)"},{value:"maximize_conversions",label:"Maximize Conversions - Volume focus"},{value:"target_roas",label:"Target ROAS - Return on ad spend (Existing)"},{value:"manual_cpc",label:"Manual CPC - Full control over bids"}],defaultValue:"maximize_clicks"},{key:"adExtensions",label:"Ad Extensions",type:"select",required:!0,helpText:"What additional information should appear with your ad?",options:[{value:"sitelinks",label:"Sitelinks - Additional page links"},{value:"callouts",label:"Callouts - Key business highlights"},{value:"structured_snippets",label:"Structured Snippets - Service categories"},{value:"call_extensions",label:"Call Extensions - Phone number prominence"}
22,{value:"location_extensions",label:"Location Extensions - Business address"},{value:"price_extensions",label:"Price Extensions - Service pricing preview"}],defaultValue:"sitelinks"}],characterLimits:{headline1:30,headline2:30,headline3:30,description1:90,description2:90,path1:15,path2:15}},{id:"email_marketing",name:"Email Marketing",fields:[...lt,{key:"subject",label:"Subject Line",type:"text",maxLength:50},{key:"preHeader",label:"Pre-header",type:"text",maxLength:90},{key:"bodyText",label:"Email Body",type:"textarea",maxLength:5e3},{key:"callToAction",label:"Call to Action",type:"text",maxLength:25},{key:"emailType",label:"Email Type",type:"select",required:!0,helpText:"What type of email campaign is this?",options:[{value:"welcome",label:"Welcome - Onboard new subscribers"},{value:"newsletter",label:"Newsletter - Regular content updates"},{value:"promotional",label:"Promotional - Sales and offers"},{value:"transactional",label:"Transactional - Order confirmations"},{value:"nurture",label:"Nurture - Educational content"},{value:"retention",label:"Retention - Re-engage inactive users"}],defaultValue:"newsletter"},{key:"personalizationLevel",label:"Personalization Level",type:"select",required:!0,helpText:"How personalized should this email be?",options:[{value:"basic",label:"Basic - Name personalization only"},{value:"behavioral",label:"Behavioral - Based on past actions"},{value:"segmented",label:"Segmented - Audience-specific content"},{value:"dynamic",label:"Dynamic - Real-time content adaptation"},{value:"individual",label:"Individual - Unique per recipient"}],defaultValue:"segmented"},{key:"sendTiming",label:"Send Timing",type:"select",required:!0,helpText:"When should this email be sent for optimal engagement?",options:[{value:"immediate",label:"Immediate - Send right away"},{value:"optimal",label:"Optimal - AI-determined best time"},{value:"business_hours",label:"Business Hours - 9 AM - 5 PM"},{value:"evening",label:"Evening - 6 PM - 9 PM"},{value:"weekend",label:"Weekend - Saturday mornings"},{value:"event_triggered",label:"Event Triggered - Based on user action"}],defaultValue:"optimal"}],characterLimits:{subject:50,preHeader:90,callToAction:25}},{id:"sms",name:"SMS Marketing",fields:[...lt,{key:"message",label:"SMS Message",type:"textarea",maxLength:160},{key:"smsType",label:"SMS Campaign Type",type:"select",required:!0,helpText:"What type of SMS campaign is this?",options:[{value:"promotional",label:"Promotional - Sales and special offers"},{value:"transactional",label:"Transactional - Order updates and confirmations"},{value:"reminder",label:"Reminder - Appointments and deadlines"},{value:"alert",label:"Alert - Important notifications"},{value:"survey",label:"Survey - Feedback and reviews"},{value:"welcome",label:"Welcome - New customer onboarding"}],defaultValue:"promotional"},{key:"deliveryTiming",label:"Delivery Timing",type:"select",required:!0,helpText:"When is the best time to send this SMS?",options:[{value:"immediate",label:"Immediate - Send right away"},{value:"business_hours",label:"Business Hours - 9 AM - 6 PM"},{value:"optimal_mobile",label:"Optimal Mobile - Peak phone usage times"},{value:"local_timezone",label:"Local Timezone - Recipient's time zone"},{value:"scheduled",label:"Scheduled - Specific date and time"},{value:"triggered",label:"Triggered - Based on user behavior"}],defaultValue:"optimal_mobile"},{key:"complianceLevel",label:"Compliance Level",type:"select",required:!0,helpText:"What compliance requirements apply?",options:[{value:"standard",label:"Standard - Basic opt-out compliance"},{value:"tcpa_strict",label:"TCPA Strict - Full regulatory compliance"},{value:"international",label:"International - Global SMS regulations"},{value:"healthcare",label:"Healthcare - HIPAA-compliant messaging"},{value:"financial",label:"Financial - Banking and finance regulations"}],defaultValue:"standard"}],characterLimits:{message:160}},{id:"linkedin_ads",name:"LinkedIn Ads",fields:[...lt,{key:"headline",label:"Headline",type:"text",maxLength:200},{key:"description",label:"Description",type:"textarea",maxLength:600},{key:"callToAction",label:"Call to Action",type:"text",maxLength:30},{key:"engagementTrigger",label:"Engagement Trigger",type:"select",required:!0,helpText:"What user behavior triggers this ad targeting?",options:[{value:"content_sharing",label:"Content Sharing - High sharing velocity and amplification"},{value:"connection_requests",label:"Connection Requests - Active professional networking"},{value:"lead_form_clicks",label:"Lead Form Clicks - B2B intent and form completion"},{value:"profile_viewing",label:"Profile Viewing - Research and browsing behavior"},{value:"comment_engagement",label:"Comment Engagement - Discussion participation"},{value:"website_visits",label:"Website Visits - Purchase browsing behavior"}],defaultValue:"content_sharing"},{key:"responseTimeWindow",label:"Response Time Window",type:"select",required:!0,helpText:"When should this ad be shown for optimal B2B engagement?",options:[{value:"business_hours",label:"Business Hours
22- Standard 9-5 professional targeting"},{value:"decision_maker_hours",label:"Decision Maker Hours - Early morning and late afternoon"},{value:"networking_times",label:"Networking Times - Lunch hours and evening events"},{value:"industry_peak",label:"Industry Peak - Sector-specific optimal engagement windows"},{value:"global_business",label:"Global Business - 24/7 international professional targeting"},{value:"weekend_planning",label:"Weekend Planning - Strategic planning and research time"}],defaultValue:"business_hours"},{key:"amplificationStrategy",label:"Amplification Strategy",type:"select",required:!0,helpText:"How should this content be amplified across LinkedIn's network?",options:[{value:"sponsored_content",label:"Sponsored Content - Native feed placement with organic feel"},{value:"audience_expansion",label:"Audience Expansion - Lookalike professional targeting"},{value:"employee_advocacy",label:"Employee Advocacy - Team member amplification"},{value:"thought_leadership",label:"Thought Leadership - Industry influence and expertise"},{value:"network_effect",label:"Network Effect - Connection-based viral expansion"},{value:"retargeting_loops",label:"Retargeting Loops - Multi-touch professional sequences"}],defaultValue:"sponsored_content"},{key:"behavioralTargeting",label:"Behavioral Targeting",type:"select",required:!0,helpText:"What professional behavior patterns should this target?",options:[{value:"job_function_focus",label:"Job Function Focus - Role-specific professional targeting"},{value:"seniority_targeting",label:"Seniority Targeting - Leadership and decision-maker levels"},{value:"company_size_segment",label:"Company Size Segment - Enterprise vs SMB behavior patterns"},{value:"industry_behavior",label:"Industry Behavior - Sector-specific professional patterns"},{value:"growth_stage_focus",label:"Growth Stage Focus - Startup vs established company targeting"},{value:"buying_committee",label:"Buying Committee - B2B purchase decision influencers"}],defaultValue:"job_function_focus"},{key:"lifecycleStage",label:"Lifecycle Stage",type:"select",required:!0,helpText:"What stage of the professional journey should this target?",options:[{value:"journey_mapping",label:"Journey Mapping - Professional pathway targeting and career stage analysis"},{value:"funnel_targeting",label:"Funnel Targeting - Sales pipeline and conversion stage optimization"},{value:"conversion_tracking",label:"Conversion Tracking - B2B outcome measurement and ROI optimization"},{value:"relationship_building",label:"Relationship Building - Long-term professional network development"},{value:"expertise_demonstration",label:"Expertise Demonstration - Authority building and thought leadership"},{value:"partnership_development",label:"Partnership Development - Strategic business relationship expansion"}],defaultValue:"journey_mapping"},{key:"timeFromTrigger",label:"Time From Trigger",type:"select",required:!0,helpText:"How should campaign timing and frequency be optimized?",options:[{value:"sequence_optimization",label:"Sequence Optimization - Multi-touch campaign timing coordination"},{value:"frequency_capping",label:"Frequency Capping - Professional exposure limit management"},{value:"business_hour_strategy",label:"Business Hour Strategy - Professional availability window targeting"},{value:"decision_cycle_timing",label:"Decision Cycle Timing - B2B purchase process alignment"},{value:"relationship_pacing",label:"Relationship Pacing - Professional trust building timeline"},{value:"industry_event_sync",label:"Industry Event Sync - Conference and professional event coordination"}],defaultValue:"sequence_optimization"},{key:"riskLevel",label:"Risk Level",type:"select",required:!0,helpText:"What professional risk factors should influence targeting strategy?",options:[{value:"churn_prediction",label:"Churn Prediction - Client retention risk assessment and targeting"},{value:"competitive_conquest",label:"Competitive Conquest - B2B competitor displacement strategies"},{value:"retention_optimization",label:"Retention Optimization - Professional relationship preservation tactics"},{value:"expansion_risk",label:"Expansion Risk - Account growth opportunity assessment"},{value:"loyalty_preservation",label:"Loyalty Preservation - High-value client protection strategies"},{value:"market_disruption",label:"Market Disruption - Industry change adaptation targeting"}],defaultValue:"churn_prediction"},{key:"expansionOpportunity",label:"Expansion Opportunity",type:"select",required:!0,helpText:"What growth and expansion opportunities should this campaign target?",options:[{value:"account_expansion",label:"Account Expansion - Existing client growth and department penetration"},{value:"enterprise_scaling",label:"Enterprise Scaling - Large organization multi-department targeting"},{value:"cross_sell_potential",label:"Cross-sell Potential - Complementary service and product promotion"},{value:"vertical_expansion",label:"Vertical Expansion - Industry sector growth and specialization"},{value:"geographic_growth",label:"Geographic Growth - Regional and international market expansion"},{value:"partnership_scaling",label:"Partnership Scaling - Strategic alliance and referral network growth"}],defaultValue:"account_expansion"},{key:"timingTrigger",label:"Timing Trigger",type:"select",required:!0,helpText:"What timing mechanisms should trigger and optimize this campaign?",options:[{value:"business_hour_bidding",label:"Business Hour Bidding - Automated professional availability optimization"},{value:"industry_event_triggers",label:"Industry Event Triggers - Conference and professional event synchronization"},{value:"quarterly_cycle_activation",label:"Quarterly Cycle Activation - Business quarter and budget cycle alignment"},{value:"decision_maker_windows",label:"Decision Maker Windows - Executive and leadership optimal timing"},{value:"procurement_cycles",label:"Procurement Cycles - Enterprise purchasing and approval timing"},{value:"competitive_moments",label:"Competitive Moments - Industry disruption and opportunity timing"}],defaultValue:"business_hour_bidding"},{key:"urgencyLevel",label:"Urgency Level",type:"select",required:!0,helpText:"What level of business urgency and priority should this convey?",options:[{value:"accelerated_delivery",label:"Accelerated Delivery - Fast-track B2B solutions and immediate results"},{value:"executive_priority",label:"Executive Priority - C-level attention and leadership urgency"},{value:"immediate_impact",label:"Immediate Impact - Quick wins and instant business value"},{value:"deadline_driven",label:"Deadline Driven - Time-sensitive business objectives and quarters"},{value:"competitive_urgency",label:"Competitive Urgency - Market advantage and first-mover positioning"},{value:"strategic_timing",label:"Strategic Timing - Long-term professional relationship building"}],defaultValue:"accelerated_delivery"},{key:"competitiveResponse",label:"Competitive Response",type:"select",required:!0,helpText:"How should this campaign respond to competitive dynamics?",options:[{value:"keyword_bidding",label:"Keyword Bidding - B2B competitive search term targeting and bidding"},{value:"enterprise_defense",label:"Enterprise Defense - Large account protection and retention automation"},{value:"counter_campaigns",label:"Counter Campaigns - Industry competitive messaging and positioning"},{value:"market_positioning",label:"Market Positioning - Thought leadership and industry authority claims"},{value:"disruption_response",label:"Disruption Response - Industry change adaptation and leadership"},{value:"alliance_building",label:"Alliance Building - Partnership and ecosystem competitive advantages"}],defaultValue:"keyword_bidding"},{key:"trendAlignment",label:"Trend Alignment",type:"select",required:!0,helpText:"How should this campaign align with industry trends and professional moments?",options:[{value:"hashtag_integration",label:"Hashtag Integration - Industry trending topics and professional discussions"},{value:"moment_targeting",label:"Moment Targeting - Real-time professional events and industry news"},{value:"viral_amplification",label:"Viral Amplification - Business content scaling and professional sharing"},{value:"thought_leadership",label:"Thought Leadership - Industry opinion and expertise positioning"}
22,{value:"trend_anticipation",label:"Trend Anticipation - Future industry direction and early adoption"},{value:"community_building",label:"Community Building - Professional network and industry group engagement"}],defaultValue:"hashtag_integration"},{key:"personalityProfile",label:"Personality Profile",type:"select",required:!0,helpText:"What professional personality traits should this campaign target?",options:[{value:"leadership_traits",label:"Leadership Traits - Executive mindset and strategic thinking patterns"},{value:"analytical_decision_makers",label:"Analytical Decision Makers - Data-driven and research-focused professionals"},{value:"innovative_early_adopters",label:"Innovative Early Adopters - Technology leaders and change champions"},{value:"relationship_builders",label:"Relationship Builders - Network-focused and collaboration-oriented professionals"},{value:"results_oriented",label:"Results Oriented - Achievement and performance-driven professionals"},{value:"security_minded",label:"Security Minded - Risk-averse and compliance-focused professionals"}],defaultValue:"leadership_traits"},{key:"valueAlignment",label:"Value Alignment",type:"select",required:!0,helpText:"What professional values and ideologies should this resonate with?",options:[{value:"innovation_culture",label:"Innovation Culture - Technology advancement and disruptive thinking"},{value:"quality_excellence",label:"Quality Excellence - Premium standards and superior performance values"},{value:"efficiency_optimization",label:"Efficiency Optimization - Cost-effectiveness and resource maximization"},{value:"collaboration_teamwork",label:"Collaboration Teamwork - Partnership and community-building values"},{value:"security_compliance",label:"Security Compliance - Risk management and regulatory adherence values"},{value:"growth_achievement",label:"Growth Achievement - Success and professional advancement values"}],defaultValue:"innovation_culture"},{key:"decisionMakingStyle",label:"Decision Making Style",type:"select",required:!0,helpText:"What decision-making approach should the messaging align with?",options:[{value:"analytical_proof_based",label:"Analytical Proof Based - Data, research, and evidence-driven decisions"},{value:"intuitive_relationship_based",label:"Intuitive Relationship Based - Trust, referrals, and relationship decisions"},{value:"committee_consensus",label:"Committee Consensus - Group evaluation and stakeholder approval processes"},{value:"individual_authority",label:"Individual Authority - Single decision-maker and executive choice"},{value:"risk_assessment_focused",label:"Risk Assessment Focused - Security and compliance evaluation priorities"},{value:"outcome_results_focused",label:"Outcome Results Focused - Performance and ROI-driven decision criteria"}],defaultValue:"analytical_proof_based"},{key:"communicationPreference",label:"Communication Preference",type:"select",required:!0,helpText:"What communication style and format should this campaign use?",options:[{value:"executive_briefing",label:"Executive Briefing - Concise, strategic, and high-level professional communication"},{value:"detailed_technical",label:"Detailed Technical - Comprehensive, data-rich, and analytical communication"},{value:"collaborative_discussion",label:"Collaborative Discussion - Interactive, community-focused, and engaging communication"},{value:"premium_presentation",label:"Premium Presentation - Polished, prestigious, and status-conscious communication"},{value:"practical_efficiency",label:"Practical Efficiency - Direct, cost-focused, and results-oriented communication"},{value:"innovative_forward_thinking",label:"Innovative Forward Thinking - Creative, trend-setting, and visionary communication"}],defaultValue:"executive_briefing"},{key:"marketPosition",label:"Market Position",type:"select",required:!0,helpText:"What competitive market position should this campaign establish or defend?",options:[{value:"industry_authority_building",label:"Industry Authority Building - Thought leadership and market expertise positioning"},{value:"competitive_positioning",label:"Competitive Positioning - B2B market differentiation and advantage messaging"},{value:"market_disruption",label:"Market Disruption - Industry innovation and change leadership positioning"},{value:"defensive_positioning",label:"Defensive Positioning - Market share protection and competitive defense"},{value:"challenger_positioning",label:"Challenger Positioning - Alternative solution and market conquest messaging"},{value:"premium_positioning",label:"Premium Positioning - Quality leadership and superior value proposition"}],defaultValue:"industry_authority_building"},{key:"competitiveThreat",label:"Competitive Threat",type:"select",required:!0,helpText:"What competitive threats should this campaign address or monitor?",options:[{value:"keyword_competition",label:"Keyword Competition - Search term and bidding competitive defense"},{value:"pricing_pressure",label:"Pricing Pressure - Cost competition and value positioning response"},{value:"feature_parity",label:"Feature Parity - Product capability competition and differentiation"},{value:"market_share_erosion",label:"Market Share Erosion - Customer retention and defensive enterprise bidding"},{value:"brand_reputation",label:"Brand Reputation - Professional image and thought leadership protection"},{value:"innovation_lag",label:"Innovation Lag - Technology advancement and industry leadership threats"}],defaultValue:"keyword_competition"},{key:"differentiationStrategy",label:"Differentiation Strategy",type:"select",required:!0,helpText:"What unique advantages should this campaign emphasize for competitive distinction?",options:[{value:"unique_value_proposition",label:"Unique Value Proposition - Professional USP emphasis and solution distinction"},{value:"superior_features",label:"Superior Features - Advanced capabilities and technology advantage messaging"},{value:"industry_expertise",label:"Industry Expertise - Specialized knowledge and professional authority positioning"},{value:"customer_success",label:"Customer Success - Proven results and B2B outcome advantages"},{value:"innovation_leadership",label:"Innovation Leadership - Technology advancement and forward-thinking positioning"},{value:"service_excellence",label:"Service Excellence - Support quality and professional relationship advantages"}],defaultValue:"unique_value_proposition"},{key:"responseUrgency",label:"Response Urgency",type:"select",required:!0,helpText:"What level of urgency should this competitive response campaign have?",options:[{value:"immediate_crisis_response",label:"Immediate Crisis Response - Emergency professional messaging and rapid deployment"},{value:"rapid_competitive_response",label:"Rapid Competitive Response - Fast B2B threat addressing and defensive action"},{value:"strategic_competitive_timing",label:"Strategic Competitive Timing - Planned competitive positioning and market timing"},{value:"proactive_market_defense",label:"Proactive Market Defense - Preventive competitive measures and authority building"},{value:"opportunistic_competitive_strike",label:"Opportunistic Competitive Strike - Market opportunity exploitation and conquest timing"},{value:"sustained_competitive_pressure",label:"Sustained Competitive Pressure - Long-term competitive positioning and market presence"}],defaultValue:"immediate_crisis_response"},{key:"adaptiveTrigger",label:"Adaptive Trigger",type:"select",required:!0,helpText:"What AI-driven optimization triggers should automatically adjust this campaign?",options:[{value:"automated_optimization",label:"Automated Optimization - AI-driven B2B performance adjustments and enterprise bidding"},{value:"performance_adjustments",label:"Performance Adjustments - Real-time professional targeting and creative optimization"},{value:"audience_expansion",label:"Audience Expansion - Automated professional audience discovery and targeting growth"},{value:"bid_optimization",label:"Bid Optimization - Dynamic B2B bid adjustments and competitive positioning"},{value:"creative_adaptation",label:"Creative Adaptation - AI-powered content and messaging performance optimization"},{value:"sentiment_response",label:"Sentiment Response - Professional mood-based messaging and emotional targeting"}],defaultValue:"automated_optimization"},{key:"learningSpeed",label:"Learning Speed",type:"select",required:!0,helpText:"How quickly should the AI learn and optimize from professional performance data?",options:[{value:"rapid_testing",label:"Rapid Testing - Fast B2B experimentation and quick professional optimization cycles"},{value:"accelerated_learning",label:"Accelerated Learning - Enhanced machine learning velocity for enterprise campaigns"},{value:"continuous_optimization",label:"Continuous Optimization - Real-time professional performance adjustments"},{value:"adaptive_iteration",label:"Adaptive Iteration - Dynamic B2B testing and iterative improvement cycles"},{value:"intelligent_scaling",label:"Intelligent Scaling - AI-powered professional audience and budget scaling"},{value:"predictive_acceleration",label:"Predictive Acceleration - Forec
22asting-based optimization and performance prediction"}],defaultValue:"rapid_testing"},{key:"personalizationDepth",label:"Personalization Depth",type:"select",required:!0,helpText:"What level of individual professional targeting and customization should this use?",options:[{value:"individual_targeting",label:"Individual Targeting - Personalized professional messaging and micro-targeting"},{value:"micro_segmentation",label:"Micro Segmentation - Granular enterprise audience and behavioral customization"},{value:"behavioral_customization",label:"Behavioral Customization - Professional activity-based content and timing optimization"},{value:"dynamic_personalization",label:"Dynamic Personalization - Real-time B2B content adaptation and individual messaging"},{value:"contextual_adaptation",label:"Contextual Adaptation - Professional situation-aware messaging and targeting"},{value:"predictive_personalization",label:"Predictive Personalization - AI-forecasted professional needs and preference targeting"}],defaultValue:"individual_targeting"},{key:"predictiveModel",label:"Predictive Model",type:"select",required:!0,helpText:"What AI forecasting models should guide professional targeting and optimization?",options:[{value:"conversion_prediction",label:"Conversion Prediction - B2B conversion probability modeling and targeting optimization"},{value:"performance_forecasting",label:"Performance Forecasting - Professional campaign outcome prediction and budget allocation"},{value:"audience_modeling",label:"Audience Modeling - Enterprise audience behavior prediction and targeting enhancement"},{value:"engagement_prediction",label:"Engagement Prediction - Professional interaction forecasting and content optimization"},{value:"lifetime_value_modeling",label:"Lifetime Value Modeling - B2B customer value prediction and acquisition targeting"},{value:"competitive_intelligence",label:"Competitive Intelligence - Market trend prediction and competitive positioning forecasting"}],defaultValue:"conversion_prediction"}],characterLimits:{headline:200,description:600,callToAction:30}},{id:"blogs",name:"Blog Posts",fields:[{key:"copyTone",label:"Copy Tone",type:"select",required:!0,helpText:"How should the AI write the content?",options:[{value:"professional",label:"Professional - Business-focused and credible"},{value:"friendly",label:"Friendly - Warm and approachable"},{value:"urgent",label:"Urgent - Time-sensitive and compelling"},{value:"casual",label:"Casual - Relaxed and conversational"},{value:"curious",label:"Curious - Question-driven and engaging"},{value:"confident",label:"Confident - Authoritative and direct"}],defaultValue:"professional"},{key:"contentLength",label:"Blog Post Length",type:"select",required:!0,helpText:"How long should the blog post be?",options:[{value:"news_article",label:"News Article - 600-1,000 words"},{value:"informational_post",label:"Informational Post - 1,000-1,500 words"},{value:"comprehensive_guide",label:"Comprehensive Guide - 1,500-2,500 words"},{value:"in_depth_analysis",label:"In-Depth Analysis - 2,500+ words"}],defaultValue:"informational_post"},{key:"callToActionType",label:"Call-to-Action Type",type:"select",required:!0,helpText:"What action should the audience take?",options:[{value:"learn_more",label:"Learn More - Soft engagement"},{value:"book_now",label:"Book Now - Schedule appointment"},{value:"get_quote",label:"Get Quote - Request pricing"},{value:"call_now",label:"Call Now - Phone contact"},{value:"visit_website",label:"Visit Website - Web traffic"},{value:"download",label:"Download - Get resource"},{value:"sign_up",label:"Sign Up - Registration"},{value:"contact_us",label:"Contact Us - General inquiry"}],defaultValue:"learn_more"},{key:"urgencyLevel",label:"Urgency Level",type:"select",required:!0,helpText:"How urgent should the message feel?",options:[{value:"no_urgency",label:"No Urgency - Informational and patient"},{value:"moderate_urgency",label:"Moderate Urgency - Encouraging action"},{value:"high_urgency",label:"High Urgency - Time-sensitive"},{value:"loyalty_appreciation",label:"Loyalty Appreciation - Thank existing customers"}],defaultValue:"no_urgency"},{key:"contentStrategy",label:"Content Strategy",type:"select",required:!0,helpText:"What should the content focus on?",options:[{value:"problem_awareness",label:"Problem Awareness - Introduce issues (Cold)"},{value:"solution_education",label:"Solution Education - Explain options (Cold to Warm)"},{value:"benefit_focused",label:"Benefit Focused - Highlight value (Warm)"},{value:"credibility_building",label:"Credibility Building - Establish trust (Warm to Hot)"},{value:"conversion_optimized",label:"Conversion Optimized - Drive action (Hot)"},{value:"retention_focused",label:"Retention Focused - Maintain relationship (Existing)"}],defaultValue:"benefit_focused"},{key:"copywritingStrategy",label:"Copywriting Strategy",type:"select",required:!0,helpText:"Which copywriting formula should guide the content structure?",options:[{value:"4cs",label:"4Cs - Clear, Concise, Compelling, Credible approach"},{value:"4ps",label:"4Ps - Promise, Picture, Proof, Push structure"},{value:"4us",label:"4Us - Urgent, Unique, Useful, Ultra-specific content"},{value:"acca",label:"ACCA - Awareness, Comprehension, Conviction, Action flow"},{value:"aducate",label:"ADUCATE - Aim, Difficulty, Understanding, Credibility, Action, Teach, Exit"},{value:"aida",label:"AIDA - Attention, Interest, Desire, Action progression"},{value:"bab",label:"BAB - Before, After, Bridge transformation"},{value:"fab",label:"FAB - Features, Advantages, Benefits focus"},{value:"pas",label:"PAS - Problem, Agitate, Solution method"},{value:"quest",label:"QUEST - Qualify, Understand, Educate, Stimulate, Transition"},{value:"6plus1",label:"6+1 Model - Command attention through close deal sequence"}],defaultValue:"aida"},{key:"keywords",label:"Focus Keywords",type:"text",maxLength:200,helpText:"Key terms to emphasize (comma-separated)",defaultValue:""}
22,{key:"customInstructions",label:"Custom AI Instructions",type:"textarea",maxLength:300,helpText:"Specific instructions for AI content generation",defaultValue:""},{key:"writingStyle",label:"Writing Style",type:"select",required:!0,helpText:"What blog format should the AI use?",options:[{value:"how_to_guide",label:"How-To Guide - Step-by-step instructions"},{value:"listicle",label:"Listicle - Numbered or bulleted lists"},{value:"case_study",label:"Case Study - Real examples and results"},{value:"opinion_piece",label:"Opinion Piece - Personal perspective"},{value:"news_update",label:"News Update - Current events and trends"},{value:"comparison",label:"Comparison - Side-by-side analysis"}],defaultValue:"how_to_guide"},{key:"seoFocus",label:"SEO Focus",type:"select",required:!0,helpText:"What SEO strategy should guide the content?",options:[{value:"local_seo",label:"Local SEO - Geographic targeting"},{value:"industry_specific",label:"Industry Terms - Technical keywords"},{value:"long_tail",label:"Long Tail - Specific phrases"},{value:"educational",label:"Educational - 'How to' queries"}],defaultValue:"industry_specific"},{key:"title",label:"Blog Title",type:"text",maxLength:100},{key:"urlSlug",label:"URL Slug",type:"text",maxLength:100,helpText:"URL-friendly version of the title"},{key:"featuredImage",label:"Featured Image",type:"text",maxLength:500,helpText:"URL or path to the main blog image"},{key:"metaDescription",label:"Meta Description",type:"text",maxLength:160},{key:"introduction",label:"Introduction",type:"textarea",maxLength:500},{key:"blogContent",label:"Main Content",type:"textarea",maxLength:5e3},{key:"conclusion",label:"Conclusion",type:"textarea",maxLength:300},{key:"tags",label:"Tags",type:"text",maxLength:200,helpText:"Comma-separated tags"}],characterLimits:{title:100,urlSlug:100,featuredImage:500,metaDescription:160,introduction:500,blogContent:5e3,conclusion:300,tags:200}},{id:"tiktok_ads",name:"TikTok Ads",fields:[{key:"copyTone",label:"Copy Tone",type:"select",required:!0,helpText:"What tone should this TikTok ad copy use?",options:[{value:"playful",label:"Playful - Fun and entertaining TikTok-native messaging"},{value:"trendy",label:"Trendy - Current and culturally relevant viral content"},{value:"authentic",label:"Authentic - Real and relatable user-generated style"},{value:"energetic",label:"Energetic - High-energy and exciting video content"},{value:"educational",label:"Educational - Informative and tutorial-style content"},{value:"aspirational",label:"Aspirational - Inspiring and goal-oriented messaging"},{value:"humorous",label:"Humorous - Comedy and meme-driven content"}],defaultValue:"trendy"},{key:"contentStrategy",label:"Content Strategy",type:"select",required:!0,helpText:"What content strategy should this TikTok campaign focus on?",options:[{value:"viral_trending",label:"Viral Trending - Trend-riding and hashtag challenge content"},{value:"user_generated",label:"User Generated - Community-driven and authentic content"},{value:"influencer_collab",label:"Influencer Collab - Creator partnership and endorsement content"},{value:"educational_tips",label:"Educational Tips - How-to and tutorial-style content"},{value:"behind_scenes",label:"Behind Scenes - Authentic brand storytelling content"},{value:"product_showcase",label:"Product Showcase - Product demonstration and feature highlighting"},{value:"entertainment_first",label:"Entertainment First - Pure entertainment with subtle brand integration"}],defaultValue:"viral_trending"},{key:"contentLength",label:"Content Length",type:"select",required:!0,helpText:"What video length should this TikTok ad target?",options:[{value:"short_snappy",label:"Short Snappy (15s) - Quick impact and immediate attention"},{value:"standard_engaging",label:"Standard Engaging (30s) - Balanced storytelling and engagement"},{value:"extended_story",label:"Extended Story (60s) - Detailed narrative and comprehensive messaging"},{value:"mini_series",label:"Mini Series (3min) - In-depth content and educational focus"}],defaultValue:"standard_engaging"},{key:"urgencyLevel",label:"Urgency Level",type:"select",required:!0,helpText:"What level of urgency should this TikTok campaign convey?",options:[{value:"no_urgency",label:"No Urgency - Casual discovery and brand awareness"},{value:"subtle_urgency",label:"Subtle Urgency - Gentle encouragement and social proof"},{value:"moderate_urgency",label:"Moderate Urgency - Clear call-to-action with incentives"},{value:"high_urgency",label:"High Urgency - Limited time offers and immediate action"},{value:"viral_urgency",label:"Viral Urgency - Trend participation and FOMO activation"}],defaultValue:"moderate_urgency"},{key:"engagementTrigger",label:"Engagement Trigger",type:"select",required:!0,helpText:"What engagement behaviors should trigger and optimize this campaign?",options:[{value:"click_through_rates",label:"Click Through Rates - High CTR user targeting and optimization"},{value:"video_completion",label:"Video Completion - Full video watch targeting and completion optimization"},{value:"share_velocity",label:"Share Velocity - Viral sharing behavior and amplification targeting"},{value:"comment_depth",label:"Comment Depth - Conversation engagement and reply thread participation"},{value:"like_engagement",label:"Like Engagement - Heart interaction patterns and positive engagement"},{value:"follow_conversion",label:"Follow Conversion - Profile follow behavior and audience growth targeting"}],defaultValue:"click_through_rates"},{key:"responseTimeWindow",label:"Response Time Window",type:"select",required:!0,helpText:"What optimal timing windows should this campaign target for maximum engagement?",options:[{value:"real_time_engagement",label:"Real Time Engagement - Immediate response and live interaction windows"},{value:"peak_activity_hours",label:"Peak Activity Hours - Prime TikTok usage and engagement periods"},{value:"viral_moment_windows",label:"Viral Moment Windows - Trending content and hashtag participation timing"},{value:"conversation_lifespan",label:"Conversation Lifespan - Comment thread and discussion engagement periods"},{value:"optimal_bidding_hours",label:"Optimal Bidding Hours - Cost-effective advertising and bidding windows"},{value:"audience_availability",label:"Audience Availability - Target demographic active usage periods"}],defaultValue:"peak_activity_hours"},{key:"amplificationStrategy",label:"Amplification Strategy",type:"select",required:!0,helpText:"What amplification methods should this campaign use to expand reach?",options:[{value:"organic_viral_boost",label:"Organic Viral Boost - Natural sharing and trending amplification"},{value:"paid_promotion_scaling",label:"Paid Promotion Scaling - Sponsored content and targeted promotion"},{value:"influencer_network",label:"Influencer Network - Creator partnerships and endorsement amplification"},{value:"lookalike_expansion",label:"Lookalike Expansion - Similar audience discovery and targeting growth"},{value:"hashtag_challenge",label:"Hashtag Challenge - Community participation and user-generated amplification"},{value:"cross_platform_boost",label:"Cross Platform Boost - Multi-platform promotion and audience synergy"}],defaultValue:"organic_viral_boost"},{key:"behavioralTargeting",label:"Behavioral Targeting",type:"select",required:!0,helpText:"What behavioral patterns should this campaign target for audience selection?",options:[{value:"interest_categories",label:"Interest Categories - Topic-based and content preference targeting"},{value:"engagement_history",label:"Engagement History - Past interaction patterns and behavior analysis"},{value:"content_consumption",label:"Content Consumption - Video watching habits and content preference patterns"},{value:"shopping_behavior",label:"Shopping Behavior - Purchase intent signals and e-commerce engagement"},{value:"social_interaction",label:"Social Interaction - Community participation and social engagement patterns"},{value:"trend_participation",label:"Trend Participation - Viral content engagement and hashtag challenge involvement"}],defaultValue:"interest_categories"},{key:"lifecycleStage",label:"Lifecycle Stage",type:"select",required:!0,helpText:"What customer journey stage should this campaign target for funnel optimization?",options:[{value:"awareness_discovery",label:"Awareness Discovery - Brand introduction and initial discovery campaigns"},{value:"consideration_engagement",label:"Consideration Engagement - Interest building and evaluation content"},{value:"conversion_activation",label:"Conversion Activation - Action-driving and purchase conversion campaigns"},{value:"retention_loyalty",label:"Retention Loyalty - Customer retention and repeat engagement campaigns"},{value:"expansion_upsell",label:"Expansion Upsell - Growth and premium feature promotion campaigns"},{value:"advocacy_referral",label:"Advocacy Referral - Brand advocacy and referral program campaigns"}],defaultValue:"awareness_discovery"},{key:"timeFromTrigger",label:"Time From Trigger",type:"select",required:!0,helpText:"What timing optimization should this campaign use for lifecycle progression?",options:[{value:"immediate_response",label:"Immediate Response - Real-time trigger and instant campaign activation"}
22,{value:"short_delay_hours",label:"Short Delay Hours - Hours-based timing and quick follow-up campaigns"},{value:"medium_delay_days",label:"Medium Delay Days - Days-based sequencing and nurture campaign timing"},{value:"long_delay_weeks",label:"Long Delay Weeks - Week-based intervals and extended lifecycle campaigns"},{value:"optimal_frequency",label:"Optimal Frequency - Frequency capping and anti-fatigue timing optimization"},{value:"lifecycle_milestone",label:"Lifecycle Milestone - Event-driven timing and milestone-based activation"}],defaultValue:"medium_delay_days"},{key:"riskLevel",label:"Risk Level",type:"select",required:!0,helpText:"What customer risk assessment should this campaign address for retention optimization?",options:[{value:"low_risk_stable",label:"Low Risk Stable - Engaged users with consistent activity and retention"},{value:"medium_risk_declining",label:"Medium Risk Declining - Moderate engagement drop and attention decline"},{value:"high_risk_churning",label:"High Risk Churning - Churn prediction and urgent retention intervention"},{value:"competitive_threat",label:"Competitive Threat - Competitive conquest defense and brand loyalty campaigns"},{value:"value_erosion",label:"Value Erosion - Declining customer value and re-engagement necessity"},{value:"dormant_reactivation",label:"Dormant Reactivation - Inactive user targeting and winback campaigns"}],defaultValue:"low_risk_stable"},{key:"expansionOpportunity",label:"Expansion Opportunity",type:"select",required:!0,helpText:"What growth opportunities should this campaign target for audience and revenue expansion?",options:[{value:"lookalike_scaling",label:"Lookalike Scaling - Similar audience discovery and targeting expansion"},{value:"cross_sell_upsell",label:"Cross Sell Upsell - Additional product promotion and revenue growth"},{value:"premium_upgrade",label:"Premium Upgrade - Feature upgrade campaigns and tier advancement"},{value:"referral_advocacy",label:"Referral Advocacy - Customer referral programs and brand advocacy campaigns"},{value:"geographic_expansion",label:"Geographic Expansion - New market targeting and location-based growth"},{value:"demographic_broadening",label:"Demographic Broadening - Audience diversification and market expansion"}],defaultValue:"lookalike_scaling"},{key:"timingTrigger",label:"Timing Trigger",type:"select",required:!0,helpText:"What timing triggers should activate and optimize this campaign for maximum impact?",options:[{value:"automated_bid_scheduling",label:"Automated Bid Scheduling - Time-based bid optimization and scheduling automation"},{value:"trend_based_activation",label:"Trend Based Activation - Trending topic triggers and viral moment campaign activation"},{value:"event_driven_launch",label:"Event Driven Launch - Cultural events, holidays, and special occasion campaign timing"},{value:"competitor_response",label:"Competitor Response - Competitive activity monitoring and counter-campaign triggers"},{value:"audience_activity_peaks",label:"Audience Activity Peaks - Peak engagement time targeting and activity-based activation"},{value:"viral_moment_capture",label:"Viral Moment Capture - Real-time trend participation and viral content timing"}],defaultValue:"trend_based_activation"},{key:"urgencyLevel",label:"Urgency Level",type:"select",required:!0,helpText:"What level of urgency should this TikTok campaign convey for time-sensitive marketing?",options:[{value:"no_urgency",label:"No Urgency - Casual discovery and brand awareness timing"},{value:"subtle_urgency",label:"Subtle Urgency - Gentle time-sensitive encouragement and soft deadlines"},{value:"moderate_urgency",label:"Moderate Urgency - Clear time-limited offers and moderate deadline pressure"},{value:"high_urgency",label:"High Urgency - Limited time offers and immediate action deadlines"},{value:"viral_urgency",label:"Viral Urgency - Trend participation timing and FOMO activation"},{value:"crisis_urgency",label:"Crisis Urgency - Emergency response timing and urgent message delivery"}],defaultValue:"moderate_urgency"},{key:"competitiveResponse",label:"Competitive Response",type:"select",required:!0,helpText:"What competitive response strategy should this campaign use for market positioning?",options:[{value:"defensive_positioning",label:"Defensive Positioning - Brand protection and competitive threat response"},{value:"aggressive_conquest",label:"Aggressive Conquest - Competitive keyword bidding and market attack campaigns"},{value:"counter_messaging",label:"Counter Messaging - Direct competitive response and differentiation messaging"},{value:"brand_defense",label:"Brand Defense - Reputation protection and competitive narrative control"},{value:"opportunity_capitalization",label:"Opportunity Capitalization - Competitor weakness exploitation and market gap targeting"},{value:"neutral_monitoring",label:"Neutral Monitoring - Competitive awareness without direct response action"}],defaultValue:"defensive_positioning"},{key:"trendAlignment",label:"Trend Alignment",type:"select",required:!0,helpText:"What trend alignment strategy should this campaign use for cultural relevance?",options:[{value:"hashtag_integration",label:"Hashtag Integration - Trending hashtag participation and viral topic alignment"},{value:"cultural_moment_targeting",label:"Cultural Moment Targeting - Cultural events, celebrations, and social movement alignment"},{value:"viral_content_amplification",label:"Viral Content Amplification - Trending content formats and viral video style adoption"},{value:"seasonal_trend_alignment",label:"Seasonal Trend Alignment - Seasonal content trends and holiday-specific messaging"},{value:"influencer_trend_following",label:"Influencer Trend Following - Creator trend adoption and influencer content mimicking"},{value:"platform_native_trends",label:"Platform Native Trends - TikTok-specific trends and platform culture alignment"}],defaultValue:"hashtag_integration"},{key:"personalityProfile",label:"Personality Profile",type:"select",required:!0,helpText:"What personality traits should this campaign target for psychological resonance?",options:[{value:"innovator_traits",label:"Innovator Traits - Early adopter behavior, tech enthusiasm, and innovation-seeking personality"},{value:"security_mindset",label:"Security Mindset - Risk-averse behavior, safety preferences, and stability-seeking personality"},{value:"status_driven",label:"Status Driven - Achievement-oriented behavior, prestige-seeking, and social validation personality"},{value:"value_conscious",label:"Value Conscious - Cost-effectiveness focus, deal-seeking behavior, and optimization personality"},{value:"community_oriented",label:"Community Oriented - Social connection focus, group participation, and collaboration personality"},{value:"achievement_focused",label:"Achievement Focused - Goal-oriented behavior, success-driven, and performance personality"}],defaultValue:"community_oriented"},{key:"valueAlignment",label:"Value Alignment",type:"select",required:!0,helpText:"What core values should this campaign align with for emotional connection?",options:[{value:"innovation_progress",label:"Innovation Progress - Technology advancement, future-focused values, and progressive ideologies"},{value:"security_stability",label:"Security Stability - Safety priorities, traditional values, and stability-focused beliefs"},{value:"success_achievement",label:"Success Achievement - Performance values, competitive spirit, and accomplishment-focused beliefs"},{value:"authenticity_transparency",label:"Authenticity Transparency - Genuine communication, honest values, and transparency-focused beliefs"},{value:"community_connection",label:"Community Connection - Social responsibility, collective values, and relationship-focused beliefs"},{value:"personal_growth",label:"Personal Growth - Self-improvement values, learning focus, and development-oriented beliefs"}],defaultValue:"authenticity_transparency"},{key:"decisionMakingStyle",label:"Decision Making Style",type:"select",required:!0,helpText:"What decision-making approach should this campaign target for conversion optimization?",options:[{value:"analytical_research",label:"Analytical Research - Data-driven decisions, research-based approach, and logical evaluation"},{value:"emotional_intuitive",label:"Emotional Intuitive - Feeling-based decisions, gut instinct approach, and emotional evaluation"},{value:"social_validation",label:"Social Validation - Peer-influenced decisions, community-based approach, and social proof evaluation"},{value:"expert_authority",label:"Expert Authority - Authority-influenced decisions, expert-based approach, and credibility evaluation"},{value:"quick_impulsive",label:"Quick Impulsive - Fast decisions, spontaneous approach, and immediate evaluation"},{value:"cautious_deliberate",label:"Cautious Deliberate - Careful decisions, thorough approach, and extended evaluation"}],defaultValue:"social_validation"},{key:"communicationPreference",label:"Communication Preference",type:"select",required:!0,helpText:"What communication style should this campaign use for audience engagement?",options:[{value:"direct_clear",label:"Direct
22Clear - Straightforward messaging, clear communication, and concise content style"},{value:"entertaining_fun",label:"Entertaining Fun - Humorous messaging, playful communication, and engaging content style"},{value:"educational_informative",label:"Educational Informative - Learning-focused messaging, instructional communication, and tutorial content style"},{value:"inspirational_motivational",label:"Inspirational Motivational - Uplifting messaging, encouraging communication, and aspirational content style"},{value:"personal_relatable",label:"Personal Relatable - Authentic messaging, personal communication, and human content style"},{value:"professional_credible",label:"Professional Credible - Authoritative messaging, expert communication, and trustworthy content style"}],defaultValue:"entertaining_fun"},{key:"marketPosition",label:"Market Position",type:"select",required:!0,helpText:"What market position should this campaign establish for competitive advantage?",options:[{value:"market_leader",label:"Market Leader - Dominant position defense, authority establishment, and market share protection"},{value:"challenger_brand",label:"Challenger Brand - Disruptive positioning, competitive attack strategies, and market disruption"},{value:"niche_specialist",label:"Niche Specialist - Specialized expertise, focused differentiation, and category leadership"},{value:"value_leader",label:"Value Leader - Cost advantage positioning, value proposition focus, and price competitiveness"},{value:"innovation_pioneer",label:"Innovation Pioneer - Technology leadership, first-mover advantage, and breakthrough positioning"},{value:"premium_brand",label:"Premium Brand - Quality superiority, luxury positioning, and premium value establishment"}],defaultValue:"challenger_brand"},{key:"competitiveThreat",label:"Competitive Threat",type:"select",required:!0,helpText:"What competitive threats should this campaign address for market protection?",options:[{value:"direct_competitor",label:"Direct Competitor - Same category rivals, feature comparison threats, and market share competition"},{value:"substitute_products",label:"Substitute Products - Alternative solutions, indirect competitors, and category disruption threats"},{value:"new_market_entrants",label:"New Market Entrants - Startup competitors, innovative challengers, and disruptive newcomers"},{value:"price_competition",label:"Price Competition - Cost-based rivals, pricing pressure threats, and value proposition challenges"},{value:"technology_disruption",label:"Technology Disruption - Tech innovation threats, platform shifts, and obsolescence risks"},{value:"brand_reputation",label:"Brand Reputation - Trust competitors, credibility threats, and reputation challenges"}],defaultValue:"direct_competitor"},{key:"differentiationStrategy",label:"Differentiation Strategy",type:"select",required:!0,helpText:"What differentiation approach should this campaign emphasize for competitive advantage?",options:[{value:"feature_superiority",label:"Feature Superiority - Product advantages, capability differences, and functional benefits"},{value:"quality_excellence",label:"Quality Excellence - Superior craftsmanship, reliability focus, and premium quality emphasis"},{value:"customer_experience",label:"Customer Experience - Service excellence, user experience superiority, and relationship advantages"},{value:"innovation_leadership",label:"Innovation Leadership - Technology advancement, creative solutions, and pioneering approaches"},{value:"brand_personality",label:"Brand Personality - Unique identity, cultural alignment, and emotional differentiation"},{value:"value_proposition",label:"Value Proposition - Cost-benefit advantages, ROI focus, and economic differentiation"}],defaultValue:"feature_superiority"},{key:"responseUrgency",label:"Response Urgency",type:"select",required:!0,helpText:"What urgency level should this competitive response campaign maintain?",options:[{value:"immediate_response",label:"Immediate Response - Crisis management, urgent counter-action, and emergency competitive defense"},{value:"rapid_deployment",label:"Rapid Deployment - Quick market response, fast competitive action, and accelerated campaign launch"},{value:"strategic_timing",label:"Strategic Timing - Planned competitive moves, calculated responses, and tactical timing"},{value:"proactive_prevention",label:"Proactive Prevention - Antici
22patory defense, preventive measures, and competitive preparation"},{value:"sustained_pressure",label:"Sustained Pressure - Long-term competitive effort, consistent messaging, and persistent positioning"},{value:"opportunistic_response",label:"Opportunistic Response - Market opportunity capture, competitive gap exploitation, and advantage timing"}],defaultValue:"strategic_timing"},{key:"adaptiveTrigger",label:"Adaptive Trigger",type:"select",required:!0,helpText:"What adaptive intelligence trigger should activate campaign optimization?",options:[{value:"performance_threshold",label:"Performance Threshold - Campaign metrics, conversion rates, and engagement performance triggers"},{value:"sentiment_shift",label:"Sentiment Shift - Audience sentiment changes, brand perception shifts, and emotional response triggers"},{value:"trend_emergence",label:"Trend Emergence - Viral content detection, hashtag momentum, and cultural trend triggers"},{value:"audience_behavior",label:"Audience Behavior - User interaction patterns, engagement behavior, and consumption habit triggers"},{value:"competitive_action",label:"Competitive Action - Competitor campaign changes, market shifts, and industry response triggers"},{value:"contextual_change",label:"Contextual Change - External events, news cycles, and environmental factor triggers"}],defaultValue:"performance_threshold"},{key:"learningSpeed",label:"Learning Speed",type:"select",required:!0,helpText:"What learning speed should the AI optimization system maintain?",options:[{value:"real_time",label:"Real Time - Instant optimization, immediate adaptation, and continuous learning cycles"},{value:"hourly_updates",label:"Hourly Updates - Hour-based learning, frequent optimization, and rapid adaptation cycles"},{value:"daily_learning",label:"Daily Learning - Daily optimization cycles, measured adaptation, and strategic learning"},{value:"weekly_analysis",label:"Weekly Analysis - Weekly learning patterns, comprehensive analysis, and periodic optimization"},{value:"campaign_lifecycle",label:"Campaign Lifecycle - Full campaign learning, end-to-end optimization, and complete cycle analysis"},{value:"seasonal_adaptation",label:"Seasonal Adaptation - Long-term pattern learning, seasonal optimization, and cyclical adaptation"}],defaultValue:"daily_learning"},{key:"personalizationDepth",label:"Personalization Depth",type:"select",required:!0,helpText:"What depth of personalization should this campaign achieve?",options:[{value:"basic_segmentation",label:"Basic Segmentation - Demographics, location, and basic interest targeting"},{value:"behavioral_patterns",label:"Behavioral Patterns - User actions, engagement history, and interaction preferences"},{value:"psychographic_profile",label:"Psychographic Profile - Personality traits, values, lifestyle, and psychological characteristics"},{value:"individual_optimization",label:"Individual Optimization - One-to-one personalization, unique user targeting, and custom content delivery"},{value:"predictive_personalization",label:"Predictive Personalization - Future behavior prediction, anticipatory content, and proactive targeting"},{value:"contextual_intelligence",label:"Contextual Intelligence - Situational awareness, environmental factors, and moment-based personalization"}],defaultValue:"behavioral_patterns"},{key:"predictiveModel",label:"Predictive Model",type:"select",required:!0,helpText:"What predictive modeling approach should guide campaign decisions?",options:[{value:"conversion_prediction",label:"Conversion Prediction - Purchase likelihood, conversion probability, and sales forecasting"},{value:"engagement_forecasting",label:"Engagement Forecasting - Interaction prediction, engagement probability, and content performance"},{value:"lifetime_value",label:"Lifetime Value - Customer value prediction, long-term worth forecasting, and retention modeling"},{value:"churn_prevention",label:"Churn Prevention - Customer retention prediction, attrition risk modeling, and loyalty forecasting"},{value:"viral_potential",label:"Viral Potential - Shareability prediction, viral content forecasting, and virality modeling"},{value:"sentiment_evolution",label:"Sentiment Evolution - Brand perception prediction, sentiment trajectory forecasting, and reputation modeling"}],defaultValue:"conversion_prediction"}],characterLimits:{headline:100,description:400,callToAction:20}}
22,{id:"generic_platform",name:"Generic Platform",fields:[...lt,{key:"headline",label:"Headline",type:"text",maxLength:150,helpText:"Main headline or title"},{key:"description",label:"Description",type:"textarea",maxLength:1e3,helpText:"Main content or description"},{key:"destinationUrl",label:"Destination URL",type:"text",maxLength:500,helpText:"Target URL for clicks"}],characterLimits:{headline:150,description:1e3,destinationUrl:500}}];function Pi(t){return Ai.find(n=>n.id===t)}const Li={facebook_ads:{configId:"facebook_ads",mockupId:"facebook_ads",displayName:"Facebook Ads"},facebook_posts:{configId:"facebook_ads",mockupId:"facebook_ads",displayName:"Facebook Posts"},facebook_page_post:{configId:"facebook_ads",mockupId:"facebook_ads",displayName:"Facebook Page Post"},facebook:{configId:"facebook_ads",mockupId:"facebook_ads",displayName:"Facebook"},google_ads:{configId:"google_search",mockupId:"google_search",displayName:"Google Ads"},google_search_ads:{configId:"google_search",mockupId:"google_search",displayName:"Google Search Ads"},google_search:{configId:"google_search",mockupId:"google_search",displayName:"Google Search"},instagram_ads:{configId:"facebook_ads",mockupId:"instagram_ads",displayName:"Instagram Ads"},instagram_posts:{configId:"facebook_ads",mockupId:"instagram_posts",displayName:"Instagram Posts"},instagram_post:{configId:"facebook_ads",mockupId:"instagram_posts",displayName:"Instagram Post"},instagram:{configId:"facebook_ads",mockupId:"instagram_ads",displayName:"Instagram"},email_marketing:{configId:"email_marketing",mockupId:"email",displayName:"Email Marketing"},email:{configId:"email_marketing",mockupId:"email",displayName:"Email"},sms:{configId:"sms",mockupId:"sms",displayName:"SMS"},text_message:{configId:"sms",mockupId:"sms",displayName:"Text Message"},linkedin_ads:{configId:"linkedin_ads",mockupId:"linkedin_ads",displayName:"LinkedIn Ads"},linkedin_posts:{configId:"linkedin_ads",mockupId:"linkedin_ads",displayName:"LinkedIn Posts"},linkedin:{configId:"linkedin_ads",mockupId:"linkedin_ads",displayName:"LinkedIn"},tiktok_ads:{configId:"tiktok_ads",mockupId:"tiktok_ads",displayName:"TikTok Ads"},tiktok:{configId:"tiktok_ads",mockupId:"tiktok",displayName:"TikTok"},blogs:{configId:"blogs",mockupId:"blog",displayName:"Blogs"},blog_posts:{configId:"blogs",mockupId:"blog",displayName:"Blog Posts"},blog:{configId:"blogs",mockupId:"blog",displayName:"Blog"},articles:{configId:"blogs",mockupId:"articles",displayName:"Articles"},content_marketing:{configId:"blogs",mockupId:"blog",displayName:"Content Marketing"},website:{configId:"generic_platform",mockupId:"blog",displayName:"Website"},landing_page:{configId:"generic_platform",mockupId:"blog",displayName:"Landing Page"},youtube_ads:{configId:"generic_platform",mockupId:"youtube_ads",displayName:"YouTube Ads"},youtube:{configId:"generic_platform",mockupId:"youtube",displayName:"YouTube"},video_ads:{configId:"generic_platform",mockupId:"youtube_ads",displayName:"Video Ads"},twitter_posts:{configId:"generic_platform",mockupId:"twitter_post",displayName:"Twitter Posts"},twitter_post:{configId:"generic_platform",mockupId:"twitter_post",displayName:"Twitter Post"},twitter_ads:{configId:"generic_platform",mockupId:"twitter_post",displayName:"Twitter Ads"},twitter:{configId:"generic_platform",mockupId:"twitter_post",displayName:"Twitter"},x_post:{configId:"generic_platform",mockupId:"twitter_post",displayName:"X Post"},pinterest:{configId:"generic_platform",mockupId:"pinterest",displayName:"Pinterest"},pinterest_ads:{configId:"generic_platform",mockupId:"pinterest_ads",displayName:"Pinterest Ads"},pinterest_pins:{configId:"generic_platform",mockupId:"pinterest",displayName:"Pinterest Pins"},snapchat_ads:{configId:"generic_platform",mockupId:"snapchat_ads",displayName:"Snapchat Ads"},snapchat:{configId:"generic_platform",mockupId:"snapchat",displayName:"Snapchat"},reddit_posts:{configId:"generic_platform",mockupId:"reddit",displayName:"Reddit Posts"},reddit:{configId:"generic_platform",mockupId:"reddit",displayName:"Reddit"},reddit_ads:{configId:"generic_platform",mockupId:"reddit",displayName:"Reddit Ads"},whatsapp_business:{configId:"generic_platform",mockupId:"whatsapp_business",displayName:"WhatsApp Business"},whatsapp:{configId:"generic_platform",mockupId:"whatsapp",displayName:"WhatsApp"},push_notifications:{configId:"generic_platform",mockupId:"push_notifications",displayName:"Push Notifications"},push:{configId:"generic_platform",mockupId:"push",displayName:"Push Notifications"},phone_calls:{configId:"generic_platform",mockupId:"phone_calls",displayName:"Phone Calls"},phone:{configId:"generic_platform",mockupId:"phone",displayName:"Phone"},voicemail:{configId:"generic_platform",mockupId:"voicemail",displayName:"Voicemail"},direct_mail:{configId:"generic_platform",mockupId:"direct_mail",displayName:"Direct Mail"}
22,postcards:{configId:"generic_platform",mockupId:"postcards",displayName:"Postcards"},letters:{configId:"generic_platform",mockupId:"letters",displayName:"Letters"},flyers_brochures:{configId:"generic_platform",mockupId:"flyers",displayName:"Flyers & Brochures"},flyers:{configId:"generic_platform",mockupId:"flyers",displayName:"Flyers"},print_ads:{configId:"generic_platform",mockupId:"print_ads",displayName:"Print Ads"},print:{configId:"generic_platform",mockupId:"print",displayName:"Print"},billboards:{configId:"generic_platform",mockupId:"billboards",displayName:"Billboards"},billboard:{configId:"generic_platform",mockupId:"billboard",displayName:"Billboard"},outdoor_advertising:{configId:"generic_platform",mockupId:"billboards",displayName:"Outdoor Advertising"},radio_ads:{configId:"generic_platform",mockupId:"radio_ads",displayName:"Radio Ads"},radio:{configId:"generic_platform",mockupId:"radio",displayName:"Radio"},radio_advertising:{configId:"generic_platform",mockupId:"radio_ads",displayName:"Radio Advertising"},tv_ads:{configId:"generic_platform",mockupId:"tv_commercials",displayName:"TV Ads"},tv_commercials:{configId:"generic_platform",mockupId:"tv_commercials",displayName:"TV Commercials"},tv_advertising:{configId:"generic_platform",mockupId:"tv_commercials",displayName:"TV Advertising"},trade_shows:{configId:"generic_platform",mockupId:"trade_shows",displayName:"Trade Shows"},webinars:{configId:"generic_platform",mockupId:"webinars",displayName:"Webinars"},webinar:{configId:"generic_platform",mockupId:"webinar",displayName:"Webinar"},affiliate_marketing:{configId:"generic_platform",mockupId:"affiliate_marketing",displayName:"Affiliate Marketing"},influencer_marketing:{configId:"generic_platform",mockupId:"instagram_posts",displayName:"Influencer Marketing"},podcast_advertising:{configId:"generic_platform",mockupId:"radio_ads",displayName:"Podcast Advertising"},seo:{configId:"blogs",mockupId:"blog",displayName:"SEO Content"}};function Ca(t){if(!t||t.trim()==="")return{configId:"generic_platform",mockupId:"blog",displayName:"Generic Platform"};const n=t.toLowerCase().trim(),c=Li[n];return c||(console.warn(`[Platform Normalization] Unknown platform: "${t}", using generic fallback`),{configId:"generic_platform",mockupId:"blog",displayName:t})}function Es(t){return Ca(t).configId}function Fs(t){return Ca(t).mockupId}function Mi(t){return Ca(t).displayName}function Di(t){return Es(t)!=="generic_platform"}const xa={tone:"copyTone",contentType:"contentStrategy",copyLength:"contentLength",callToAction:"callToActionType",toneStyle:"copyTone",contentApproach:"contentStrategy",urgency:"urgencyLevel",cta:"callToActionType",strategy:"contentStrategy"},ts={contentLength:{comprehensive:"detailed_explanation",concise:"ultra_concise",concise_action:"concise_action_focused",medium:"medium_context",detailed:"detailed_explanation",long_form:"long_form_story",solution_focused:"medium_context",personalized:"medium_context",benefit_heavy:"detailed_explanation",comparison_rich:"detailed_explanation"},callToActionType:{buy_now:"book_now",upgrade:"sign_up",shop_now:"visit_website",order_now:"book_now",subscribe:"sign_up","Get Free Consultation":"get_quote"},copyTone:{educational:"professional",informative:"professional",persuasive:"confident",empathetic:"friendly"},urgencyLevel:{mild:"moderate_urgency",none:"no_urgency",low:"gentle_nudge",medium:"moderate_urgency",high:"high_urgency",urgent:"immediate_action",immediate:"immediate_action"},contentStrategy:{solution_showcase:"benefit_focused",demonstrate:"benefit_focused",problem_agitation:"problem_awareness",educate:"solution_education",conversion:"conversion_optimized",retention:"retention_focused",credibility:"credibility_building"}},Ei={copyTone:"professional",contentLength:"medium_context",callToActionType:"learn_more",urgencyLevel:"moderate_urgency",contentStrategy:"benefit_focused",keywords:"",customInstructions:"",adObjective:"traffic",audienceTargeting:"detailed_targeting",placementStrategy:"automatic"};function fa(t){return t==null?!0:typeof t=="string"?t.trim()==="":!1}function ct(t){const n={},c=l=>{if(!(!t||typeof t!="object")){if(!fa(t[l]))return t[l];
22for(const[u,x]of Object.entries(xa))if(x===l&&!fa(t[u]))return t[u]}};for(const[l,u]of Object.entries(Ei)){const x=c(l);let b=fa(x)?u:typeof x=="string"?x.trim():x;typeof b=="string"&&ts[l]&&(b=ts[l][b]||b),n[l]=b}if(t&&typeof t=="object"){const l=Object.keys(xa);for(const[u,x]of Object.entries(t)){if(l.includes(u))continue;const b=xa[u]||u;if(!n.hasOwnProperty(b)&&x!==null&&x!==void 0){const S=typeof x=="string"?x.trim():x;n[b]=S}}}return n}const Fi={facebook:{platform:"Facebook",imageSpecs:{recommendedWidth:1200,recommendedHeight:630,aspectRatio:"1.91:1",maxFileSize:"8MB",formats:["JPG","PNG"],notes:"Feed images perform best at 1200x630. Square images (1:1) work well for carousel ads."},videoSpecs:{recommendedWidth:1280,recommendedHeight:720,aspectRatio:"16:9",maxDuration:240,maxFileSize:"4GB",formats:["MP4","MOV"],notes:"Vertical videos (9:16) perform well in Stories and Reels"},temperatureRecommendations:{cold:["Eye-catching hero images","Problem/solution visuals","Attention-grabbing graphics"],warm:["Behind-the-scenes photos","Team photos","Customer success stories"],hot:["Product demonstrations","Special offer graphics","Limited-time promotions"],existing:["Customer testimonials","Case study screenshots","Before/after comparisons"]}},instagram:{platform:"Instagram",imageSpecs:{recommendedWidth:1080,recommendedHeight:1080,aspectRatio:"1:1",maxFileSize:"8MB",formats:["JPG","PNG"],notes:"Square (1:1) for feed, vertical (4:5) for portraits, landscape (1.91:1) supported"},videoSpecs:{recommendedWidth:1080,recommendedHeight:1920,aspectRatio:"9:16",maxDuration:60,maxFileSize:"650MB",formats:["MP4","MOV"],notes:"Reels perform best at 9:16 vertical format"},temperatureRecommendations:{cold:["Lifestyle imagery","Aesthetic visuals","Brand mood shots"],warm:["User-generated content","Behind-the-scenes","Process videos"],hot:["Product showcases","Flash sale graphics","Countdown timers"],existing:["Customer photos","Reviews screenshots","Testimonial videos"]}},linkedin:{platform:"LinkedIn",imageSpecs:{recommendedWidth:1200,recommendedHeight:627,aspectRatio:"1.91:1",maxFileSize:"5MB",formats:["JPG","PNG"],notes:"Professional, high-quality images perform best"},videoSpecs:{recommendedWidth:1920,recommendedHeight:1080,aspectRatio:"16:9",maxDuration:600,maxFileSize:"5GB",formats:["MP4"],notes:"Native videos get 5x more engagement"},temperatureRecommendations:{cold:["Industry insights graphics","Professional headshots","Company achievements"],warm:["Team culture photos","Office environment","Employee spotlights"],hot:["Webinar announcements","Event invitations","Job postings"],existing:["Client success stories","Partnership announcements","Award recognitions"]}},twitter:{platform:"Twitter/X",imageSpecs:{recommendedWidth:1200,recommendedHeight:675,aspectRatio:"16:9",maxFileSize:"5MB",formats:["JPG","PNG","GIF"],notes:"Images with 2:1 aspect ratio display best in timeline"},videoSpecs:{recommendedWidth:1280,recommendedHeight:720,aspectRatio:"16:9",maxDuration:140,maxFileSize:"512MB",formats:["MP4"],notes:"Keep videos short and engaging for best performance"},temperatureRecommendations:{cold:["Infographics","Statistics visuals","Breaking news graphics"],warm:["Thread illustrations","Community highlights","Engagement posts"],hot:["Limited offers","Flash announcements","Real-time updates"],existing:["Customer feedback","Social proof","Success metrics"]}},youtube:{platform:"YouTube",imageSpecs:{recommendedWidth:1280,recommendedHeight:720,aspectRatio:"16:9",maxFileSize:"2MB",formats:["JPG","PNG"],notes:"Thumbnail images are crucial for click-through rates"},videoSpecs:{recommendedWidth:1920,recommendedHeight:1080,aspectRatio:"16:9",maxDuration:43200,maxFileSize:"128GB",formats:["MP4","MOV","AVI","WMV"],notes:"Higher resolution (4K) supported for premium quality"},temperatureRecommendations:{cold:["Eye-catching thumbnails","Title cards","Channel art"],warm:["Behind-the-scenes","Vlogs","Q&A sessions"],hot:["Product launches","Special announcements","Live streams"],existing:["Customer testimonials","Case studies","Success stories"]}},tiktok:{platform:"TikTok",imageSpecs:{recommendedWidth:1080,recommendedHeight:1920,aspectRatio:"9:16",maxFileSize:"5MB",formats:["JPG","PNG"],notes:"Cover images for videos should be vertical"},videoSpecs:{recommendedWidth:1080,recommendedHeight:1920,aspectRatio:"9:16",maxDuration:600,maxFileSize:"287.6MB",formats:["MP4","MOV"],notes:"Vertical videos only, 15-60 seconds perform best"},temperatureRecommendations:{cold:["Trending challenges","Educational content","Entertainment value"],warm:["Behind-the-scenes","Day-in-the-life","Team content"],hot:["Flash sales","Limited drops","Exclusive offers"],existing:["User testimonials","Product reviews","Transformation videos"]}},google_my_business:{platform:"Google My Business",imageSpecs:{recommendedWidth:1200,recommendedHeight:900,aspectRatio:"4:3",maxFileSize:"5MB",formats:["JPG","PNG"],notes:"High-quality photos of your business, products, and services"},videoSpecs:{recommendedWidth:1920,recommendedHeight:1080,aspectRatio:"16:9",maxDuration:30,maxFileSize:"75MB",formats:["MP4"],notes:"Short, informative videos about your business"},temperatureRecommendations:{cold:["Storefront photos","Product showcases","Service demonstrations"],warm:["Team photos","Interior views","Work in progress"],hot:["Special promotions","New arrivals","Event announcements"],existing:["Customer photos","Reviews with images","5-star testimonials"]}},email:{platform:"Email",imageSpecs:{recommendedWidth:600,recommendedHeight:400,aspectRatio:"3:2",maxFileSize:"1MB",formats:["JPG","PNG","GIF"],notes:"Keep images under 600px wide for mobile compatibility"},temperatureRecommendations:{cold:["Header graphics","Hero images","Infographics"],warm:["Product features","Team introductions","Newsletter graphics"],hot:["Sale banners","CTA buttons","Urgency graphics"],existing:["Customer stories","Case study images","Success metrics"]}}};function Bi(t,n){var b;const c=t.toLowerCase().replace(/-/g,"_"),l=Fi[c]||null;if(!l)return{specs:null,recommendations:["Use high-quality, relevant images","Ensure proper lighting and composition"]};const u=(n==null?void 0:n.toLowerCase())||"cold",x=((b=l.temperatureRecommendations)==null?void 0:b[u])||[];return{specs:l,recommendations:x}}function Ri(t){return{"1:1":"Square","16:9":"Landscape (Widescreen)","9:16":"Vertical (Portrait)","4:3":"Standard","3:2":"Classic","1.91:1":"Link Preview","2:1":"Wide Banner","4:5":"Portrait"}[t]||t}function zi({isOpen:t,onClose:n,onUpload:c,mediaType:l,serviceId:u}){const{activeCompanyId:x}
22=aa(),[b,S]=o.useState(""),[d,R]=o.useState(""),[G,O]=o.useState(""),[D,I]=o.useState("general"),Q=dt({mutationFn:async F=>(await Ae("/api/media-assets",{method:"POST",body:JSON.stringify({...F,businessProfileId:1,companyId:x,serviceId:u||void 0,tags:[]})})).json(),onSuccess:F=>{oa({title:"Media Uploaded",description:"Your media has been added to the library successfully."}),ln.invalidateQueries({predicate:q=>{const $=q.queryKey[0];return typeof $=="string"&&$.startsWith("/api/media-assets")}}),c(F.url),n()},onError:()=>{oa({title:"Upload Failed",description:"Failed to add media to library. Please try again.",variant:"destructive"})}}),T=()=>{if(!b||!d){oa({title:"Missing Information",description:"Please provide both URL and title for the media.",variant:"destructive"});return}const F=l==="all"?b.match(/\.(mp4|webm|mov|avi)$/i)?"video":"image":l;Q.mutate({url:b,title:d,description:G,type:F,category:D})};return e.jsx(vt,{open:t,onOpenChange:n,children:e.jsxs(bt,{className:"max-w-md",children:[e.jsxs(yt,{children:[e.jsx(jt,{children:"Add Media from URL"}),e.jsxs(wa,{children:["Add a new ",l==="all"?"image or video":l," to your media library"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ge,{htmlFor:"media-url",children:"Media URL"}),e.jsx(Pe,{id:"media-url",value:b,onChange:F=>S(F.target.value),placeholder:`https://example.com/media.${l==="video"?"mp4":"jpg"}`})]}),e.jsxs("div",{children:[e.jsx(ge,{htmlFor:"media-title",children:"Title"}),e.jsx(Pe,{id:"media-title",value:d,onChange:F=>R(F.target.value),placeholder:"Enter a descriptive title"})]}),e.jsxs("div",{children:[e.jsx(ge,{htmlFor:"media-description",children:"Description (Optional)"}),e.jsx(Pe,{id:"media-description",value:G,onChange:F=>O(F.target.value),placeholder:"Brief description of the media"})]}),e.jsxs("div",{children:[e.jsx(ge,{htmlFor:"media-category",children:"Category"}),e.jsxs(Ce,{value:D,onValueChange:F=>I(F),children:[e.jsx(Se,{id:"media-category",children:e.jsx(Ie,{})}),e.jsxs(Te,{children:[e.jsx(K,{value:"hero",children:"Hero Images"}),e.jsx(K,{value:"product",children:"Products & Services"}),e.jsx(K,{value:"testimonial",children:"Testimonials"}),e.jsx(K,{value:"team",children:"Team Photos"}),e.jsx(K,{value:"general",children:"General"})]})]})]})]}),e.jsxs(Ts,{children:[e.jsx(V,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(V,{onClick:T,disabled:Q.isPending,children:Q.isPending?"Uploading...":"Add to Library"})]})]})})}function ja({value:t,onChange:n,label:c,placeholder:l="Select media from library",mediaType:u="all",serviceId:x,platformType:b,temperature:S,className:d=""}){const{activeCompanyId:R}
22=aa(),[G,O]=o.useState(!1),[D,I]=o.useState(null),[Q,T]=o.useState(""),[F,q]=o.useState("all"),[$,ie]=o.useState(!1),{data:A=[],isLoading:J}=Ve({queryKey:[`/api/media-assets?${R?`companyId=${R}`:""}${x?`&serviceId=${x}`:""}`],enabled:!!R&&G}),m=A.filter(r=>{var y;return!(u!=="all"&&r.type!==u||F!=="all"&&r.category!==F||Q&&!r.title.toLowerCase().includes(Q.toLowerCase())&&!((y=r.description)!=null&&y.toLowerCase().includes(Q.toLowerCase())))});o.useEffect(()=>{if(t&&A.length>0){const r=A.find(y=>y.url===t);I(r||null)}},[t,A]);const _=r=>{I(r),n(r.url),O(!1)},p=()=>{I(null),n(void 0)},f=r=>{n(r),O(!1),ie(!1)};return e.jsxs("div",{className:d,children:[e.jsx(ge,{children:c}),e.jsx("div",{className:"mt-2",children:D?e.jsx(ae,{className:"p-4 relative",children:e.jsxs("div",{className:"flex items-center space-x-4",children:[D.type==="image"?e.jsx("div",{className:"w-20 h-20 rounded overflow-hidden bg-gray-100",children:e.jsx("img",{src:D.url,alt:D.title,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"w-20 h-20 rounded bg-gray-100 flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-gray-400"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:D.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.category})]}),e.jsx(V,{variant:"ghost",size:"icon",onClick:p,className:"absolute top-2 right-2",children:e.jsx(rn,{className:"h-4 w-4"})})]})}):e.jsxs(V,{variant:"outline",onClick:()=>O(!0),className:"w-full justify-start text-left",children:[u==="video"?e.jsx(ua,{className:"mr-2 h-4 w-4"}):e.jsx(Ka,{className:"mr-2 h-4 w-4"}),l]})}),e.jsx(vt,{open:G,onOpenChange:O,children:e.jsxs(bt,{className:"max-w-4xl max-h-[80vh]",children:[e.jsxs(yt,{children:[e.jsxs(jt,{children:["Select ",u==="all"?"Media":u]}),e.jsx(wa,{children:"Choose from your media library or upload new content"})]}),e.jsxs(Bt,{defaultValue:"library",className:"w-full",children:[e.jsxs(Rt,{className:"grid w-full grid-cols-2",children:[e.jsx(Re,{value:"library",children:"Media Library"}),e.jsx(Re,{value:"upload",children:"Add New"})]}),e.jsxs(Ye,{value:"library",className:"space-y-4",children:[b&&(()=>{const{specs:r,recommendations:y}=Bi(b,S),C=u==="video"?r==null?void 0:r.videoSpecs:r==null?void 0:r.imageSpecs;return!r||y.length===0?null:e.jsx("div",{className:"bg-orange-50 dark:bg-orange-950/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4 space-y-3",children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx(Je,{className:"h-5 w-5 text-orange-600 dark:text-orange-400 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("h4",{className:"font-medium text-sm text-orange-900 dark:text-orange-100",children:[r.platform," Recommendations"]}),C&&e.jsxs("div",{className:"text-sm text-orange-800 dark:text-orange-200 space-y-1",children:[e.jsxs("p",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:"Optimal size:"}),C.recommendedWidth,"x",C.recommendedHeight,"(",Ri(C.aspectRatio),")"]}),C.notes&&e.jsxs("p",{className:"flex items-start gap-2",children:[e.jsx(Qe,{className:"h-3 w-3 mt-0.5 flex-shrink-0"}),e.jsx("span",{className:"text-xs",children:C.notes})]})]}),y.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs font-medium text-orange-700 dark:text-orange-300 mb-1",children:["Suggested content for ",S||"cold"," audience:"]}),e.jsx("ul",{className:"text-xs text-orange-600 dark:text-orange-400 space-y-0.5",children:y.slice(0,3).map((k,M)=>e.jsxs("li",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-orange-400",children:"â¢"})," ",k]},M))})]})]})]})})})(),e.jsxs("div",{className:"flex space-x-2",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Is,{className:"absolute left-2 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Pe,{placeholder:"Search media...",value:Q,onChange:r=>T(r.target.value),className:"pl-8"})]}),e.jsxs(Ce,{value:F,onValueChange:q,children:[e.jsx(Se,{className:"w-[180px]",children:e.jsx(Ie,{placeholder:"All Categories"})}),e.jsxs(Te,{children:[e.jsx(K,{value:"all",children:"All Categories"}),e.jsx(K,{value:"hero",children:"Hero Images"}),e.jsx(K,{value:"product",children:"Products & Services"}),e.jsx(K,{value:"testimonial",children:"Testimonials"}),e.jsx(K,{value:"team",children:"Team Photos"}),e.jsx(K,{value:"general",children:"General"})]})]})]}),e.jsx(Ft,{className:"h-[400px]",children:J?e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[...Array(6)].map((r,y)=>e.jsx(xt,{className:"h-32 w-full"},y))}):m.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ka,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No media found"}),e.jsx("p",{className:"text-sm mt-2",children:"Try adjusting your filters or add new media"})]}):e.jsx("div",{className:"grid grid-cols-3 gap-4",children:m.map(r=>e.jsxs(ae,{className:"cursor-pointer hover:ring-2 hover:ring-primary transition-all",onClick:()=>_(r),children:[r.type==="image"?e.jsxs("div",{className:"aspect-video relative bg-gray-100",children:[e.jsx("img",{src:r.url,alt:r.title,className:"w-full h-full object-cover rounded-t"}),(D==null?void 0:D.id)===r.id&&e.jsx("div",{className:"absolute inset-0 bg-primary/20 flex items-center justify-center",children:e.jsx(Va,{className:"h-8 w-8 text-white"})})]}):e.jsxs("div",{className:"aspect-video relative bg-gray-100 flex items-center justify-center rounded-t",children:[e.jsx(ua,{className:"h-12 w-12 text-gray-400"}),(D==null?void 0:D.id)===r.id&&e.jsx("div",{className:"absolute inset-0 bg-primary/20 flex items-center justify-center",children:e.jsx(Va,{className:"h-8 w-8 text-white"})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:r.title}),e.jsx(z,{variant:"secondary",className:"text-xs mt-1",children:r.category})]})]},r.id))})})]}),e.jsx(Ye,{value:"upload",children:e.jsx("div",{className:"space-y-4 py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ya,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Add New Media"}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["Upload new ",u==="all"?"images or videos":u," to your media library"]}),e.jsxs(V,{onClick:()=>ie(!0),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),"Add from URL"]})]})})})]}),e.jsx(Ts,{children:e.jsx(V,{variant:"outline",onClick:()=>O(!1),children:"Cancel"})})]})}),e.jsx(zi,{isOpen:$,onClose:()=>ie(!1),onUpload:f,mediaType:u,serviceId:x})]})}function as({platformType:t,register:n,control:c,setValue:l,watch:u,errors:x={},className:b,campaignId:S,stepId:d,avatarData:R,offerData:G,businessProfile:O,serviceId:D,showOnlyConfiguration:I=!1,showOnlyContent:Q=!1,temperature:T,awarenessLevel:F,configuration:q,mockupComponent:$,previousStepsContent:ie}){const[A,J]=o.useState(!1),[m,_]=o.useState(new Set),[p,f]=o.useState(!1),[r,y]=o.useState("visual");o.useEffect(()=>{q&&typeof q=="object"&&(console.log("ð [PlatformContentForm] Syncing configuration to form state:",q),Object.entries(q).forEach(([s,h])=>{h!=null&&h!==""&&l(`configuration.${s}`,h)}))},[q,l]),o.useEffect(()=>{T&&(console.log("ð [PlatformContentForm] Syncing temperature to form state:",T),l("temperature",T))},[T,l]),o.useEffect(()=>{F&&(console.log("ð [PlatformContentForm] Syncing awarenessLevel to form state:",F),l("awarenessLevel",F))},[F,l]);const C=Es(t),k=!Di(t),M=Pi(C);if(!M)return console.error(`[PlatformContentForm] No config found for normalized ID: ${C}, original: ${t}`),e.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-900/20 rounded-lg",children:e.jsxs("p",{className:"text-red-600 dark:text-red-400 flex items-center gap-2",children:[e.jsx(mt,{className:"w-4 h-4"}),"Platform configuration error: Unable to load form"]})});const we=lt.map(s=>s.key),ze=M.fields.filter(s=>we.includes(s.key)),nt=M.fields.filter(s=>!we.includes(s.key)),tt=nt.filter(s=>(s.type==="text"||s.type==="textarea")&&s.maxLength),ut=M.characterLimits?Object.keys(M.characterLimits).map(s=>{const h=nt.find(te=>te.key===s);return h&&(h.type==="text"||h.type==="textarea")?{...h,maxLength:M.characterLimits[s]}:{key:s,label:s.charAt(0).toUpperCase()+s.slice(1).replace(/([A-Z])/g," $1"),type:M.characterLimits[s]>50?"textarea":"text",maxLength:M.characterLimits[s],required:!1,placeholder:`Enter ${s.toLowerCase()}...`}}):[],ce=[...tt,...ut.filter(s=>!tt.some(h=>h.key===s.key))],Oe=nt.filter(s=>!ce.some(h=>h.key===s.key)),Ee=async s=>{if(!(!S||!d)){_(h=>new Set([...h,s.key]));try{const h=await Ae(`/api/campaigns/v2/${S}/steps/${d}/generate-field`,{method:"POST",body:JSON.stringify({fieldKey:s.key,fieldType:s.type,maxLength:s.maxLength,platformType:t,existingContent:u(`platformContent.${s.key}`)||"",avatarData:R,offerData:G,businessProfile:O,platformConfig:ct(u("configuration")),temperature:T||u("temperature")||"warm",awarenessLevel:F||u("awarenessLevel")||"solution_aware",previousStepsContent:ie||[],linkedContentStepId:se||null,linkedContentVariantId:E||1})});h.success&&h.content&&l(`platformContent.${s.key}`,Lt(h.content))}catch(h){console.error("Failed to generate field content:",h)}finally{_(h=>{const te=new Set(h);return te.delete(s.key),te})}}},N=async()=>
22{if(!(!S||!d)){J(!0);try{const s=await Ae(`/api/campaigns/v2/${S}/steps/${d}/generate-all-fields`,{method:"POST",body:JSON.stringify({platformType:t,textFields:ce.map(h=>({key:h.key,type:h.type,maxLength:h.maxLength,label:h.label})),existingContent:u("platformContent")||{},avatarData:R,offerData:G,businessProfile:O,platformConfig:ct(u("configuration")),temperature:T||u("temperature")||"warm",awarenessLevel:F||u("awarenessLevel")||"solution_aware",linkedContentStepId:se||null,linkedContentVariantId:E||1})});s.success&&s.content&&Object.entries(s.content).forEach(([h,te])=>{l(`platformContent.${h}`,Lt(te))})}catch(s){console.error("Failed to generate all fields:",s)}finally{J(!1)}}},U=(s,h="platformContent")=>{var je,xe,$e,Fe,pt;const te=`${h}.${s.key}`,v=h==="configuration"?(je=x==null?void 0:x.configuration)==null?void 0:je[s.key]:(xe=x==null?void 0:x.platformContent)==null?void 0:xe[s.key],X=u(te)??"",H=($e=s.helpText)==null?void 0:$e.replace(/Facebook/g,t!=null&&t.includes("instagram")?"Instagram":"Facebook");switch(s.type){case"text":return e.jsxs("div",{className:"space-y-2",children:[!s.maxLength&&e.jsxs(ge,{htmlFor:s.key,children:[s.label,s.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(Pe,{id:s.key,...n(te,{required:s.required?`${s.label} is required`:!1,maxLength:s.maxLength?{value:s.maxLength,message:`Maximum ${s.maxLength} characters`}:void 0}),placeholder:s.placeholder||`Enter ${s.label.toLowerCase()}...`,maxLength:s.maxLength,className:ot(v&&"border-red-500")}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]}),v&&e.jsx("p",{className:"text-xs text-red-500",children:v.message})]},s.key);case"textarea":return e.jsxs("div",{className:"space-y-2",children:[!s.maxLength&&e.jsxs(ge,{htmlFor:s.key,children:[s.label,s.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(Na,{id:s.key,...n(te,{required:s.required?`${s.label} is required`:!1,maxLength:s.maxLength?{value:s.maxLength,message:`Maximum ${s.maxLength} characters`}:void 0}),placeholder:s.placeholder||`Enter ${s.label.toLowerCase()}...`,maxLength:s.maxLength,rows:s.maxLength&&s.maxLength>500?8:4,className:ot(v&&"border-red-500")}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]}),v&&e.jsx("p",{className:"text-xs text-red-500",children:v.message})]},s.key);case"select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ge,{htmlFor:s.key,children:[s.label,s.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsxs(Ce,{value:X||"",onValueChange:ee=>l(te,ee),children:[e.jsx(Se,{className:ot(v&&"border-red-500"),children:e.jsx(Ie,{placeholder:`Select ${s.label.toLowerCase()}`})}),e.jsx(Te,{children:(Fe=s.options)==null?void 0:Fe.map(ee=>e.jsx(K,{value:ee.value,children:ee.label},ee.value))})]}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]}),v&&e.jsx("p",{className:"text-xs text-red-500",children:v.message})]},s.key);case"multiselect":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ge,{children:[s.label,s.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-3 border rounded-md",children:(pt=s.options)==null?void 0:pt.map(ee=>{const fe=Array.isArray(X)&&X.includes(ee.value);return e.jsx(z,{variant:fe?"default":"outline",className:ot("cursor-pointer transition-all",fe&&"bg-orange-500 hover:bg-orange-600"),onClick:()=>{const at=Array.isArray(X)?X:[];fe?l(te,at.filter(Ue=>Ue!==ee.value)):l(te,[...at,ee.value])},children:ee.label},ee.value)})}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]})]},s.key);case"array":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ge,{htmlFor:s.key,children:[s.label,s.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsxs("div",{className:"space-y-2",children:[Array.isArray(X)&&X.map((ee,fe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Pe,{value:ee,onChange:at=>{const Ue=[...X];Ue[fe]=at.target.value,l(te,Ue)},placeholder:s.placeholder}),e.jsx("button",{type:"button",onClick:()=>{const at=X.filter((Ue,kt)=>kt!==fe);l(te,at)},className:"px-2 py-1 text-red-500 hover:bg-red-50 rounded",children:"Remove"})]},fe)),e.jsxs("button",{type:"button",onClick:()=>{const ee=Array.isArray(X)?X:[];l(te,[...ee,""])},className:"px-3 py-1 text-sm bg-orange-100 hover:bg-orange-200 text-orange-700 rounded",children:["Add ",s.label]})]}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]})]},s.key);case"image":return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ja,{value:X,onChange:ee=>l(te,ee),label:s.label+(s.required?" *":""),placeholder:"Select image from library...",mediaType:"image",platformType:t,serviceId:D,temperature:T}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]}),v&&e.jsx("p",{className:"text-xs text-red-500",children:v.message})]},s.key);case"video":return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ja,{value:X,onChange:ee=>l(te,ee),label:s.label+(s.required?" *":""),placeholder:"Select video from library...",mediaType:"video",platformType:t,serviceId:D,temperature:T}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Qe,{className:"w-3 h-3"}),H]}),v&&e.jsx("p",{className:"text-xs text-red-500",children:v.message})]},s.key);default:return null}},{data:oe}=Ve({queryKey:["/api/campaigns/v2",S,"steps"],enabled:!!S}),se=u("linkedContentStepId"),E=u("linkedContentVariantId"),P=u("platformContent.inheritedLinkedContentStepId"),Y=u("platformContent.inheritedLinkedContentVariantId");return e.jsxs("div",{className:ot("space-y-4",b),children:[k&&e.jsxs("div",{className:"bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Qe,{className:"w-5 h-5 text-amber-600 dar
22k:text-amber-400"}),e.jsx("h3",{className:"font-semibold text-amber-900 dark:text-amber-100",children:"Generic Content Editor"})]}),e.jsxs("p",{className:"text-sm text-amber-700 dark:text-amber-300",children:["This platform (",t,") uses a generic content editor with basic fields. Platform-specific features and best practices are available for supported platforms like Facebook Ads, Google Search, Email Marketing, LinkedIn Ads, TikTok Ads, Blogs, and SMS."]})]}),(I||!I&&!Q)&&e.jsxs(e.Fragment,{children:[!I&&e.jsxs("div",{className:"bg-gradient-to-r from-orange-50 to-orange-100 dark:from-orange-900/20 dark:to-orange-800/20 p-4 rounded-lg",children:[e.jsxs("h3",{className:"font-semibold text-lg mb-1",children:[Mi(t),k&&t&&t!=="generic_platform"&&e.jsxs("span",{className:"ml-2 text-sm font-normal text-muted-foreground",children:["(",t,")"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:M.description}),M.mediaSpecs&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[M.mediaSpecs.image&&e.jsxs(z,{variant:"secondary",className:"text-xs",children:["Images: ",M.mediaSpecs.image.formats.join(", ")," ⢠Max ",M.mediaSpecs.image.maxSize]}),M.mediaSpecs.video&&e.jsxs(z,{variant:"secondary",className:"text-xs",children:["Videos: ",M.mediaSpecs.video.formats.join(", ")," ⢠Max ",M.mediaSpecs.video.maxSize]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 border border-green-200 dark:border-green-800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Wt,{className:"w-5 h-5 text-green-600 dark:text-green-400"}),e.jsx("h3",{className:"font-semibold text-green-900 dark:text-green-100",children:"Ad Scent Linking"}),e.jsx(Dt,{className:"w-4 h-4 text-green-600 dark:text-green-400"})]}),e.jsx("p",{className:"text-sm text-green-700 dark:text-green-300 mb-4",children:"Link this content to another campaign step to maintain consistent messaging, tone, and CTAs for better conversion rates."}),P&&!se&&e.jsxs("div",{className:"mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Wt,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"font-medium text-blue-800 dark:text-blue-200",children:"Workflow Template Linking:"}),e.jsxs("span",{className:"text-blue-700 dark:text-blue-300",children:['Inherits ad scent from step "',P,'" (variant ',Y,")"]})]}),e.jsx(V,{type:"button",size:"sm",variant:"outline",className:"mt-2 text-blue-600 border-blue-300 hover:bg-blue-100",onClick:()=>{l("linkedContentStepId",P),l("linkedContentVariantId",Y)},children:"Apply Inherited Linking"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{htmlFor:"linkedContentStepId",className:"text-green-800 dark:text-green-200",children:"Link to Content Step"}),e.jsxs(Ce,{value:se||"none",onValueChange:s=>l("linkedContentStepId",s==="none"?void 0:s),children:[e.jsx(Se,{children:e.jsx(Ie,{placeholder:"Select destination content..."})}),e.jsxs(Te,{children:[e.jsx(K,{value:"none",children:"No linking"}),(()=>{const s=(oe==null?void 0:oe.filter(v=>v.stepId!==d))||[],h={cold:[],warm:[],hot:[],existing:[]};return s.forEach(v=>{const X=v.temperature||"warm";h[X]&&h[X].push(v)}),Object.keys(h).forEach(v=>{h[v].sort((X,H)=>{const je=X.platformType||"",xe=H.platformType||"";if(je!==xe)return je.localeCompare(xe);const $e=X.awarenessLevel||"",Fe=H.awarenessLevel||"";return $e.localeCompare(Fe)})}),[{key:"cold",label:"ð§ Cold Audience"},{key:"warm",label:"ð¤ï¸ Warm Audience"},{key:"hot",label:"ð¥ Hot Audience"},{key:"existing",label:"ð¥ Existing Customers"}].map(({key:v,label:X})=>{const H=h[v];return!H||H.length===0?null:e.jsxs(on,{children:[e.jsx(cn,{children:X}),H.map(je=>{let xe=je.stepId;const $e=je.stepId.split("_");if($e.length>=3){const Fe=$e.slice(0,2).join(" ").replace("_"," "),pt=$e.slice(2,-1).join(" ").replace(/_/g," ");xe=`${Fe} - ${pt}`}return je.versionName?xe+=` (${je.versionName})`:je.variantId&&je.variantId>1&&(xe+=` (Variant ${je.variantId})`),e.jsx(K,{value:je.stepId,children:xe},je.stepId)})]},v)})})()]})]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-400",children:"AI will match messaging and CTAs to this linked content"})]}),se&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{htmlFor:"linkedContentVariantId",className:"text-green-800 dark:text-green-200",children:"Content Variant"}),e.jsxs(Ce,{value:(E==null?void 0:E.toString())||"1",onValueChange:s=>l("linkedContentVariantId",parseInt(s)),children:[e.jsx(Se,{children:e.jsx(Ie,{placeholder:"Select variant..."})}),e.jsx(Te,{children:[1,2,3,4,5].map(s=>e.jsxs(K,{value:s.toString(),children:["Variant ",s]},s))})]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-400",children:"Specific version to match against"})]})]}),se&&e.jsx("div",{className:"mt-3 p-3 bg-green-100 dark:bg-green-900/30 rounded border border-green-200 dark:border-green-700",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Wt,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{className:"font-medium text-green-800 dark:text-green-200",children:"Ad Scent Active:"}),e.jsx("span",{className:"text-green-700 dark:text-green-300",children:"AI will ensure message consistency with linked content"})]})})]}),ze.length>0&&e.jsx(Kt,{open:p,onOpenChange:f,children:e.jsxs("div",{className:"bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-5 h-5 text-purple-600 dar
22k:text-purple-400"}),e.jsx("h3",{className:"font-medium text-purple-900 dark:text-purple-100",children:"Content Strategy Settings"})]}),e.jsx(Qt,{asChild:!0,children:e.jsxs(V,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:[e.jsx(Pt,{className:`h-4 w-4 transition-transform duration-200 ${p?"transform rotate-180":""}`}),e.jsx("span",{className:"sr-only",children:"Toggle content strategy settings"})]})})]}),!p&&e.jsx("p",{className:"text-xs text-purple-600 dark:text-purple-400",children:"Click to view and customize AI content generation settings"}),e.jsxs(Jt,{children:[e.jsx("p",{className:"text-sm text-purple-700 dark:text-purple-300 mb-4 mt-2",children:"These settings guide how AI generates your content. They're inherited from your workflow but can be customized for this step."}),e.jsx("div",{className:"space-y-4",children:ze.map(s=>U(s,"configuration"))})]})]})}),($||ce.length>0)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"}),e.jsx("span",{className:"font-medium text-blue-900 dark:text-blue-100",children:"AI Content Generation"})]}),e.jsx(V,{onClick:N,disabled:A||!S||!d,size:"sm",className:"bg-blue-600 hover:bg-blue-700 text-white","data-testid":"button-generate-all",children:A?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-4 h-4 mr-2"}),"Generate All"]})})]}),e.jsx("p",{className:"text-sm text-blue-700 dark:text-blue-300 mt-2",children:"Generate AI-powered content for all text fields based on your avatar, offer, and platform settings."})]}),e.jsxs(Bt,{value:r,onValueChange:s=>y(s),className:"w-full",children:[e.jsxs(Rt,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Re,{value:"visual",className:"flex items-center gap-2","data-testid":"tab-visual-preview",disabled:!$,children:[e.jsx(Gt,{className:"w-4 h-4"}),"Visual Preview"]}),e.jsxs(Re,{value:"form",className:"flex items-center gap-2","data-testid":"tab-form-fields",children:[e.jsx(Qa,{className:"w-4 h-4"}),"Form Fields"]})]}),e.jsx(Ye,{value:"visual",className:"mt-0",children:$?e.jsx("div",{className:"rounded-lg border bg-background p-4",children:$}):e.jsxs("div",{className:"rounded-lg border bg-gray-50 dark:bg-gray-800 p-8 text-center",children:[e.jsx(Gt,{className:"w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No visual preview available for this platform."}),e.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Use the Form Fields tab to edit content."})]})}),e.jsx(Ye,{value:"form",className:"mt-0 space-y-4",children:ce.length>0?e.jsx(e.Fragment,{children:ce.map(s=>{var h;return e.jsxs("div",{className:"bg-white dark:bg-gray-800 border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.label}),S&&d&&e.jsx(V,{onClick:()=>Ee(s),disabled:m.has(s.key),size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:text-blue-300 dark:hover:bg-blue-900/20","data-testid":`button-ai-suggest-${s.key}`,children:m.has(s.key)?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"w-3 h-3 mr-1 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kn,{className:"w-3 h-3 mr-1"}),"AI Suggest"]})})]}),e.jsxs(z,{variant:"outline",className:"text-xs",children:[((h=u(`platformContent.${s.key}`))==null?void 0:h.length)||0,"/",s.maxLength," chars"]})]}),U(s)]},s.key)})}):e.jsxs("div",{className:"rounded-lg border bg-gray-50 dark:bg-gray-800 p-8 text-center",children:[e.jsx(Qa,{className:"w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No form fields available for this platform."})]})})]})]}),Oe.length>0&&e.jsx("div",{className:"space-y-4",children:Oe.map(s=>U(s,"platformContent"))})]})]})}function Vi({value:t,onChange:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How would you like to create content?"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Choose how much AI assistance you want when building your campaign"})]}),e.jsxs(Qn,{value:t,onValueChange:n,className:"gap-4",children:[e.jsx(ae,{className:`p-4 cursor-pointer transition-all ${t==="blank"?"border-primary ring-2 ring-primary ring-offset-2":"hover:border-muted-foreground
22/50"}`,children:e.jsxs("label",{htmlFor:"blank",className:"flex gap-4 cursor-pointer",children:[e.jsx(ma,{value:"blank",id:"blank",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(dn,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("div",{className:"font-semibold",children:"Blank Canvas"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start with empty fields. I'll write my own content from scratch."}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"â Full creative control ⢠AI tools available if needed"})]})]})}),e.jsx(ae,{className:`p-4 cursor-pointer transition-all ${t==="suggestions"?"border-primary ring-2 ring-primary ring-offset-2":"hover:border-muted-foreground/50"}`,children:e.jsxs("label",{htmlFor:"suggestions",className:"flex gap-4 cursor-pointer",children:[e.jsx(ma,{value:"suggestions",id:"suggestions",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Je,{className:"h-5 w-5 text-orange-500"}),e.jsx("div",{className:"font-semibold",children:"AI Suggestions"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get short starter text for each field that I can refine and customize."}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"â Starting points for inspiration ⢠Easy to edit and improve"})]})]})}),e.jsx(ae,{className:`p-4 cursor-pointer transition-all ${t==="complete"?"border-primary ring-2 ring-primary ring-offset-2":"hover:border-muted-foreground/50"}`,children:e.jsxs("label",{htmlFor:"complete",className:"flex gap-4 cursor-pointer",children:[e.jsx(ma,{value:"complete",id:"complete",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ea,{className:"h-5 w-5 text-orange-500"}),e.jsx("div",{className:"font-semibold",children:"Complete Buildout"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate fully written content for all fields. I'll review and make final tweaks."}),e.jsx("div",{className:"mt-2 text-xs text-muted-foreground",children:"â Instant campaign ready ⢠Saves maximum time ⢠Refinement tools available"})]})]})})]})]})}const Ut={cold:"#3B82F6",warm:"#F59E0B",hot:"#EF4444",existing:"#10B981"},ss={facebook:"#1877F2",instagram:"#E4405F",google:"#4285F4",linkedin:"#0077B5",twitter:"#1DA1F2",email:"#EA4335",sms:"#25D366",youtube:"#FF0000",tiktok:"#000000",other:"#6B7280"};function Oi({campaign:t,workflowSteps:n,onBudgetUpdate:c,initialBudget:l=1500}){const{toast:u}
22=Et(),[x,b]=o.useState(l),[S,d]=o.useState([]),[R,G]=o.useState(!0),[O,D]=o.useState(!0),[I,Q]=o.useState(null),[T,F]=o.useState({cold:60,warm:25,hot:10,existing:5}),q=Oa.useMemo(()=>{const r=new Map;return S.forEach(y=>{const C=y.platform.toLowerCase(),k=r.get(C)||0;r.set(C,k+y.allocatedAmount)}),Array.from(r.entries()).map(([y,C])=>({channel:y,amount:C,percentage:x>0?C/x*100:0,color:ss[y]||ss.other}))},[S,x]),$=Oa.useMemo(()=>{const r=new Map;return S.forEach(y=>{const C=r.get(y.temperature)||0;r.set(y.temperature,C+y.allocatedAmount)}),Array.from(r.entries()).map(([y,C])=>({name:y.charAt(0).toUpperCase()+y.slice(1),value:C,percentage:x>0?C/x*100:0,color:Ut[y]}))},[S,x]);o.useEffect(()=>{n.length>0&&O&&ie()},[x,T,n,O]);const ie=()=>{const r=[],y=n.reduce((C,k)=>{const M=k.temperature||"warm";return C[M]||(C[M]=[]),C[M].push(k),C},{});Object.entries(y).forEach(([C,k])=>{const M=x*(T[C]||25)/100,we=k.length>0?M/k.length:0;k.forEach(ze=>{r.push({stepId:ze.id,platform:ze.platform||"other",temperature:C,allocatedAmount:Math.round(we*100)/100,percentage:x>0?we/x*100:0})})}),d(r)},A=(r,y)=>{d(C=>C.map(k=>k.stepId===r?{...k,allocatedAmount:y,percentage:y/x*100}:k)),D(!1)},J=()=>{const r=localStorage.getItem("adBudgetTemplate");if(r){const y=JSON.parse(r);Q(y),b(y.monthlyBudget||1500),y.tempAllocation&&F({cold:y.tempAllocation.cold||60,warm:y.tempAllocation.warm||25,hot:y.tempAllocation.hot||10,existing:5}),u({title:"Budget Template Loaded",description:"Applied saved budget allocation settings"})}else u({title:"No Template Found",description:"Create a template in the Budget Calculator first",variant:"destructive"})},m=()=>{c({totalBudget:x,tempAllocation:T,stepBudgets:S,channelAllocations:q,autoAllocate:O}),u({title:"Budget Saved",description:`Campaign budget of $${x} allocated across ${S.length} steps`})},_=S.reduce((r,y)=>r+y.allocatedAmount,0),p=x-_,f=Math.abs(p)<.01?"balanced":p>0?"under":"over";return e.jsxs(ae,{children:[e.jsxs(ye,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-orange-500"}),e.jsx(Ne,{children:"Campaign Budget & Allocation"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:f==="balanced"?"default":f==="under"?"secondary":"destructive",children:f==="balanced"?"Fully Allocated":f==="under"?`$${p.toFixed(2)} Remaining`:`$${Math.abs(p).toFixed(2)} Over`}),e.jsx(Qt,{asChild:!0,children:e.jsx(V,{variant:"ghost",size:"sm",onClick:()=>G(!R),children:R?e.jsx(Pt,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4"})})})]})]}),e.jsx(et,{children:"Manage budget allocation across platforms and temperature levels"})]}),e.jsx(Kt,{open:R,onOpenChange:G,children:e.jsx(Jt,{children:e.jsxs(me,{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(V,{variant:"outline",size:"sm",onClick:J,children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Load Template"]}),e.jsx(Yt,{href:"/budget-calculator",children:e.jsxs(V,{variant:"outline",size:"sm",children:[e.jsx(Wt,{className:"h-4 w-4 mr-2"}),"Open Calculator"]})}),e.jsx(Yt,{href:"/setup/strategy/digital-ad-budget",children:e.jsxs(V,{variant:"outline",size:"sm",children:[e.jsx(Yn,{className:"h-4 w-4 mr-2"}),"Temperature Calculator"]})})]}),e.jsxs("div",{children:[e.jsx(ge,{htmlFor:"total-budget",children:"Total Campaign Budget"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"$"}),e.jsx(Pe,{id:"total-budget",type:"number",value:x,onChange:r=>b(Number(r.target.value)),className:"max-w-[200px]"}),e.jsx(V,{variant:"outline",size:"sm",onClick:()=>D(!O),children:O?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-4 w-4 mr-2"}),"Auto"]}):e.jsxs(e.Fragment,{children:[e.jsx(ws,{className:"h-4 w-4 mr-2"}),"Manual"]})})]})]}),e.jsxs(Bt,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(Rt,{className:"grid w-full grid-cols-3",children:[e.jsx(Re,{value:"overview",children:"Overview"}),e.jsx(Re,{value:"channels",children:"By Channel"}),e.jsx(Re,{value:"steps",children:"By Step"})]}),e.jsxs(Ye,{value:"overview",className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ae,{children:[e.jsx(ye,{className:"pb-2",children:e.jsx(Ne,{className:"text-sm",children:"Temperature Allocation"})}),e.jsxs(me,{children:[e.jsx("div",{className:"h-[200px]",children:e.jsx(Zn,{width:"100%",height:"100%",children:e.jsxs(ti,{children:[e.jsx(ai,{data:$,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:70,label:({name:r,percentage:y})=>`${r}: ${y.toFixed(0)}%`,children:$.map((r,y)=>e.jsx(Xn,{fill:r.color},y))}),e.jsx(ei,{formatter:r=>`$${r.toFixed(2)}`})]})})}),O&&e.jsx("div",{className:"space-y-2 mt-4",children:Object.entries(T).map(([r,y])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Ut[r]}}),e.jsx("span",{className:"text-sm capitalize",children:r})]}),e.jsx(Pe,{type:"number",value:y,onChange:C=>F(k=>({...k,[r]:Number(C.target.value)})),className:"w-20 h-8 text-right",min:"0",max:"100"})]},r))})]})]}),e.jsxs(ae,{children:[e.jsx(ye,{className:"pb-2",children:e.jsx(Ne,{className:"text-sm",children:"Budget Metrics"})}),e.jsxs(me,{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Budget"}),e.jsxs("span",{className:"font-semibold",children:["$",x.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Allocated"}),e.jsxs("span",{className:"font-semibold",children:["$",_.toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Daily Spend"}),e.jsxs("span",{className:"font-semibold",children:["$",(x/30).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Steps Budgeted"}),e.jsxs("span",{className:"font-semibold",children:[S.length," / ",n.length]})]}),e.jsx(Jn,{value:_/x*100,className:"mt-2"})]})]})]}),I&&e.jsxs(pn,{children:[e.jsx(Qe,{className:"h-4 w-4"}),e.jsxs(gn,{children:["Using budget template: $",I.monthlyBudget," monthly budget with ",I.level1Posts||4," educational posts"]})]})]}),e.jsx(Ye,{value:"channels",className:"space-y-4",children:e.jsx("div",{className:"space-y-2",children:q.map(r=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-4 h-4 rounded",style:{backgroundColor:r.color}}),e.jsx("span",{className:"font-medium capitalize",children:r.channel}),e.jsxs(z,{variant:"outline",children:[r.percentage.toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:["$",r.amount.toFixed(2)]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Daily: $",(r.amount/30).toFixed(2)]})]})]},r.channel))})}),e.jsx(Ye,{value:"steps",className:"space-y-4",children:e.jsx("div",{className:"space-y-2",children:n.map((r,y)=>{const C=S.find(k=>k.stepId===r.id);return e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(z,{variant:"outline",children:["Step ",y+1]}),e.jsx("span",{className:"text-sm font-medium",children:r.name}),e.jsx(z,{variant:"secondary",style:{backgroundColor:`${Ut[r.temperature]}20`,color:Ut[r.temperature]},children:r.temperature})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"$"}),e.jsx(Pe,{type:"number",value:(C==null?void 0:C.allocatedAmount)||0,onChange:k=>A(r.id,Number(k.target.value)),className:"w-24 h-8",min:"0",step:"10"})]})]},r.id)})})})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(V,{onClick:m,children:[e.jsx(Ht,{className:"h-4 w-4 mr-2"}),"Save Budget Allocation"]})})]})})})]})}const qi=o.lazy(()=>le(()=>import("./facebook-ad-mockup-BkALhgJj.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(t=>({default:t.FacebookAdMockup}))),$i=o.lazy(()=>le(()=>import("./google-search-mockup-hmE1fEdb.js"),__vite__mapDeps([11,1,2])).then(t=>({default:t.GoogleSearchMockup}))),ns=o.lazy(()=>le(()=>import("./instagram-post-mockup-CF3rT3Dh.js"),__vite__mapDeps([12,1,2,7,6])).then(t=>({default:t.InstagramPostMockup}))),Ui=o.lazy(()=>le(()=>import("./email-mockup-BSO_UPGU.js"),__vite__mapDeps([13,1,2,14])).then(t=>({default:t.EmailMockup}))),Wi=o.lazy(()=>le(()=>import("./twitter-post-mockup-D12O4fKe.js"),__vite__mapDeps([15,1,2,6,8,7])).then(t=>({default:t.TwitterPostMockup}))),Hi=o.lazy(()=>le(()=>import("./linkedin-ads-mockup-Ha6n9rSC.js"),__vite__mapDeps([16,1,2,8])).then(t=>({default:t.LinkedInAdsMockup}))),Gi=o.lazy(()=>le(()=>import("./sms-mockup-CQXgyJDf.js"),__vite__mapDeps([17,1,2,18])).then(t=>({default:t.SMSMockup}))),is=o.lazy(()=>le(()=>import("./youtube-ads-mockup-C0bs0ojk.js"),__vite__mapDeps([19,1,2,10,20,21,8,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,4,6,38,39,40,41,42,43,44,45,46,47,48,49,50,51])).then(t=>({default:t.YouTubeAdsMockup}))),rs=o.lazy(()=>le(()=>import("./tiktok-ads-mockup-fKF5oGJ5.js"),__vite__mapDeps([52,1,2,10,8])).then(t=>({default:t.TikTokAdsMockup}))),ls=o.lazy(()=>le(()=>import("./pinterest-mockup-Dd1KKEiy.js"),__vite__mapDeps([53,1,2,4,6,7,9,10])).then(t=>({default:t.PinterestMockup}))),os=o.lazy(()=>le(()=>import("./snapchat-ads-mockup-D9LAur0e.js"),__vite__mapDeps([54,1,2,36,10,8])).then(t=>({default:t.SnapchatAdsMockup}))),Ki=o.lazy(()=>le(()=>import("./reddit-mockup-CZy9nM3R.js"),__vite__mapDeps([55,1,2,4,5,56,57,8,7])).then(t=>({default:t.RedditMockup}))),cs=o.lazy(()=>le(()=>import("./whatsapp-business-mockup-Bh0DAhVC.js"),__vite__mapDeps([58,1,2,5,22,18,59,60,20,61,9])).then(t=>({default:t.WhatsAppBusinessMockup}))),ds=o.lazy(()=>le(()=>import("./push-notifications-mockup-DW3DPxCU.js"),__vite__mapDeps([62,1,2,29,63,4,8,64,65])).then(t=>({default:t.PushNotificationsMockup}))),ms=o.lazy(()=>le(()=>import("./webinars-mockup-azpRsk5P.js"),__vite__mapDeps([66,1,2,29,27,5,10,61,8,67,31,30])).then(t=>({default:t.WebinarsMockup}))),us=o.lazy(()=>le(()=>import("./phone-calls-mockup-Cvjtc9zF.js"),__vite__mapDeps([68,1,2,29,69,61,20])).then(t=>({default:t.PhoneCallsMockup}))),Qi=o.lazy(()=>le(()=>import("./voicemail-mockup-CQr_yUQx.js"),__vite__mapDeps([70,1,2,29,27,71,72,10,20,73,69])).then(t=>({default:t.VoicemailMockup}))),ps=o.lazy(()=>le(()=>import("./postcards-mockup-CR5fL-xo.js"),__vite__mapDeps([74,1,2,14,75,76])).then(t=>({default:t.PostcardsMockup}))),Ji=o.lazy(()=>le(()=>import("./letters-mockup-D5t4vLdw.js"),__vite__mapDeps([77,1,2,76,78])).then(t=>({default:t.LettersMockup}))),gs=o.lazy(()=>le(()=>import("./print-ads-mockup-czZ_h_57.js"),__vite__mapDeps([79,1,2,80,76,4,75,81])).then(t=>({default:t.PrintAdsMockup}))),hs=o.lazy(()=>le(()=>import("./billboards-mockup-N86ZTu8h.js"),__vite__mapDeps([82,1,2,29,27,60])).then(t=>({default:t.BillboardsMockup}))),xs=o.lazy(()=>le(()=>
22import("./radio-ads-mockup-Dc4OXNQm.js"),__vite__mapDeps([83,1,2,29,63,84,64,72,10,20,61,23,24,25,26,27,28,30,31,32,33,34,35,36,37,4,6,38,39,40,41,42,43,44,45,46,47,48,49,50,51])).then(t=>({default:t.RadioAdsMockup}))),fs=o.lazy(()=>le(()=>import("./tv-commercials-mockup-BwhprIt8.js"),__vite__mapDeps([85,1,2,29,63,86,10,72,20,87,59,23,24,25,26,27,28,30,31,32,33,34,35,36,37,4,6,38,39,40,41,42,43,44,45,46,47,48,49,50,51])).then(t=>({default:t.TVCommercialsMockup}))),vs=o.lazy(()=>le(()=>import("./articles-mockup-ynvpJikh.js"),__vite__mapDeps([88,1,2,29,27,89,90,32,30,31,91,92,33,93,34,48,94,95,8,4,96])).then(t=>({default:t.ArticlesMockup}))),bs=o.lazy(()=>le(()=>import("./trade-shows-mockup-Dmgq-t6P.js"),__vite__mapDeps([97,1,2,29,63,98,59])).then(t=>({default:t.TradeShowsMockup}))),ys=o.lazy(()=>le(()=>import("./affiliate-marketing-mockup-BxSJAVAz.js"),__vite__mapDeps([99,1,2,29,100,87,101,98])).then(t=>({default:t.AffiliateMarketingMockup}))),js=o.lazy(()=>le(()=>import("./flyers-mockup-CZSVCdir.js"),__vite__mapDeps([102,1,2,75,76,4,56,57,81])).then(t=>({default:t.FlyersMockup}))),ka=o.lazy(()=>le(()=>import("./blog-mockup-DqSxzh4B.js"),__vite__mapDeps([103,1,2,3,4,5,6])).then(t=>({default:t.BlogMockup}))),Bs={facebook_ads:qi,google_search:$i,instagram_ads:ns,instagram_posts:ns,email:Ui,twitter_post:Wi,linkedin_ads:Hi,sms:Gi,youtube_ads:is,youtube:is,tiktok_ads:rs,tiktok:rs,pinterest:ls,pinterest_ads:ls,snapchat_ads:os,snapchat:os,reddit:Ki,whatsapp_business:cs,whatsapp:cs,push_notifications:ds,push:ds,webinars:ms,webinar:ms,phone_calls:us,phone:us,voicemail:Qi,postcards:ps,letters:Ji,direct_mail:ps,print_ads:gs,print:gs,billboards:hs,billboard:hs,radio_ads:xs,radio:xs,tv_commercials:fs,tv:fs,articles:vs,article:vs,blog:ka,blog_post:ka,trade_shows:bs,trade_show:bs,affiliate_marketing:ys,affiliate:ys,flyers:js,flyer:js};function ks(t){const n=Fs(t),c=Bs[n];return c||(console.warn(`[Platform Mockup] No mockup found for ID: ${n} (original: ${t}), using Blog fallback`),ka)}function Ns(t){const n=Fs(t);return Bs.hasOwnProperty(n)}function Yi(t){const{campaignId:n,avatarId:c,offerId:l,targetService:u,companyId:x,autoInitialize:b=!1}=t,{toast:S}
22=Et(),[d,R]=o.useState({sessionId:null,sessionStatus:"idle",contextVersion:0,expiresAt:null,stats:{totalMessages:0,totalTokensUsed:0,contextTokens:0,generatedFields:0}}),[G,O]=o.useState(!1),[D,I]=o.useState(null),Q=o.useCallback(async()=>{if(!n){console.log("âï¸ Skipping AI session init - no campaignId");return}R(A=>({...A,sessionStatus:"initializing"})),I(null);try{console.log("ð¤ Initializing AI session for campaign",n);const A=await Ae(`/api/campaigns/v2/${n}/ai-session/initialize`,{method:"POST",body:JSON.stringify({avatarId:c,offerId:l,targetService:u,companyId:x})});return R({sessionId:A.sessionId,sessionStatus:"active",contextVersion:A.contextVersion,expiresAt:new Date(A.expiresAt),stats:A.stats}),console.log("â
AI session initialized:",{sessionId:A.sessionId,contextVersion:A.contextVersion,expiresAt:A.expiresAt}),A.sessionId}catch(A){throw console.error("â Failed to initialize AI session:",A),R(J=>({...J,sessionStatus:"error"})),I(A.message||"Failed to initialize AI session"),A}},[n,c,l,u,x]),T=o.useCallback(async(A,J,m,_,p,f)=>{var y;let r=d.sessionId;if((!r||d.sessionStatus!=="active")&&(console.log("ð Session not active, initializing first..."),r=await Q(),!r))throw new Error("Failed to initialize session");O(!0),I(null);try{console.log(`ð¨ Generating ${J} for step ${A} using session ${r}`);const C=await Ae(`/api/campaigns/v2/${n}/ai-session/generate`,{method:"POST",body:JSON.stringify({sessionId:r,stepId:A,fieldKey:J,platformType:m,temperature:_,awarenessLevel:p,maxLength:f==null?void 0:f.maxLength,customInstructions:f==null?void 0:f.customInstructions})});return R(k=>({...k,stats:{...k.stats,totalMessages:k.stats.totalMessages+2,totalTokensUsed:k.stats.totalTokensUsed+C.tokensUsed,generatedFields:k.stats.generatedFields+1}})),console.log(`â
Generated ${J}:`,{content:C.content.substring(0,100)+"...",tokensUsed:C.tokensUsed,cached:C.cached}),C.content}catch(C){throw console.error(`â Failed to generate ${J}:`,C),I(C.message||"Failed to generate content"),(y=C.message)!=null&&y.includes("expired")&&(R(k=>({...k,sessionStatus:"expired"})),await Q()),C}finally{O(!1)}},[d.sessionId,d.sessionStatus,n,Q]),F=o.useCallback(async(A,J)=>{const m={};let _=0,p=0;A.forEach(r=>{_+=r.fields.length});let f=d.sessionId;if((!f||d.sessionStatus!=="active")&&(f=await Q(),!f))throw new Error("Failed to initialize session for bulk generation");for(const r of A){m[r.stepId]={};for(const y of r.fields){p++,J==null||J(p,_,`${r.platformType} - ${y.key}`);try{const C=await T(r.stepId,y.key,r.platformType,r.temperature,r.awarenessLevel,{maxLength:y.maxLength});m[r.stepId][y.key]=C,await new Promise(k=>setTimeout(k,500))}catch(C){console.error(`Failed to generate ${y.key} for step ${r.stepId}:`,C)}}}return m},[d.sessionId,d.sessionStatus,Q,T]),q=o.useCallback(async()=>{if(!d.sessionId||!n)return null;try{const A=await Ae(`/api/campaigns/v2/${n}/ai-session/status?sessionId=${d.sessionId}`);return R(J=>{var m;return{...J,stats:{totalMessages:A.messageCount||0,totalTokensUsed:((m=A.session)==null?void 0:m.totalTokensUsed)||0,contextTokens:A.contextTokens||0,generatedFields:A.generatedFields||0}}}),A}catch(A){return console.error("Failed to get session status:",A),null}},[d.sessionId,n]),$=o.useCallback(async(A=20)=>{if(!d.sessionId||!n)return[];try{return(await Ae(`/api/campaigns/v2/${n}/ai-session/history?sessionId=${d.sessionId}&limit=${A}`)).messages||[]}catch(J){return console.error("Failed to get session history:",J),[]}},[d.sessionId,n]),ie=o.useCallback(async()=>{if(!(!d.sessionId||!n))try{await Ae(`/api/campaigns/v2/${n}/ai-session/reset`,{method:"DELETE",body:JSON.stringify({sessionId:d.sessionId})}
22),R({sessionId:null,sessionStatus:"idle",contextVersion:0,expiresAt:null,stats:{totalMessages:0,totalTokensUsed:0,contextTokens:0,generatedFields:0}}),S({title:"Session Reset",description:"AI session has been reset. A new session will be created on next generation."})}catch(A){console.error("Failed to reset session:",A),S({title:"Error",description:"Failed to reset AI session",variant:"destructive"})}},[d.sessionId,n,S]);return o.useEffect(()=>{b&&n&&!d.sessionId&&Q()},[b,n,d.sessionId]),o.useEffect(()=>{if(!d.expiresAt)return;const A=()=>{new Date>d.expiresAt&&R(m=>({...m,sessionStatus:"expired"}))},J=setInterval(A,6e4);return A(),()=>clearInterval(J)},[d.expiresAt]),{sessionId:d.sessionId,sessionStatus:d.sessionStatus,contextVersion:d.contextVersion,expiresAt:d.expiresAt,stats:d.stats,isGenerating:G,lastError:D,initializeSession:Q,generateContent:T,generateBulkContent:F,getSessionStatus:q,getSessionHistory:$,resetSession:ie}}function Zi({sessionState:t,onReset:n,onViewHistory:c}){const[l,u]=o.useState(!1),[x,b]=o.useState([]),[S,d]=o.use
22State(!1),R=async()=>{if(c){d(!0);try{const I=await c();b(I),u(!0)}catch(I){console.error("Failed to load history:",I)}finally{d(!1)}}},G=()=>{switch(t.sessionStatus){case"active":return e.jsxs(z,{className:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:[e.jsx(ea,{className:"w-3 h-3 mr-1"}),"Active"]});case"initializing":return e.jsxs(z,{className:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:[e.jsx(Mt,{className:"w-3 h-3 mr-1 animate-spin"}),"Initializing"]});case"expired":return e.jsxs(z,{className:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",children:[e.jsx(ta,{className:"w-3 h-3 mr-1"}),"Expired"]});case"error":return e.jsxs(z,{className:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",children:[e.jsx(mt,{className:"w-3 h-3 mr-1"}),"Error"]});default:return e.jsxs(z,{variant:"outline",children:[e.jsx(ba,{className:"w-3 h-3 mr-1"}),"Idle"]})}},O=I=>I>1e6?`${(I/1e6).toFixed(1)}M`:I>1e3?`${(I/1e3).toFixed(1)}k`:I.toString(),D=()=>{if(!t.expiresAt)return"N/A";const I=new Date,T=new Date(t.expiresAt).getTime()-I.getTime();if(T<=0)return"Expired";const F=Math.floor(T/(1e3*60*60)),q=Math.floor(T%(1e3*60*60)/(1e3*60));return F>0?`${F}h ${q}m`:`${q}m`};return e.jsxs(ae,{className:"w-full",children:[e.jsx(ye,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ba,{className:"w-4 h-4 text-orange-500"}),"AI Session"]}),G()]})}),e.jsxs(me,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Messages"}),e.jsx("p",{className:"font-medium",children:t.stats.totalMessages})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Fields Generated"}),e.jsx("p",{className:"font-medium",children:t.stats.generatedFields})]}),e.jsx("div",{className:"space-y-1",children:e.jsx(hn,{children:e.jsxs(xn,{children:[e.jsx(fn,{asChild:!0,children:e.jsxs("div",{className:"cursor-help",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Tokens Used"}),e.jsx("p",{className:"font-medium",children:O(t.stats.totalTokensUsed)})]})}),e.jsxs(vn,{children:[e.jsxs("p",{children:["Total: ",t.stats.totalTokensUsed.toLocaleString()]}),e.jsxs("p",{children:["Context: ",t.stats.contextTokens.toLocaleString()]})]})]})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Expires In"}),e.jsx("p",{className:"font-medium",children:D()})]})]}),t.contextVersion>1&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-blue-50 dark:bg-blue-950 rounded-lg",children:[e.jsx(Mt,{className:"w-4 h-4 text-blue-600 dark:text-blue-400"}),e.jsxs("p",{className:"text-xs text-blue-700 dark:text-blue-300",children:["Context updated ",t.contextVersion-1," time",t.contextVersion>2?"s":""]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[c&&e.jsxs(vt,{open:l,onOpenChange:u,children:[e.jsx(bn,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",onClick:R,disabled:S||!t.sessionId,className:"flex-1",children:[e.jsx(yn,{className:"w-4 h-4 mr-1"}),"History"]})}),e.jsxs(bt,{className:"max-w-3xl max-h-[80vh]",children:[e.jsxs(yt,{children:[e.jsx(jt,{children:"AI Session History"}),e.jsx(wa,{children:"Conversation history for debugging and analysis"})]}),e.jsx(Ft,{className:"h-[500px] mt-4",children:e.jsx("div",{className:"space-y-4",children:x.map((I,Q)=>e.jsxs("div",{className:`p-3 rounded-lg ${I.role==="system"?"bg-gray-100 dark:bg-gray-800":I.role==="user"?"bg-blue-50 dark:bg-blue-950":"bg-green-50 dark:bg-green-950"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(z,{variant:"outline",className:"text-xs",children:I.role}),I.fieldKey&&e.jsxs("span",{className:"text-xs text-gray-500",children:[I.fieldKey," ⢠",I.temperature]})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap line-clamp-6",children:I.content}),I.totalTokens&&e.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Tokens: ",I.totalTokens," | Cost: $",I.estimatedCost||"0.00",I.
22cached&&" (cached)"]})]},Q))})})]})]}),n&&e.jsxs(V,{variant:"outline",size:"sm",onClick:n,disabled:!t.sessionId,className:"flex-1",children:[e.jsx(Mt,{className:"w-4 h-4 mr-1"}),"Reset"]})]})]})]})}function Xi({serviceId:t,selectedReviews:n,onReviewsChange:c,temperature:l="warm",maxSelections:u=5,className:x}){const{activeCompanyId:b}=aa(),[S,d]=o.useState(""),[R,G]=o.useState("all"),[O,D]=o.useState("all"),[I,Q]=o.useState("all"),{data:T,isLoading:F}=Ve({queryKey:["/api/reviews",b,t],enabled:!!b}),q=o.useMemo(()=>{if(!T)return[];let p=[...T];switch(t&&(p=p.filter(f=>f.serviceId===t)),l){case"cold":p=p.filter(f=>f.rating>=4&&f.sentiment==="positive").sort((f,r)=>{var k,M;const y=(f.isFeatured?2:0)+((k=f.photoUrls)!=null&&k.length?1:0)+f.rating;return(r.isFeatured?2:0)+((M=r.photoUrls)!=null&&M.length?1:0)+r.rating-y});break;case"warm":p=p.filter(f=>f.rating>=4&&f.content.length>100).sort((f,r)=>{var k,M;const y=f.content.length/100+f.rating+(((k=f.keywords)==null?void 0:k.length)||0);return r.content.length/100+r.rating+(((M=r.keywords)==null?void 0:M.length)||0)-y});break;case"hot":p=p.filter(f=>f.rating===5).sort((f,r)=>new Date(r.createdAt).getTime()-new Date(f.createdAt).getTime());break;case"existing":p=p.sort((f,r)=>new Date(r.createdAt).getTime()-new Date(f.createdAt).getTime());break}return p.slice(0,3)},[T,t,l]),$=o.useMemo(()=>{if(!T)return[];let p=[...T];if(t&&(p=p.filter(f=>f.serviceId===t)),S){const f=S.toLowerCase();p=p.filter(r=>{var y;return r.customerName.toLowerCase().includes(f)||r.content.toLowerCase().includes(f)||((y=r.serviceType)==null?void 0:y.toLowerCase().includes(f))})}if(R!=="all"){const f=parseInt(R);p=p.filter(r=>r.rating>=f)}return O!=="all"&&(p=p.filter(f=>f.platform===O)),I!=="all"&&(p=p.filter(f=>f.sentiment===I)),p},[T,t,S,R,O,I]),ie=p=>{n.includes(p)?c(n.filter(f=>f!==p)):n.length<u&&c([...n,p])},A=()=>{const p=q.map(r=>r.id),f=[...new Set([...n,...p])].slice(0,u);c(f)},J=()=>{switch(l){case"cold":return e.jsx(si,{className:"h-4 w-4 text-blue-500"});case"warm":return e.jsx(ri,{className:"h-4 w-4 text-yellow-500"});case"hot":return e.jsx(Ms,{className:"h-4 w-4 text-red-500"});case"existing":return e.jsx(jn,{className:"h-4 w-4 text-pink-500"})}},m=()=>{switch(l){case"cold":return"Cold Audience - Showcase best proof";case"warm":return"Warm Audience - Build trust with stories";case"hot":return"Hot Audience - Recent success highlights";case"existing":return"Existing Customers - Community feedback"}},_=p=>{const f=[];for(let r=1;r<=5;r++)r<=p?f.push(e.jsx(It,{className:"h-3 w-3 fill-yellow-400 text-yellow-400"},r)):f.push(e.jsx(It,{className:"h-3 w-3 text-gray-300"},r));return e.jsx("div",{className:"flex gap-0.5",children:f})};return e.jsxs(ae,{className:ot("",x),children:[e.jsx(ye,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ne,{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-5 w-5 text-yellow-500"}),"Customer Reviews"]}),e.jsxs(et,{className:"flex items-center gap-2 mt-1",children:[J(),m()]})]}),e.jsxs(z,{variant:"secondary",children:[n.length," / ",u," selected"]})]})}),e.jsxs(me,{className:"space-y-4",children:[q.length>0&&e.jsxs("div",{className:"p-3 bg-orange-50 dark:bg-orange-950 rounded-lg border border-orange-200 dark:border-orange-800",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-4 w-4 text-orange-600 dark:text-orange-400"}),e.jsxs("span",{className:"text-sm font-medium text-orange-900 dark:text-orange-100",children:["AI Recommended for ",l," audience"]})]}),e.jsx(V,{size:"sm",variant:"ghost",onClick:A,className:"text-xs",children:"Select All"})]}),e.jsx("div",{className:"space-y-2",children:q.slice(0,2).map(p=>e.jsxs("div",{className:"text-xs p-2 bg-white dark:bg-gray-900 rounded border border-orange-100 dark:border-orange-900",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"font-medium",children:p.customerName}),_(p.rating)]}),e.jsx("p",{className:"text-gray-600 dark:text-gray-400 line-clamp-2",children:p.content})]}
22,p.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Is,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"}),e.jsx(Pe,{placeholder:"Search reviews...",value:S,onChange:p=>d(p.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ce,{value:R,onValueChange:G,children:[e.jsx(Se,{className:"h-9",children:e.jsx(Ie,{placeholder:"Rating"})}),e.jsxs(Te,{children:[e.jsx(K,{value:"all",children:"All Ratings"}),e.jsx(K,{value:"5",children:"5 Stars"}),e.jsx(K,{value:"4",children:"4+ Stars"}),e.jsx(K,{value:"3",children:"3+ Stars"})]})]}),e.jsxs(Ce,{value:I,onValueChange:Q,children:[e.jsx(Se,{className:"h-9",children:e.jsx(Ie,{placeholder:"Sentiment"})}),e.jsxs(Te,{children:[e.jsx(K,{value:"all",children:"All Sentiments"}),e.jsx(K,{value:"positive",children:"Positive"}),e.jsx(K,{value:"neutral",children:"Neutral"}),e.jsx(K,{value:"negative",children:"Negative"})]})]})]})]}),e.jsx(Ft,{className:"h-[400px] pr-4",children:F?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(xt,{className:"h-24 w-full"},p))}):e.jsxs("div",{className:"space-y-3",children:[$.map(p=>e.jsx("div",{className:ot("p-3 rounded-lg border cursor-pointer transition-all",n.includes(p.id)?"bg-orange-50 dark:bg-orange-950 border-orange-300 dark:border-orange-700":"bg-white dark:bg-gray-900 border-gray-200 dark:border-gray-700 hover:border-orange-300 dark:hover:border-orange-700"),onClick:()=>ie(p.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(va,{checked:n.includes(p.id),onCheckedChange:()=>ie(p.id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:p.customerName}),p.isFeatured&&e.jsx(z,{variant:"secondary",className:"text-xs",children:"Featured"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[_(p.rating),e.jsx("span",{className:"text-xs text-gray-500",children:p.platform}),p.serviceType&&e.jsxs("span",{className:"text-xs text-gray-500",children:["⢠",p.serviceType]})]})]}),p.sentiment&&e.jsx(z,{variant:p.sentiment==="positive"?"default":p.sentiment==="neutral"?"secondary":"destructive",className:"text-xs",children:p.sentiment})]}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-3",children:p.content}),p.keywords&&p.keywords.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:p.keywords.slice(0,3).map((f,r)=>e.jsx(z,{variant:"outline",className:"text-xs",children:f},r))})]})]})},p.id)),$.length===0&&e.jsxs("div",{className:"text-center py-8 text-gray-500",children:[e.jsx(It,{className:"h-12 w-12 mx-auto mb-3 text-gray-300"}),e.jsx("p",{children:"No reviews found matching your criteria"})]})]})}),n.length>0&&e.jsx("div",{className:"pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:[n.length," review",n.length!==1?"s":""," selected for ",l," content"]}),e.jsx(V,{size:"sm",variant:"ghost",onClick:()=>c([]),className:"text-xs",children:"Clear All"})]})})]})]})}const er=be.object({name:be.string().min(1,"Campaign name is required"),description:be.string().optional(),offerId:be.string().min(1,"Offer is required"),avatarId:be.string().min(1,"Avatar is required"),workflowId:be.string().min(1,"Workflow is required"),serviceId:be.string().optional(),contentGenerationLevel:be.enum(["blank","suggestions","complete"]).default("blank"),deploymentStatus:be.string().default("draft")}),tr=be.object({platformContent:be.record(be.any()).default({}),destinationUrl:be.string().optional(),temperature:be.string().optional(),awarenessLevel:be.string().optional(),configuration:be.record(be.any()).optional(),mediaUrl:be.string().optional()}),St=t=>t?t.split("_").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "):"";function ar(){var Ba;
22const[t,n]=o.useState(null),[c,l]=o.useState(null),[u,x]=o.useState(!1),[b,S]=o.useState("disabled"),[d,R]=o.useState(null),[G,O]=o.useState(()=>!!!new URLSearchParams(window.location.search).get("id")),[D,I]=o.useState(!1),[Q,T]=o.useState([]),[F,q]=o.useState(()=>{const a=localStorage.getItem("campaignStepsViewMode");return a==="list"||a==="temperature"?a:"temperature"}),[$,ie]=o.useState(!1),[A,J]=o.useState(""),[m,_]=o.useState(!1),[p,f]=o.useState(null),[r,y]=o.useState({current:0,total:0}),[C,k]=o.useState(""),[M,we]=o.useState(!1),[ze,nt]=o.useState([]),[tt,ut]=o.useState(!1),{toast:ce}=Et(),Oe=Ss();kn();const{activeCompanyId:Ee,isLoading:N,isHydrated:U}=aa(),se=new URLSearchParams(window.location.search).get("id"),E=se?parseInt(se):null,P=!!E;console.log("ð [Campaign Builder] Mode:",{isEditMode:P,campaignId:E,windowSearch:window.location.search});const Y=qa({resolver:Wa(er),defaultValues:{name:"",description:"",offerId:"",avatarId:"",workflowId:"",contentGenerationLevel:"blank",deploymentStatus:"draft"}}),s=qa({resolver:Wa(tr),defaultValues:{platformContent:{},destinationUrl:"",temperature:"warm",awarenessLevel:"solution_aware",configuration:{},mediaUrl:""}}),{data:h,isLoading:te}=Ve({queryKey:["/api/campaigns",E],enabled:P&&!!E,staleTime:1e3*60*5}),v=P&&h&&h.companyId||Ee,X=v?`?companyId=${v}`:"";o.useEffect(()=>
22{console.log("ð¢ Campaign Builder Company Context:",{isEditMode:P,campaignId:h==null?void 0:h.id,campaignCompanyId:h==null?void 0:h.companyId,activeCompanyId:Ee,queryCompanyId:v,companyQueryParam:X,isHydrated:U,companyContextLoading:N})},[h,v,P,Ee,U,N]);const{data:H,isLoading:je}=Ve({queryKey:v?["/api/offers",{companyId:v}]:["/api/offers"],enabled:U&&!!v,staleTime:1e3*60*5,queryFn:v?async()=>{const a=await fetch(`/api/offers${X}`,{credentials:"include",headers:{"x-company-id":String(v)}});if(!a.ok)throw new Error(`Failed to fetch offers: ${a.status}`);return a.json()}:void 0}),{data:xe,isLoading:$e}=Ve({queryKey:v?["/api/avatars",{companyId:v}]:["/api/avatars"],enabled:U&&!!v,staleTime:1e3*60*5,queryFn:v?async()=>{const a=await fetch(`/api/avatars${X}`,{credentials:"include",headers:{"x-company-id":String(v)}});if(!a.ok)throw new Error(`Failed to fetch avatars: ${a.status}`);return a.json()}:void 0}),{data:Fe,isLoading:pt}=Ve({queryKey:v?["/api/workflows",{companyId:v}]:["/api/workflows"],enabled:U&&!!v,staleTime:1e3*60*5,queryFn:v?async()=>{const a=await fetch(`/api/workflows${X}`,{credentials:"include",headers:{"x-company-id":String(v)}});if(!a.ok)throw new Error(`Failed to fetch workflows: ${a.status}`);return a.json()}:void 0}),{data:ee}=Ve({queryKey:v?["/api/business-profile",{companyId:v}]:["/api/business-profile"],enabled:U&&!!v,staleTime:1e3*60*5,queryFn:v?async()=>{const a=await fetch(`/api/business-profile${X}`,{credentials:"include",headers:{"x-company-id":String(v)}});if(!a.ok)throw new Error(`Failed to fetch business profile: ${a.status}`);return a.json()}:void 0}),{data:fe,isLoading:at}=Ve({queryKey:v?["/api/business-services",{companyId:v}]:["/api/business-services"],enabled:U&&!!v,staleTime:1e3*60*5,queryFn:v?async()=>{const a=await fetch(`/api/business-services?companyId=${v}`,{credentials:"include",headers:{"x-company-id":String(v)}});if(!a.ok)throw new Error(`Failed to fetch business services: ${a.status}`);return a.json()}:void 0}),Ue=P&&h?h.workflowId:Y.watch("workflowId"),{data:kt}=Ve({queryKey:["/api/workflows",Ue],enabled:!!Ue,staleTime:1e3*60*5}),de=(kt==null?void 0:kt.steps)||[],Nt=P&&h?h.targetAvatarId:parseInt(Y.watch("avatarId")),st=P&&h?h.offerId:parseInt(Y.watch("offerId")),gt=P&&h?h.serviceId:parseInt(Y.watch("serviceId")),Ze=xe==null?void 0:xe.find(a=>a.id===Nt),zt=H==null?void 0:H.find(a=>a.id===st),ke=fe==null?void 0:fe.find(a=>a.id===gt),Vt=(ke==null?void 0:ke.name)||(ee==null?void 0:ee.services)&&Object.keys(ee.services)[0]||void 0,{sessionId:Sa,sessionStatus:Ia,contextVersion:Rs,expiresAt:zs,stats:Vs,isGenerating:sr,lastError:nr,initializeSession:Os,generateContent:ir,generateBulkContent:rr,getSessionStatus:lr,getSessionHistory:qs,resetSession:$s}=Yi({campaignId:E||void 0,avatarId:Nt||void 0,offerId:st||void 0,targetService:Vt||void 0,companyId:Ee||void 0,autoInitialize:!1}),{data:he}=Ve({queryKey:["/api/campaigns/v2",E,"steps"],enabled:P&&!!E,staleTime:1e3*60*5}),it=a=>{var w;if(!a)return{};const i=(w=a.content)==null?void 0:w.platformContent,g=a.platformContent;let j={};if(g)if(typeof g=="string")try{const L=JSON.parse(g);L&&typeof L=="object"&&(j={...L})}catch(L){console.warn("Failed to parse platformContent JSON string:",L)}else typeof g=="object"&&g!==null&&(j={...g});return i&&typeof i=="object"&&i!==null&&(j={...j,...i}),JSON.parse(JSON.stringify(j))},Us=/\b(Problem|Solution|Product|Most|Existing\s+Customer|Your\s+Solution)\s+(Unaware|Aware|Customers?|Discovery|Benefits?|Urgency|Retention)\b/i,sa=a=>{if(!a||typeof a!="string")return!0;const i=a.trim();return i===""?!0:Us.test(i)},rt=(a,i)=>{if(!i||!a)return a;const g=new Set([i.name,i.description,i.title,i.copy].filter(Boolean).map(w=>w.toLowerCase().trim()));if(g.size===0)return a;const j={};for(const[w,L]of Object.entries(a))typeof L=="string"&&g.has(L.toLowerCase().trim())?j[w]="":j[w]=L;return j},wt=a=>{if(!he||!P)return{filled:0,total:0,status:"empty"};const i=he.find(Z=>Z.stepId===a);if(!i)return console.log(`â ï¸ No campaign step found for stepId: ${a}`,{availableSteps:he.map(Z=>({id:Z.id,stepId:Z.stepId}))}),{filled:0,total:0,status:"empty"};const g=it(i),j=de==null?void 0:de.find(Z=>Z.id===a),w=j?rt(g,j):g,L=["headline","primaryText","callToAction","imageUrl","videoUrl","linkUrl","secondaryText"],W=L.filter(Z=>{const pe=w[Z];
22return pe==null?!1:typeof pe=="string"?pe.trim()!==""&&!sa(pe):!0}),re=W.length,ne=L.length;let B="empty";return re===0?B="empty":re<ne?B="partial":B="complete",console.log(`â Completion status for ${a}:`,{filled:re,total:ne,status:B,filledFields:W.map(Z=>w[Z])}),{filled:re,total:ne,status:B}},Ta=()=>{if(!he||!P||!de)return 0;let a=0;return de.forEach(i=>{const g=wt(i.id);a+=g.total-g.filled}),a},Ws=()=>{const a=F==="list"?"temperature":"list";q(a),localStorage.setItem("campaignStepsViewMode",a)},Hs=()=>{const a={hot:[],warm:[],cold:[],existing:[],unassigned:[]};return de.forEach(i=>{var j;const g=(j=i.temperature)==null?void 0:j.toLowerCase();g==="hot"?a.hot.push(i):g==="warm"?a.warm.push(i):g==="cold"?a.cold.push(i):g==="existing"?a.existing.push(i):a.unassigned.push(i)}),a},na=(a,i,g,j)=>e.jsx("div",{onClick:()=>ia(a),className:` 23 p-3 rounded-lg border cursor-pointer transition-all duration-200 24 hover:shadow-sm touch-manipulation 25 ${(t==null?void 0:t.id)===a.id?`border-blue-200 ${j} dark:border-blue-800`:"border-gray-200 dark:border-gray-700 hover:border-blue-200 dark:hover:border-blue-800"} 26 `,"data-testid":`workflow-step-${a.id}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 sm:w-6 sm:h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-xs font-medium text-blue-600 dark:text-blue-400",children:g+1})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium text-sm sm:text-base text-gray-900 dark:text-white truncate",children:a.name}),P&&e.jsx(z,{variant:i.status==="complete"?"default":i.status==="partial"?"secondary":"outline",className:`text-xs px-1.5 py-0.5 ${i.status==="complete"?"bg-green-100 text-green-700 border-green-300":i.status==="partial"?"bg-yellow-100 text-yellow-700 border-yellow-300":"bg-gray-100 text-gray-600 border-gray-300"}`,children:i.status==="empty"?"Empty":i.status==="complete"?"Complete":`${i.filled}/${i.total}`})]}),a.description&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate",children:a.description})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 sm:gap-2 flex-shrink-0",children:e.jsx(z,{variant:"outline",className:"text-xs px-1.5 py-0.5",children:St(a.platform)})})]})},a.id),Gs=()=>{if(!de||de.length===0)return"warm";const a={cold:0,warm:0,hot:0,existing:0};de.forEach(j=>{var L;const w=(L=j.temperature)==null?void 0:L.toLowerCase();w&&a[w]!==void 0&&a[w]++});let i="warm",g=0;return Object.entries(a).forEach(([j,w])=>{w>g&&(g=w,i=j)}),i},Ks=a=>{if(!a||!xe)return"";const i=xe.find(g=>g.id.toString()===a);return(i==null?void 0:i.name)||""},Qs=a=>{if(!a||!H)return"";const i=H.find(g=>g.id.toString()===a);return(i==null?void 0:i.title)||(i==null?void 0:i.name)||""},Js=a=>{if(!a||!Fe)return"";const i=Fe.find(g=>g.id.toString()===a);return(i==null?void 0:i.name)||""},Aa=o.useCallback((a,i,g)=>{const j=Ks(a),w=Qs(i),L=Js(g);return j&&w&&L?`${j} + ${w} + ${L}`:""},[xe,H,Fe]);o.useEffect(()=>{if(P)return;const a=Y.watch((i,{name:g,type:j})=>{const{avatarId:w,offerId:L,workflowId:W}=i;if(!(g==="name"&&j==="change"))if(w&&L&&W&&!$){const re=Aa(w,L,W);re&&re!==i.name&&(J(re),Y.setValue("name",re,{shouldDirty:!1,shouldTouch:!1}))}else!$&&(!w||!L||!W)&&i.name&&(Y.setValue("name","",{shouldDirty:!1,shouldTouch:!1}),J(""))});return()=>a.unsubscribe()},[Aa,$,P]),o.useEffect(()=>{var a,i,g,j;P&&h&&!te&&(console.log("ð Hydrating form with campaign data:",h),Y.reset({name:h.name||"",description:h.description||"",offerId:((a=h.offerId)==null?void 0:a.toString())||"",avatarId:((i=h.targetAvatarId)==null?void 0:i.toString())||"",workflowId:((g=h.workflowId)==null?void 0:g.toString())||"",serviceId:((j=h.serviceId)==null?void 0:j.toString())||"",deploymentStatus:h.deploymentStatus||"draft"}),ie(!0))},[h,te,P]),o.useEffect(()=>{if(!st||!(H!=null&&H.length)||!(fe!=null&&fe.length)||Y.getValues("serviceId"))return;const i=H.find(w=>w.id===st);if(!i)return;const g=(i.targetService||i.productService||"").toLowerCase().trim();if(!g||g==="general service")return;const j=fe.find(w=>w.name.toLowerCase()===g)||fe.find(w=>w.name.toLowerCase().includes(g)||g.includes(w.name.toLowerCase()));j&&Y.setValue("serviceId",j.id.toString(),{shouldDirty:!0})},[st,H,fe]),o.useEffect(()=>{E&&v&&Ia!=="initializing"&&(console.log("ð¤ Initializing/refreshing AI session for campaign:",{campaignId:E,avatarId:Nt,offerId:st,targetService:Vt,companyId:v}),Os({campaignId:E,avatarId:Nt||void 0,offerId:st||void 0,targetService:Vt||void 0}))},[E,v,Nt,st,Vt]);const Pa=a=>{if(!a||typeof a!="object")return{};const i={};for(const[g,j]of Object.entries(a))typeof j=="string"?i[g]=Lt(j):i[g]=j;return i},ia=a=>{var i,g;if(n(a),l("step"),P&&he&&he.length>0){const j=he.find(w=>w.stepId===a.id);if(j){const w=j.configuration||a.configuration||{},L=ct(w),W=((i=j.content)==null?void 0:i.platformContent)||j.platformContent||{},re=rt(Pa(W),a);s.reset({platformContent:re,destinationUrl:j.destinationUrl||"",temperature:j.temperature||a.temperature||"warm",awarenessLevel:j.awarenessLevel||a.awarenessLevel||"solution_aware",configuration:L,mediaUrl:((g=j.content)==null?void 0:g.mediaUrl)||j.mediaUrl||""}),console.log("ð Loaded step configuration:",{stepId:a.id,existingStepId:j.stepId,dbId:j.id,temperature:j.temperature||a.temperature,awarenessLevel:j.awarenessLevel||a.awarenessLevel,hasConfiguration:!!(j.
26configuration||a.configuration),normalizedFields:Object.keys(L),configValues:{copyTone:L.copyTone,contentLength:L.contentLength,callToActionType:L.callToActionType}})}else{const w=a.configuration||{},L=ct(w);s.reset({platformContent:{},destinationUrl:"",temperature:a.temperature||"warm",awarenessLevel:a.awarenessLevel||"solution_aware",configuration:L,mediaUrl:""})}}else{const j=a.configuration||{},w=ct(j);s.reset({platformContent:{},destinationUrl:"",temperature:a.temperature||"warm",awarenessLevel:a.awarenessLevel||"solution_aware",configuration:w,mediaUrl:""})}window.innerWidth<768&&x(!0)};o.useEffect(()=>{var re,ne;if(!t||!he||!P)return;const a=he.find(B=>B.stepId===t.id);if(!a)return;const i=((re=a.content)==null?void 0:re.platformContent)||a.platformContent||{},g=rt(i,t);if(!Object.entries(g).some(([,B])=>typeof B=="string"&&B.trim()!==""&&!sa(B)))return;const w=a.configuration||t.configuration||{},L=ct(w),W=rt(Pa(i),t);s.reset({platformContent:W,destinationUrl:a.destinationUrl||"",temperature:a.temperature||t.temperature||"warm",awarenessLevel:a.awarenessLevel||t.awarenessLevel||"solution_aware",configuration:L,mediaUrl:((ne=a.content)==null?void 0:ne.mediaUrl)||a.mediaUrl||""})},[he,t==null?void 0:t.id]);const La=()=>{n(null),l("scheduling"),S("active")},Ys=()=>{n(null),l("budget")},Zs=a=>{ce({title:"Campaign Scheduled",description:`Successfully scheduled ${a.length} pieces of content.`}),P&&E&&Oe.invalidateQueries({queryKey:["/api/campaigns",E]})},ra=dt({mutationFn:async a=>{const i={name:a.name,description:a.description,type:"marketing",offerId:parseInt(a.offerId),avatarId:parseInt(a.avatarId),workflowId:parseInt(a.workflowId),serviceId:a.serviceId?parseInt(a.serviceId):void 0,contentGenerationLevel:a.contentGenerationLevel,deploymentStatus:a.deploymentStatus,companyId:Ee};d&&(i.estimatedBudget=d.totalBudget,i.budgetAllocation=d);const g=Ee?`?companyId=${Ee}`:"";return(await Ae(`/api/campaigns/v2${g}`,{method:"POST",body:JSON.stringify(i)})).json()},onSuccess:a=>{ie(!1),J(""),Y.reset();const i=Y.getValues("contentGenerationLevel")||"blank";ce({title:"Campaign Created",description:i==="complete"?"Your campaign has been created with AI-generated content.":"Your campaign has been created successfully."}),window.location.href=`/campaign-builder?id=${a.id}`},onError:a=>{ce({title:"Error",description:a.message||"Failed to create campaign",variant:"destructive"})}}),la=dt({mutationFn:async a=>{const i={name:a.name,description:a.description,offerId:parseInt(a.offerId),targetAvatarId:parseInt(a.avatarId),workflowId:parseInt(a.workflowId),serviceId:a.serviceId?parseInt(a.serviceId):void 0};return d&&(i.estimatedBudget=d.totalBudget,i.budgetAllocation=d),Ae(`/api/campaigns/${E}`,{method:"PATCH",body:JSON.stringify(i)})},onSuccess:()=>{E&&Oe.invalidateQueries({queryKey:["/api/campaigns",E]}),ce({title:"Campaign Updated",description:"Your campaign has been updated successfully."})},onError:a=>{ce({title:"Error",description:a.message||"Failed to update campaign",variant:"destructive"})}}),_t=dt({mutationFn:async a=>{if(!E||!t)throw new Error("Campaign ID and step are required");return Ae(`/api/campaigns/v2/${E}/steps/${t.id}`,{method:"PATCH",body:JSON.stringify({content:a})})},onSuccess:()=>{E&&Oe.invalidateQueries({queryKey:["/api/campaigns/v2",E,"steps"]}),ce({title:"Content Saved",description:"Step content has been saved successfully."})},onError:a=>{ce({title:"Error",description:a.message||"Failed to save content",variant:"destructive"})}}),Xs=a=>{P?la.mutate(a):ra.mutate(a)},Ma=a=>{const i={...a,configuration:ct(a.configuration)};_t.mutate(i)},Da=o.useMemo(()=>{if(!t||!he||!Array.isArray(he))return[];const a=he.find(W=>W.stepId===t.id);if(!a)return[];const i={cold:1,warm:2,hot:3,existing:4},g=(a.temperature||t.temperature||"warm").toLowerCase(),j=i[g]||1,w=[...he].sort((W,re)=>{const ne=(W.temperature||"cold").toLowerCase(),B=(re.temperature||"cold").toLowerCase();return(i[ne]||1)-(i[B]||1)}),L=[];for(const W of w){if(W.stepId===t.id)continue;const re=(W.temperature||"cold").toLowerCase();if((i[re]||1)>=j)continue;const B=it(W);if(Object.keys(B).length===0)continue;const Z=de.find(pe=>pe.id===W.stepId);L.push({stepId:W.stepId,stepName:(Z==null?void 0:Z.name)||W.stepId,temperature:re,awarenessLevel:W.awarenessLevel||"",platform:(Z==null?void 0:Z.platform)||"",content:B})}return L},[t,he,de,it]),Ea=async()=>
26{if(!E||!t||!he){ce({title:"Error",description:"Campaign data not loaded",variant:"destructive"});return}const a=he.find(i=>i.stepId===t.id);if(!a){ce({title:"Error",description:"Step record not found in campaign",variant:"destructive"});return}try{we(!0);const i={cold:1,warm:2,hot:3,existing:4},g=(a.temperature||t.temperature||"warm").toLowerCase(),j=i[g]||1,w=[...he].sort((B,Z)=>{const pe=(B.temperature||"cold").toLowerCase(),Me=(Z.temperature||"cold").toLowerCase();return(i[pe]||1)-(i[Me]||1)}),L=[];for(const B of w){if(B.stepId===t.id)continue;const Z=(B.temperature||"cold").toLowerCase();if((i[Z]||1)>=j)continue;const Me=it(B);if(Object.keys(Me).length===0)continue;const ue=de.find(ve=>ve.id===B.stepId);L.push({stepId:B.stepId,stepName:(ue==null?void 0:ue.name)||B.stepId,temperature:Z,awarenessLevel:B.awarenessLevel||"",platform:(ue==null?void 0:ue.platform)||"",content:Me})}console.log(`ð Per-step regenerate: "${t.name}" with ${L.length} prior step(s) as context`);const W=rt(it(a),t),ne=await(await Ae(`/api/campaigns/v2/${E}/steps/${a.id}/generate-all-fields`,{method:"POST",body:JSON.stringify({platformType:t.platform,textFields:[{key:"headline",type:"headline",maxLength:100},{key:"primaryText",type:"primaryText",maxLength:300},{key:"callToAction",type:"callToAction",maxLength:30},{key:"secondaryText",type:"secondaryText",maxLength:200},{key:"description",type:"description",maxLength:500},{key:"subject",type:"subject",maxLength:80},{key:"preheader",type:"preheader",maxLength:100}],existingContent:W,avatarData:Ze,offerData:zt,businessProfile:ee,platformConfig:{},previousStepsContent:L})})).json();if(ne!=null&&ne.content&&typeof ne.content=="object")s.setValue("platformContent",ne.content),await Oe.invalidateQueries({queryKey:["/api/campaigns/v2",E,"steps"]}),ce({title:"Step Regenerated",description:L.length>
260?`Regenerated with context from ${L.length} prior step(s)`:"Regenerated with fresh context"});else throw new Error((ne==null?void 0:ne.error)||"Unexpected response from server")}catch(i){console.error("Error regenerating step:",i),ce({title:"Regeneration Failed",description:i.message||"Could not regenerate step content",variant:"destructive"})}finally{we(!1)}},Fa=async a=>{if(!E||!de||!he){ce({title:"Error",description:"Campaign data not loaded",variant:"destructive"});return}const i={cold:1,warm:2,hot:3,existing:4},g=[...de].sort((w,L)=>{const W=i[w.temperature||"cold"]||1,re=i[L.temperature||"cold"]||1;return W-re}),j=a?g.filter(w=>(w.temperature||"cold")===a):g;if(j.length===0){ce({title:"Nothing to generate",description:"No steps found for this audience."});return}try{_(!0),f(a),y({current:0,total:j.length}),k("");let w=0,L=0;const W=[];if(a){const ne=i[a]||1;for(const B of g){if((i[B.temperature||"cold"]||1)>=ne)break;const Z=he.find(ue=>ue.stepId===B.id);if(!Z)continue;const pe=rt(it(Z),B);Object.values(pe).some(ue=>typeof ue=="string"&&ue.trim()!==""&&!sa(ue))&&W.push({stepId:B.id,stepName:B.name,temperature:B.temperature||"cold",awarenessLevel:B.awarenessLevel||"",platform:B.platform||"",content:pe})}W.length>0&&console.log(`ð Pre-loaded ${W.length} colder step(s) as narrative context for ${a} generation`)}for(let ne=0;ne<j.length;ne++){const B=j[ne],Z=B.temperature||"cold",pe=B.awarenessLevel||B.awareness_level||"",Me=Z.charAt(0).toUpperCase()+Z.slice(1),ue=pe?pe.replace(/_/g," ").replace(/\b\w/g,_e=>_e.toUpperCase()):"",ve=B.platform?B.platform.replace(/_/g," ").replace(/\b\w/g,_e=>_e.toUpperCase()):"",Be=[Me,ue,ve].filter(Boolean).join(" â ");k(`${Be} (${ne+1}/${j.length})`),y({current:ne+1,total:j.length});try{const _e=he.find(tn=>tn.stepId===B.id);if(!_e){console.log(`âï¸ Skipping step ${B.name} â no campaign step found`);continue}const Ot=rt(it(_e),B),ht=await(await Ae(`/api/campaigns/v2/${E}/steps/${_e.id}/generate-all-fields`,{method:"POST",body:JSON.stringify({platformType:B.platform,textFields:[{key:"headline",type:"headline",maxLength:100},{key:"primaryText",type:"primaryText",maxLength:300},{key:"callToAction",type:"callToAction",maxLength:30},{key:"secondaryText",type:"secondaryText",maxLength:200},{key:"description",type:"description",maxLength:500},{key:"subject",type:"subject",maxLength:80},{key:"preheader",type:"preheader",maxLength:100}],existingContent:Ot,avatarData:Ze,offerData:zt,businessProfile:ee,platformConfig:{},previousStepsContent:W})})).json();ht!=null&&ht.content&&typeof ht.content=="object"&&(W.push({stepId:B.id,stepName:B.name,temperature:Z,awarenessLevel:pe,platform:B.platform||"",content:ht.content}),(t==null?void 0:t.id)===B.id&&s.setValue("platformContent",ht.content,{shouldDirty:!1})),w++,await Oe.refetchQueries({queryKey:["/api/campaigns/v2",E,"steps"]})}catch(_e){console.error(`Error generating content for step ${B.name}:`,_e),L++}}Oe.invalidateQueries({queryKey:["/api/campaigns",E]}),W.length>0&&(nt(ne=>{const B=new Map(ne.map(Z=>[Z.stepId,Z]));return W.forEach(Z=>B.set(Z.stepId,Z)),Array.from(B.values())}),ut(!0));const re=a?`${a.charAt(0).toUpperCase()+a.slice(1)} audience`:"all steps";ce({title:"Generation Complete",description:`Generated ${w} ${re} step${w!==1?"s":""}${L>0?`, ${L} failed`:""}`})}catch(w){console.error("Bulk generation error:",w),ce({title:"Error",description:"Failed to generate content",variant:"destructive"})}finally{_(!1),f(null),y({current:0,total:0}),k("")}},en=()=>Fa(null);return te?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx(De,{className:"h-8 w-8 animate-spin text-orange-500"})}):e.jsxs("div",{className:"min-h-screen bg-gray-100 dark:bg-gray-900 md:flex md:h-screen",children:[e.jsx("div",{className:"w-full md:w-1/2 bg-white dark:bg-gray-800 md:overflow-y-auto",children:e.jsxs("div",{className:"p-3 sm:p-6",children:[e.jsxs("div",{className:"mb-4 sm:mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 mb-3",children:[e.jsx(Nn,{className:"w-6 h-6 sm:w-8 sm:h-8 text-orange-500 flex-shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-lg sm:text-2xl font-bold text-gray-900 dark:text-white",children:P?"Edit Campaign":"Create Campaign"}),e.jsx("p",{className:"text-xs sm:text-sm text-gray-600 dark:text-gray-400",children:P?"Upd
26ate your campaign details and workflow steps":"Build a new multi-step marketing campaign"}),P&&h&&v&&ee&&e.jsx("div",{className:"mt-2",children:e.jsxs(z,{variant:"outline",className:"text-xs bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800",children:[e.jsx(wn,{className:"h-3 w-3 mr-1"}),"Editing: ",ee.businessName||`Company ${v}`]})})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 mt-3 sm:mt-4 sm:justify-between",children:[e.jsx(Yt,{href:"/campaigns",children:e.jsx(V,{variant:"ghost",className:"w-full sm:w-auto h-9 sm:h-8 text-sm","data-testid":"button-back-to-library",children:"â Back to Library"})}),e.jsx(Yt,{href:"/campaign-guide-introduction",children:e.jsxs(V,{variant:"outline",className:"w-full sm:w-auto border-blue-200 text-blue-700 hover:bg-blue-50 h-9 sm:h-8 text-sm","data-testid":"button-campaign-guide",children:[e.jsx(_n,{className:"w-4 h-4 mr-2"}),"Guide"]})})]})]}),E&&Sa&&e.jsx("div",{className:"mb-4",children:e.jsx(Zi,{sessionState:{sessionId:Sa,sessionStatus:Ia,contextVersion:Rs,expiresAt:zs,stats:Vs},onReset:$s,onViewHistory:()=>qs(20)})}),e.jsx(Kt,{open:G,onOpenChange:O,children:e.jsxs(ae,{className:"mb-4 sm:mb-6",children:[e.jsx(ye,{className:"pb-3 sm:pb-6",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ne,{className:"text-base sm:text-lg",children:"Campaign Details"}),!G&&P&&h&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-1",children:h.name}),h.description&&e.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2",children:h.description}),e.jsx(z,{variant:h.deploymentStatus==="live"?"default":h.deploymentStatus==="draft"?"secondary":"outline",className:"text-xs mt-1",children:h.deploymentStatus.charAt(0).toUpperCase()+h.deploymentStatus.slice(1)})]}),!G&&!P&&e.jsx(et,{className:"text-sm",children:P?"Update the core details of your campaign":"Configure the core details of your campaign"})]}),e.jsx(Qt,{asChild:!0,children:e.jsxs(V,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:[e.jsx(Pt,{className:`h-4 w-4 transition-transform duration-200 ${G?"transform rotate-180":""}`}),e.jsx("span",{className:"sr-only",children:"Toggle campaign details"})]})})]})}),e.jsx(Jt,{children:e.jsx(me,{className:"pt-0",children:e.jsx(ca,{...Y,children:e.jsxs("form",{onSubmit:Y.handleSubmit(Xs),className:"space-y-4",children:[e.jsx(We,{control:Y.control,name:"avatarId",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Target Avatar"}),$e||P&&te?e.jsx(xt,{className:"h-11 w-full"}):e.jsxs(Ce,{onValueChange:a.onChange,value:a.value,children:[e.jsx(Ge,{children:e.jsx(Se,{className:"h-11","data-testid":"select-campaign-avatar",children:e.jsx(Ie,{placeholder:"Select target avatar"})})}),e.jsx(Te,{children:xe==null?void 0:xe.map(i=>e.jsx(K,{value:i.id.toString(),children:i.name},i.id))})]}),e.jsx(Ke,{})]})}),e.jsx(We,{control:Y.control,name:"offerId",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Offer"}),je||P&&te?e.jsx(xt,{className:"h-11 w-full"}):e.jsxs(Ce,{onValueChange:a.onChange,value:a.value,children:[e.jsx(Ge,{children:e.jsx(Se,{className:"h-11","data-testid":"select-campaign-offer",children:e.jsx(Ie,{placeholder:"Select an offer"})})}),e.jsx(Te,{children:H==null?void 0:H.map(i=>e.jsx(K,{value:i.id.toString(),children:i.title||i.name},i.id))})]}),e.jsx(Ke,{})]})}),e.jsx(We,{control:Y.control,name:"serviceId",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Target Service"}),e.jsx(Cn,{className:"text-xs mb-2",children:"Select the specific service you're promoting in this campaign"}),at||P&&te?e.jsx(xt,{className:"h-11 w-full"}):e.jsxs(Ce,{onValueChange:a.onChange,value:a.value,children:[e.jsx(Ge,{children:e.jsx(Se,{className:"h-11","data-testid":"select-campaign-service",children:e.jsx(Ie,{placeholder:"Select service to promote"})})}),e.jsx(Te,{children:fe==null?void 0:fe.map(i=>e.jsx(K,{value:i.id.toString(),children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:i.name}),i.category&&e.jsx("span",{className:"text-xs text-gray-500",children:i.category})]})},i.id))})]}),e.jsx(Ke,{})]})}),ke&&e.jsx(ae,{className:"bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800",children:e.jsx(me,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm text-orange-900 dark:text-orange-100",children:ke.name}),ke.category&&e.jsx("p",{className:"text-xs text-orange-700 dark:text-orange-300 mt-1",children:ke.category})]}
26),e.jsx(z,{variant:"secondary",className:"bg-orange-100 dark:bg-orange-900 text-orange-900 dark:text-orange-100",children:"Target Service"})]}),ke.benefits&&ke.benefits.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-orange-800 dark:text-orange-200 mb-1",children:"Key Benefits:"}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[ke.benefits.slice(0,3).map((a,i)=>e.jsx(z,{variant:"outline",className:"text-xs bg-white dark:bg-gray-900 border-orange-300 dark:border-orange-700",children:a},i)),ke.benefits.length>3&&e.jsxs(z,{variant:"outline",className:"text-xs bg-white dark:bg-gray-900 border-orange-300 dark:border-orange-700",children:["+",ke.benefits.length-3," more"]})]})]}),ke.solutions&&ke.solutions.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-orange-800 dark:text-orange-200 mb-1",children:"Solutions:"}),e.jsx("ul",{className:"text-xs text-orange-700 dark:text-orange-300 space-y-0.5",children:ke.solutions.slice(0,2).map((a,i)=>e.jsxs("li",{className:"flex items-start",children:[e.jsx("span",{className:"mr-1",children:"â¢"}),e.jsx("span",{className:"line-clamp-1",children:a})]},i))})]}),Ze&&ke&&e.jsx("div",{className:"pt-2 border-t border-orange-200 dark:border-orange-800",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-3 w-3 text-orange-600 dark:text-orange-400"}),e.jsxs("p",{className:"text-xs text-orange-700 dark:text-orange-300",children:["Targeting: ",e.jsx("span",{className:"font-medium",children:Ze.name}),Ze.painPoint&&((Ba=ke.solutions)==null?void 0:Ba.some(a=>a.toLowerCase().includes(Ze.painPoint.toLowerCase())||Ze.painPoint.toLowerCase().includes(a.toLowerCase())))&&e.jsxs(z,{className:"ml-2 text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200",children:[e.jsx(Ls,{className:"h-3 w-3 mr-1"}),"Good fit"]})]})]})})]})})}),e.jsx(We,{control:Y.control,name:"workflowId",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Workflow"}),pt||P&&te?e.jsx(xt,{className:"h-11 w-full"}):e.jsxs(Ce,{onValueChange:a.onChange,value:a.value,children:[e.jsx(Ge,{children:e.jsx(Se,{className:"h-11","data-testid":"select-campaign-workflow",children:e.jsx(Ie,{placeholder:"Select workflow"})})}),e.jsx(Te,{children:Fe==null?void 0:Fe.map(i=>e.jsx(K,{value:i.id.toString(),children:i.name},i.id))})]}),e.jsx(Ke,{})]})}),!P&&e.jsx(We,{control:Y.control,name:"contentGenerationLevel",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Ge,{children:e.jsx(Vi,{value:a.value,onChange:a.onChange})}),e.jsx(Ke,{})]})}),e.jsx(We,{control:Y.control,name:"name",render:({field:a})=>e.jsxs(He,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Campaign Name"}),!P&&A&&!$&&e.jsxs(z,{variant:"secondary",className:"text-xs",children:[e.jsx(Je,{className:"h-3 w-3 mr-1"}),"Auto-generated"]}),!P&&$&&e.jsxs(z,{variant:"outline",className:"text-xs",children:[e.jsx(ni,{className:"h-3 w-3 mr-1"}),"Custom"]})]}),e.jsx(Ge,{children:e.jsx(Pe,{...a,placeholder:"Enter campaign name",className:"h-11",onChange:i=>{if(a.onChange(i),!P){const g=i.target.value;g!==A&&g!==""&&ie(!0)}},"data-testid":"input-campaign-name"})}),e.jsx(Ke,{})]})}),e.jsx(We,{control:Y.control,name:"description",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Description (Optional)"}),e.jsx(Ge,{children:e.jsx(Na,{...a,placeholder:"Describe your campaign",rows:3,"data-testid":"textarea-campaign-description"})}),e.jsx(Ke,{})]})}),e.jsx(We,{control:Y.control,name:"deploymentStatus",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Deployment Status"}),e.jsxs(Ce,{onValueChange:a.onChange,value:a.value,children:[e.jsx(Ge,{children:e.jsx(Se,{className:"h-11","data-testid":"select-deployment-status",children:e.jsx(Ie,{})})}),e.jsxs(Te,{children:[e.jsx(K,{value:"draft",children:"Draft"}),e.jsx(K,{value:"review",children:"Under Review"}),e.jsx(K,{value:"approved",children:"Approved"}),e.jsx(K,{value:"live",children:"Live"}),e.jsx(K,{value:"paused",children:"Paused"}),e.jsx(K,{value:"completed",children:"Completed"})]})]}),e.jsx(Ke,{})]})}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-3 sm:gap-2 pt-4",children:e.jsx(V,{type:"submit",disabled:ra.isPending||la.isPending,className:"w-full sm:w-auto h-11 sm:h-10","data-testid":"button-save-campaign",children:ra.isPending||la.isPending?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),P?"Updating...":"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2"}),P?"Update Campaign":"Create Campaign"]})})})]})})})})]})}),P&>&&Ue&&e.jsx(Kt,{open:D,onOpenChange:I,children:e.jsxs(ae,{className:"mb-4 sm:mb-6",children:[e.jsx(ye,{className:"pb-3 sm:pb-6",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(Ne,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(It,{className:"h-4 w-4 sm:h-5 sm:w-5 text-yellow-500"}
26),"Social Proof Selection"]}),e.jsx(et,{className:"text-sm mt-1",children:D?"Select customer reviews to include in your campaign for maximum impact":Q.length>0?`${Q.length} review${Q.length!==1?"s":""} selected`:"Add customer testimonials to build trust"})]}),e.jsx(Qt,{asChild:!0,children:e.jsxs(V,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:[e.jsx(Pt,{className:`h-4 w-4 transition-transform duration-200 ${D?"transform rotate-180":""}`}),e.jsx("span",{className:"sr-only",children:"Toggle review selector"})]})})]})}),e.jsx(Jt,{children:e.jsx(me,{children:e.jsx(Xi,{serviceId:gt,selectedReviews:Q,onReviewsChange:T,temperature:Gs(),maxSelections:5})})})]})}),P&&Ue&&de&&de.length>0&&e.jsxs(ae,{className:"mb-4 sm:mb-6",children:[e.jsx(ye,{className:"pb-3 sm:pb-6",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx($a,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-500"}),"Workflow Steps"]}),e.jsx(V,{variant:"ghost",size:"sm",onClick:Ws,className:"h-7 px-2","data-testid":"button-toggle-view-mode",children:F==="list"?e.jsxs(e.Fragment,{children:[e.jsx(Ms,{className:"h-4 w-4 mr-1"}),"By Temp"]}):e.jsxs(e.Fragment,{children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"List"]})})]})})}),e.jsx(et,{className:"text-sm",children:F==="list"?"Click on a step to create content - organized by sequence":"Steps organized by temperature level - click to edit content"}),P&&Ta()>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 pt-1",children:[e.jsx(V,{onClick:en,disabled:m,size:"sm",className:"w-full sm:w-auto","data-testid":"button-generate-all-empty",children:m?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),r.current,"/",r.total]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-4 w-4 mr-2"}),"Generate All (",Ta(),")"]})}),m&&C&&e.jsxs("span",{className:"text-xs text-muted-foreground animate-pulse text-center sm:text-left",children:["Generating: ",C]})]})]})}),e.jsxs(me,{className:"pt-0",children:[P&&ze.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("button",{type:"button",onClick:()=>ut(a=>!a),className:"w-full flex items-center justify-between px-3 py-2.5 rounded-lg border border-orange-200 bg-orange-50 dark:bg-orange-950/30 dark:border-orange-800 hover:bg-orange-100 dark:hover:bg-orange-950/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm font-semibold text-orange-700 dark:text-orange-300",children:"Campaign Narrative Flow"}),e.jsxs(z,{className:"text-xs bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300 border-orange-300 dark:border-orange-700",children:[ze.length," step",ze.length!==1?"s":""]})]}),tt?e.jsx(In,{className:"h-4 w-4 text-orange-500"}):e.jsx(Pt,{className:"h-4 w-4 text-orange-500"})]}),tt&&(()=>{const a={cold:{label:"Cold",color:"text-blue-700 dark:text-blue-300",bg:"bg-blue-50",border:"border-blue-200",darkBg:"dark:bg-blue-950/30",darkBorder:"dark:border-blue-800"},warm:{label:"Warm",color:"text-yellow-700 dark:text-yellow-300",bg:"bg-yellow-50",border:"border-yellow-200",darkBg:"dark:bg-yellow-950/30",darkBorder:"dark:border-yellow-800"},hot:{label:"Hot",color:"text-red-700 dark:text-red-300",bg:"bg-red-50",border:"border-red-200",darkBg:"dark:bg-red-950/30",darkBorder:"dark:border-red-800"},existing:{label:"Existing Customers",color:"text-purple-700 dark:text-purple-300",bg:"bg-purple-50",border:"border-purple-200",darkBg:"dark:bg-purple-950/30",darkBorder:"dark:border-purple-800"}},i=["cold","warm","hot","existing"],g={};return ze.forEach(j=>{const w=j.temperature||"warm";g[w]||(g[w]=[]),g[w].push(j)}),e.jsxs("div",{className:"mt-2 space-y-3 p-3 border border-orange-100 dark:border-orange-900/50 rounded-lg bg-white dark:bg-gray-900",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click any step to jump to it and review its content."}),i.filter(j=>{var w;return((w=g[j])==null?void 0:w.length)>0}).map(j=>{const w=a[j]||a.warm;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("span",{className:`text-xs font-bold uppercase tracking-wide ${w.color}`,children:w.label}),e.jsx("div",{className:"flex-1 h-px bg-current opacity-20"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2",children:g[j].map(L=>{const W=de.find(re=>
26re.id===L.stepId);return e.jsxs("div",{onClick:()=>{W&&(ia(W),L.content&&Object.keys(L.content).length>0&&s.setValue("platformContent",L.content,{shouldDirty:!1}))},className:`p-2.5 rounded-md border cursor-pointer transition-all hover:shadow-sm ${w.bg} ${w.border} ${w.darkBg} ${w.darkBorder}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("span",{className:`text-xs font-semibold ${w.color} truncate flex-1`,children:L.stepName}),e.jsx(z,{variant:"outline",className:"text-xs px-1 py-0 shrink-0 h-4",children:St(L.platform)})]}),L.content.headline&&e.jsx("p",{className:"text-xs font-medium text-gray-800 dark:text-gray-200 line-clamp-1 mb-0.5",children:Lt(L.content.headline)}),L.content.primaryText&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 line-clamp-2",children:Lt(L.content.primaryText)})]},L.stepId)})})]},j)})]})})()]}),F==="list"?e.jsx("div",{className:"space-y-2",children:de.map((a,i)=>{const g=wt(a.id);return e.jsx("div",{onClick:()=>ia(a),className:` 27 p-3 rounded-lg border cursor-pointer transition-all duration-200 28 hover:shadow-sm touch-manipulation 29 ${(t==null?void 0:t.id)===a.id?"border-blue-200 bg-blue-50 dark:bg-blue-900/20 dark:border-blue-800":"border-gray-200 dark:border-gray-700 hover:border-blue-200 dark:hover:border-blue-800"} 30 `,"data-testid":`workflow-step-${a.id}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 sm:w-6 sm:h-6 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-xs font-medium text-blue-600 dark:text-blue-400",children:i+1})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium text-sm sm:text-base text-gray-900 dark:text-white truncate",children:a.name}),P&&e.jsx(z,{variant:g.status==="complete"?"default":g.status==="partial"?"secondary":"outline",className:`text-xs px-1.5 py-0.5 ${g.status==="complete"?"bg-green-100 text-green-700 border-green-300":g.status==="partial"?"bg-yellow-100 text-yellow-700 border-yellow-300":"bg-gray-100 text-gray-600 border-gray-300"}`,children:g.status==="empty"?"Empty":g.status==="complete"?"Complete":`${g.filled}/${g.total}`})]}),a.description&&e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate",children:a.description})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 flex-shrink-0",children:[e.jsx(z,{variant:"outline",className:"text-xs px-1.5 py-0.5",children:St(a.platform)}),a.temperature&&e.jsx(z,{variant:"secondary",className:"text-xs px-1.5 py-0.5 hidden sm:inline-flex",children:a.temperature})]})]})},a.id)})}):e.jsx(An,{type:"multiple",defaultValue:["cold","warm","hot","existing"],className:"w-full",children:(()=>{const a=Hs();return[{key:"cold",label:"âï¸ Cold Audience",color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-50 dark:bg-blue-900/20"},{key:"warm",label:"ð¡ï¸ Warm Audience",color:"text-orange-600 dark:text-orange-400",bgColor:"bg-orange-50 dark:bg-orange-900/20"},{key:"hot",label:"ð¥ Hot Audience",color:"text-red-600 dark:text-red-400",bgColor:"bg-red-50 dark:bg-red-900/20"},{key:"existing",label:"ð¤ Existing Customers",color:"text-green-600 dark:text-green-400",bgColor:"bg-green-50 dark:bg-green-900/20"},{key:"unassigned",label:"â Unassigned",color:"text-gray-600 dark:text-gray-400",bgColor:"bg-gray-50 dark:bg-gray-900/20"}].map(({key:g,label:j,color:w,bgColor:L})=>{const W=a[g];if(W.length===0)return null;const re=["cold","warm","hot","existing"].includes(g)&&P,ne=m&&p===g,B={cold:"âï¸ Generate Cold",warm:"ð¡ï¸ Generate Warm",hot:"ð¥ Generate Hot",existing:"ð¤ Generate Existing"};return e.jsxs(Pn,{value:g,"data-testid":`accordion-temperature-${g}`,children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ln,{className:"flex-1 hover:no-underline py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`font-medium ${w}`,children:j}),e.jsxs(z,{variant:"secondary",children:[W.length," ",W.length===1?"step":"steps"]})]})}),re&&e.jsx(V,{type:"button",size:"sm",variant:"outline",onClick:Z=>{Z.stopPropagation(),Fa(g)},disabled:m,className:"h-7 text-xs px-2 shrink-0 mr-1",children:ne?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-3 w-3 mr-1 animate-spin"}),"Generatingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"h-3 w-3 mr-1"}),B[g]||"Generate"]})})]}),e.jsx(Mn,{children:e.jsx("div",{className:"space-y-2 pt-2","data-testid":`temperature-content-${g}`,children:(()=>{const pe={cold:{levels:["problem_unaware","solution_unaware"],labels:{problem_unaware:{icon:"âï¸",label:"Problem Unaware",color:"text-blue-700 dark:text-blue-300"},solution_unaware:{icon:"ð§",label:"Solution Unaware",color:"text-cyan-700 dark:text-cyan-300"}}}
30,warm:{levels:["solution_aware","your_solution_aware"],labels:{solution_aware:{icon:"ð¡ï¸",label:"Solution Aware",color:"text-orange-700 dark:text-orange-300"},your_solution_aware:{icon:"ð¥",label:"Your Solution Aware",color:"text-red-600 dark:text-red-400"}}}}[g];let Me=0;if(!pe)return W.map(ve=>{Me++;const Be=wt(ve.id);return na(ve,Be,Me,L)});const ue={};return pe.levels.forEach(ve=>{ue[ve]=[]}),ue.other=[],W.forEach(ve=>{var _e;const Be=((_e=ve.awarenessLevel)==null?void 0:_e.toLowerCase())||"";pe.levels.includes(Be)?ue[Be].push(ve):ue.other.push(ve)}),e.jsxs(e.Fragment,{children:[pe.levels.map(ve=>{const Be=ue[ve];if(Be.length===0)return null;const _e=pe.labels[ve];return e.jsxs("div",{className:"mb-3","data-testid":`awareness-group-${ve}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 py-1 border-b border-gray-200 dark:border-gray-700",children:[e.jsx("span",{className:"text-sm",children:_e.icon}),e.jsx("span",{className:`text-xs font-medium ${_e.color}`,children:_e.label}),e.jsxs(z,{variant:"outline",className:"text-xs px-1 py-0 ml-auto",children:[Be.length," ",Be.length===1?"step":"steps"]})]}),e.jsx("div",{className:"space-y-2 pl-2",children:Be.map(Ot=>{Me++;const Ra=wt(Ot.id);return na(Ot,Ra,Me,L)})})]},ve)}),ue.other.length>0&&e.jsxs("div",{className:"mb-3","data-testid":"awareness-group-other",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 py-1 border-b border-gray-200 dark:border-gray-700",children:[e.jsx("span",{className:"text-sm",children:"ð"}),e.jsx("span",{className:"text-xs font-medium text-gray-600 dark:text-gray-400",children:"Other Steps"}),e.jsxs(z,{variant:"outline",className:"text-xs px-1 py-0 ml-auto",children:[ue.other.length," ",ue.other.length===1?"step":"steps"]})]}),e.jsx("div",{className:"space-y-2 pl-2",children:ue.other.map(ve=>{Me++;const Be=wt(ve.id);return na(ve,Be,Me,L)})})]})]})})()})})]},g)})})()})]})]}),P&&h&&de&&de.length>0&&e.jsxs(ae,{className:"mb-6",children:[e.jsx(ye,{className:"pb-3 sm:pb-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ne,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(Ua,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-500"}),"Budget & Allocation"]}),e.jsx(et,{className:"text-sm",children:"Manage budget allocation across platforms and temperature levels"})]}),e.jsxs(V,{onClick:Ys,variant:c==="budget"?"default":"outline",className:"h-9 sm:h-10 text-sm","data-testid":"button-budget-campaign",children:[e.jsx(Ua,{className:"w-4 h-4 mr-2"}),"Budget"]})]})}),e.jsx(me,{className:"pt-0",children:e.jsx("div",{className:"text-center py-4",children:e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:'Click "Budget" to allocate spending across your campaign steps and platforms.'})})})]}),P&&h&&de&&de.length>0&&e.jsxs(ae,{children:[e.jsx(ye,{className:"pb-3 sm:pb-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ne,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(qe,{className:"w-4 h-4 sm:w-5 sm:h-5 text-orange-500"}),"Schedule Campaign"]}),e.jsx(et,{className:"text-sm",children:"Schedule your campaign content across social platforms"})]}),e.jsxs(V,{onClick:La,variant:c==="scheduling"?"default":"outline",className:"h-9 sm:h-10 text-sm","data-testid":"button-schedule-campaign",children:[e.jsx(qe,{className:"w-4 h-4 mr-2"}),"Schedule"]})]})}),e.jsx(me,{className:"pt-0",children:e.jsxs("div",{className:"text-center py-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{className:"w-4 h-4 text-green-500"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[de.length," steps ready"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Ready to schedule"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:'Click "Schedule" to set up posting times and platforms for your campaign content.'}),e.jsxs(V,{onClick:La,size:"sm",className:"w-full sm:w-auto","data-testid":"button-open-scheduling",children:[e.jsx(qe,{className:"w-4 h-4 mr-2"}),"Open Campaign Scheduler"]})]})})]})]})}),e.jsxs("div",{className:"hidden md:block w-1/2 bg-gray-50 dark:bg-gray-900 overflow-y-auto",children:[c==="step"&&t&&P&&E&&e.jsx("div",{className:"p-6",children:e.jsxs(ae,{children:[e.jsxs(ye,{children:[e.jsxs(Ne,{className:"flex items-center gap-2",children:[e.jsxs("span",{children:["Create Content for ",t.name]}),e.jsx(z,{variant:"outline",className:"text-xs",children:St(t.platform)})]}),t.description&&e.jsx(et,{children:t.description})]}),e.jsx(me,{children:e.jsx(ca,{...s,children:e.jsxs("form",{onSubmit:s.handleSubmit(Ma),className:"space-y-6",children:[(()=>{const a=s.watch("configuration");console.log("ð¨ Rendering PlatformContentForm:",{stepId:t.id,platform:t.platform,hasConfiguration:!!a,configKeys:a?Object.keys(a):[],temperature:s.watch("temperature"),awarenessLevel:s.watch("awarenessLevel")});const i=Ns(t.platform)?e.jsx(o.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center p-8 bg-gray-100 dark:bg-gray-800 rounded-lg",children:e.jsx(De,{className:"h-8 w-8 animate-spin text-orange-500"})}),children:(()=>{const g=ks(t.platform);return g?e.jsx(g,{register:s.register,control:s.control,setValue:s.setValue,wat
30ch:s.watch,businessProfile:ee}):null})()}):void 0;return e.jsx(as,{platformType:t.platform,register:s.register,control:s.control,setValue:s.setValue,watch:s.watch,errors:s.formState.errors,campaignId:E,stepId:t.id,avatarData:Ze,offerData:zt,businessProfile:ee,serviceId:gt,temperature:s.watch("temperature"),awarenessLevel:s.watch("awarenessLevel"),configuration:a,mockupComponent:i,previousStepsContent:Da})})(),e.jsx(We,{control:s.control,name:"destinationUrl",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{children:"Destination URL"}),e.jsx(Ge,{children:e.jsx(Pe,{...a,placeholder:"https://example.com",type:"url"})}),e.jsx(Ke,{})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{children:"Media Assets"}),e.jsx(ja,{value:s.watch("mediaUrl"),onChange:a=>s.setValue("mediaUrl",a||""),label:"Select Media",placeholder:"Choose image or video from library",mediaType:"all",serviceId:gt,platformType:t==null?void 0:t.platform,temperature:s.watch("temperature"),className:"w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select media assets to include with this campaign step"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(V,{type:"button",variant:"outline",onClick:()=>{n(null),l(null),s.reset()},children:"Cancel"}),e.jsx(V,{type:"button",variant:"outline",onClick:Ea,disabled:M||m,"data-testid":"button-regenerate-step",children:M?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),"Regenerating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"h-4 w-4 mr-2"}),"Regenerate Step"]})}),e.jsx(V,{type:"submit",disabled:_t.isPending,children:_t.isPending?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2"}),"Save Content"]})})]})]})})})]})}),c==="scheduling"&&h&&e.jsx("div",{className:"p-6",children:e.jsx(Ti,{campaign:h,workflowSteps:de,onScheduleComplete:Zs})}),c==="budget"&&h&&e.jsx("div",{className:"p-6",children:e.jsx(Oi,{campaign:h,workflowSteps:de,onBudgetUpdate:a=>{R(a),console.log("Budget data updated:",a),ce({title:"Budget Allocated",description:`Campaign budget of $${a.totalBudget} has been allocated.`})},initialBudget:(d==null?void 0:d.totalBudget)||h.estimatedBudget||1500})}),!c&&e.jsx("div",{className:"flex items-center justify-center h-full p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx($a,{className:"h-12 w-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 mb-2 font-medium",children:"No Step Selected"}),e.jsx("p",{className:"text-sm text-gray-400",children:'Select a workflow step from the left panel to create content, or click "Schedule" to set up your campaign timeline.'})]})})]}),e.jsx(Dn,{open:u,onOpenChange:x,children:e.jsxs(En,{side:"bottom",className:"h-[90vh] px-4 py-6 overflow-y-auto",children:[e.jsxs(Fn,{className:"mb-6",children:[e.jsxs(Bn,{className:"text-left flex items-center gap-2",children:[e.jsxs("span",{children:["Create Content for ",t==null?void 0:t.name]}),t&&e.jsx(z,{variant:"outline",className:"text-xs",children:St(t.platform)})]}),(t==null?void 0:t.description)&&e.jsx(Rn,{className:"text-left",children:t.description})]}),t&&P&&E&&e.jsx(ca,{...s,children:e.jsxs("form",{onSubmit:s.handleSubmit(Ma),className:"space-y-6",children:[(()=>{const a=Ns(t.platform)?e.jsx(o.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center p-8 bg-gray-100 dark:bg-gray-800 rounded-lg",children:e.jsx(De,{className:"h-8 w-8 animate-spin text-orange-500"})}),children:(()=>{const g=ks(t.platform);return g?e.jsx(g,{register:s.register,control:s.control,setValue:s.setValue,wat
30ch:s.watch,businessProfile:ee}):null})()}):void 0,i=s.watch("configuration");return e.jsx(as,{platformType:t.platform,register:s.register,control:s.control,setValue:s.setValue,watch:s.watch,errors:s.formState.errors,campaignId:E,stepId:t.id,avatarData:Ze,offerData:zt,businessProfile:ee,serviceId:gt,temperature:s.watch("temperature"),awarenessLevel:s.watch("awarenessLevel"),configuration:i,mockupComponent:a,previousStepsContent:Da})})(),e.jsx(We,{control:s.control,name:"destinationUrl",render:({field:a})=>e.jsxs(He,{children:[e.jsx(Xe,{className:"text-sm font-medium",children:"Destination URL"}),e.jsx(Ge,{children:e.jsx(Pe,{...a,placeholder:"https://example.com",type:"url",className:"h-11","data-testid":"input-step-destination-url"})}),e.jsx(Ke,{})]})}),e.jsxs("div",{className:"flex flex-col gap-3 pt-6 border-t",children:[e.jsx(V,{type:"submit",className:"w-full h-11 text-sm","data-testid":"button-save-step-mobile",disabled:_t.isPending,children:_t.isPending?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2"}),"Save Content"]})}),e.jsx(V,{type:"button",variant:"outline",onClick:Ea,disabled:M||m,className:"w-full h-11 text-sm","data-testid":"button-regenerate-step-mobile",children:M?e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2 animate-spin"}),"Regenerating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"h-4 w-4 mr-2"}),"Regenerate Step"]})}),e.jsx(V,{type:"button",variant:"outline",onClick:()=>{x(!1),n(null),l(null),s.reset()},className:"w-full h-11 text-sm","data-testid":"button-cancel-step-mobile",children:"Cancel"})]})]})})]})})]})}const Br=Object.freeze(Object.defineProperty({__proto__:null,default:ar},Symbol.toStringTag,{value:"Module"}));export{ua as F,Ya as S,Br as c};
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.